Crucial® DDR4 Server Memory - Farnell Element 14
- Revenir à l'accueil
Farnell Element 14 :
See the trailer for the next exciting episode of The Ben Heck show. Check back on Friday to be among the first to see the exclusive full show on element…
Connect your Raspberry Pi to a breadboard, download some code and create a push-button audio play project.
Puce électronique / Microchip :
Sans fil - Wireless :
Texas instrument :
Ordinateurs :
Logiciels :
Tutoriels :
Autres documentations :
Farnell-CLRC632-NXP-..> 20-Dec-2014 10:22 2.6M
Farnell-7491181012-O..> 20-Dec-2014 10:22 2.6M
Farnell-LPC4350-30-2..> 20-Dec-2014 10:21 1.4M
Farnell-LPC178x-7x-N..> 20-Dec-2014 10:21 1.6M
Farnell-Data-Sheet-J..> 20-Dec-2014 10:21 1.0M
Farnell-LPC81xM-NXP-..> 20-Dec-2014 10:20 1.2M
Farnell-Data-Sheet-J..> 20-Dec-2014 10:20 1.2M
Farnell-SL3S1003_101..> 20-Dec-2014 10:06 2.0M
Farnell-NT3H1101-NT3..> 20-Dec-2014 10:06 2.3M
Farnell-LPC1769-68-6..> 20-Dec-2014 10:06 2.2M
Farnell-SL3S1203_121..> 20-Dec-2014 10:01 2.0M
Farnell-PN512-NXP-Se..> 20-Dec-2014 10:01 1.9M
Farnell-MMBZxVCL-MMB..> 20-Dec-2014 09:53 1.6M
Farnell-Datasheet-NX..> 20-Dec-2014 09:52 1.6M
Farnell-IP4251_52_53..> 20-Dec-2014 09:51 1.6M
Farnell-BC846DS2-NXP..> 20-Dec-2014 09:48 1.2M
Farnell-BAT54J-Schot..> 20-Dec-2014 09:47 1.1M
Farnell-PMEG3010EP-N..> 20-Dec-2014 09:47 1.1M
Farnell-AVR172-Senso..> 20-Dec-2014 09:47 1.2M
Farnell-PBSS5320X-NX..> 20-Dec-2014 09:47 1.6M
Farnell-ATtiny2313-A..> 20-Dec-2014 09:47 1.6M
Farnell-SG2525A-SG35..> 20-Dec-2014 09:39 1.0M
Farnell-PMBT3906-PNP..> 20-Dec-2014 09:39 1.0M
Farnell-PDTB123TT-NX..> 20-Dec-2014 09:39 1.0M
Farnell-PIC12F529T39..> 20-Dec-2014 09:39 1.0M
Farnell-PSMN011-80YS..> 20-Dec-2014 09:39 1.1M
Farnell-PESD5V0F1BL-..> 20-Dec-2014 09:39 1.1M
Farnell-MB85RS128B-F..> 20-Dec-2014 09:38 1.1M
Farnell-SMAJ-STMicro..> 13-Oct-2014 07:07 734K
Farnell-L6562-STMicr..> 13-Oct-2014 07:07 754K
Farnell-LM139-LM239-..> 13-Oct-2014 07:07 771K
Farnell-L4978-STMicr..> 13-Oct-2014 07:07 783K
Farnell-ST1S10PHR-ST..> 13-Oct-2014 07:06 820K
Farnell-TIP41C-TIP42..> 13-Oct-2014 07:06 829K
Farnell-MC34063ABD-T..> 13-Oct-2014 07:06 844K
Farnell-ESM6045DV-ST..> 13-Oct-2014 07:06 850K
Farnell-TIP102-TIP10..> 13-Oct-2014 07:06 853K
Farnell-ST3232B-ST32..> 13-Oct-2014 07:06 867K
Farnell-STM32F030x4-..> 13-Oct-2014 07:06 1.1M
Farnell-STM32F103x8-..> 13-Oct-2014 07:06 1.0M
Farnell-STM32F405xx-..> 13-Oct-2014 07:05 1.4M
Farnell-STM32F205xx-..> 13-Oct-2014 07:05 1.7M
Farnell-STP16NF06L-n..> 13-Oct-2014 07:05 1.7M
Farnell-STP80NF55L-0..> 13-Oct-2014 07:05 1.7M
Farnell-LM217-LM317-..> 13-Oct-2014 07:04 1.7M
Farnell-LM2904-LM290..> 13-Oct-2014 07:04 1.7M
Farnell-L78-Positive..> 13-Oct-2014 07:04 1.8M
Farnell-VND920P-E-ST..> 13-Oct-2014 07:04 1.8M
Farnell-LM350-STMicr..> 13-Oct-2014 07:03 1.8M
Smart_street_lightin..> 13-Oct-2014 07:03 1.6M
Farnell-Smart-street..> 13-Oct-2014 07:02 1.8M
Farnell-ULN2001-ULN2..> 13-Oct-2014 07:02 1.9M
Farnell-ULQ2001-ULQ2..> 13-Oct-2014 07:02 1.9M
Farnell-L6384E-STMic..> 13-Oct-2014 07:02 1.9M
Farnell-AN2794-Appli..> 13-Oct-2014 07:01 1.0M
Farnell-STEVAL-TDR02..> 13-Oct-2014 07:01 960K
Farnell-TL084-TL084A..> 11-Oct-2014 15:54 1.7M
Farnell-TDA7296-STMi..> 11-Oct-2014 15:54 1.7M
Farnell-L78-STMicroe..> 11-Oct-2014 15:49 1.6M
Farnell-LM158-LM258-..> 11-Oct-2014 15:49 1.6M
Farnell-LF351-STMicr..> 11-Oct-2014 15:49 1.7M
Farnell-L293B-STMicr..> 11-Oct-2014 15:49 1.7M
Farnell-NE556-SA556-..> 11-Oct-2014 15:48 1.7M
Farnell-SO967460-PDF..> 11-Oct-2014 12:05 2.9M
Farnell-Everything-Y..> 11-Oct-2014 12:05 1.5M
cookiechoices.js 27-Sep-2014 12:40 6.0K
Farnell-ULN2803A-Rev..> 09-Sep-2014 19:26 2.9M
Analog-Devices-Convo..> 09-Sep-2014 08:26 2.1M
Analog-Devices-Convo..> 09-Sep-2014 08:25 2.2M
Analog-Devices-Convo..> 09-Sep-2014 08:25 2.2M
Analog-Devices-ADMC4..> 09-Sep-2014 08:23 2.3M
Analog-Devices-Wi-Fi..> 09-Sep-2014 08:23 2.3M
Analog-Devices-ADMC2..> 09-Sep-2014 08:21 2.4M
Analog-Devices-ADC-S..> 09-Sep-2014 08:21 2.4M
Analog-Devices-Visua..> 09-Sep-2014 08:18 2.5M
Analog-Devices-ANF32..> 09-Sep-2014 08:18 2.6M
Farnell-Compensating..> 09-Sep-2014 08:16 2.6M
Farnell-Compensating..> 09-Sep-2014 08:16 2.6M
Farnell-LM7805-Fairc..> 09-Sep-2014 08:13 2.7M
Farnell-AD620-Rev-H-..> 09-Sep-2014 08:13 2.6M
Farnell-Datasheet-FT..> 09-Sep-2014 08:10 2.8M
Farnell-MAX4661-MAX4..> 09-Sep-2014 08:10 2.8M
Farnell-OPA627-Texas..> 09-Sep-2014 08:08 2.8M
Farnell-REF19x-Serie..> 09-Sep-2014 08:08 2.8M
Farnell-Data-Sheet-M..> 09-Sep-2014 08:05 2.8M
Analog-Devices-Digit..> 08-Sep-2014 18:03 2.0M
Analog-Devices-Digit..> 08-Sep-2014 18:02 2.1M
Analog-Devices-Basic..> 08-Sep-2014 17:49 1.9M
Farnell-AD9833-Rev-E..> 08-Sep-2014 17:49 1.8M
Farnell-The-Discrete..> 08-Sep-2014 17:44 1.8M
Electronique-Basic-o..> 08-Sep-2014 17:43 1.8M
Analog-Devices-AN300..> 08-Sep-2014 17:42 2.0M
Analog-Devices-The-C..> 08-Sep-2014 17:41 1.9M
Analog-Devices-Intro..> 08-Sep-2014 17:39 1.9M
Analog-Devices-Compl..> 08-Sep-2014 17:38 2.0M
Analog-Devices-Gloss..> 08-Sep-2014 17:36 2.0M
Farnell-ADuM1300-ADu..> 08-Sep-2014 08:11 1.7M
Farnell-AD586BRZ-Ana..> 08-Sep-2014 08:09 1.6M
Farnell-ADuM1200-ADu..> 08-Sep-2014 08:09 1.6M
Farnell-NA555-NE555-..> 08-Sep-2014 07:51 1.5M
Farnell-AD9834-Rev-D..> 08-Sep-2014 07:32 1.2M
Farnell-MSP430F15x-M..> 08-Sep-2014 07:32 1.3M
Farnell-AD736-Rev-I-..> 08-Sep-2014 07:31 1.3M
Farnell-AD8307-Data-..> 08-Sep-2014 07:30 1.3M
Farnell-Single-Chip-..> 08-Sep-2014 07:30 1.5M
Farnell-Quadruple-2-..> 08-Sep-2014 07:29 1.5M
Farnell-ADE7758-Rev-..> 08-Sep-2014 07:28 1.7M
Farnell-MAX3221-Rev-..> 08-Sep-2014 07:28 1.8M
Farnell-USB-to-Seria..> 08-Sep-2014 07:27 2.0M
Farnell-AD8313-Analo..> 08-Sep-2014 07:26 2.0M
Farnell-SN54HC164-SN..> 08-Sep-2014 07:25 2.0M
Farnell-AD8310-Analo..> 08-Sep-2014 07:24 2.1M
Farnell-AD8361-Rev-D..> 08-Sep-2014 07:23 2.1M
Farnell-2N3906-Fairc..> 08-Sep-2014 07:22 2.1M
Farnell-AD584-Rev-C-..> 08-Sep-2014 07:20 2.2M
Farnell-ADE7753-Rev-..> 08-Sep-2014 07:20 2.3M
Farnell-TLV320AIC23B..> 08-Sep-2014 07:18 2.4M
Farnell-STM32F405xxS..> 27-Aug-2014 18:27 1.8M
Farnell-fx-3650P-fx-..> 29-Jul-2014 10:42 1.5M
Farnell-MSP430-Hardw..> 29-Jul-2014 10:36 1.1M
Farnell-LM324-Texas-..> 29-Jul-2014 10:32 1.5M
Farnell-LM386-Low-Vo..> 29-Jul-2014 10:32 1.5M
Farnell-NE5532-Texas..> 29-Jul-2014 10:32 1.5M
Farnell-Hex-Inverter..> 29-Jul-2014 10:31 875K
Farnell-AT90USBKey-H..> 29-Jul-2014 10:31 902K
Farnell-AT89C5131-Ha..> 29-Jul-2014 10:31 1.2M
Farnell-MSP-EXP430F5..> 29-Jul-2014 10:31 1.2M
Farnell-Explorer-16-..> 29-Jul-2014 10:31 1.3M
Farnell-TMP006EVM-Us..> 29-Jul-2014 10:30 1.3M
Farnell-Gertboard-Us..> 29-Jul-2014 10:30 1.4M
Farnell-LMP91051-Use..> 29-Jul-2014 10:30 1.4M
Farnell-Thermometre-..> 29-Jul-2014 10:30 1.4M
Farnell-user-manuel-..> 29-Jul-2014 10:29 1.5M
Farnell-TLV320AIC325..> 28-Jul-2014 17:45 2.9M
Farnell-2-GBPS-Diffe..> 28-Jul-2014 17:42 2.7M
Farnell-LMT88-2.4V-1..> 28-Jul-2014 17:42 2.8M
Farnell-Octal-Genera..> 28-Jul-2014 17:42 2.8M
Farnell-Dual-MOSFET-..> 28-Jul-2014 17:41 2.8M
Farnell-SN54LV4053A-..> 28-Jul-2014 17:20 5.9M
Farnell-TAS1020B-USB..> 28-Jul-2014 17:19 6.2M
Farnell-TPS40060-Wid..> 28-Jul-2014 17:19 6.3M
Farnell-TL082-Wide-B..> 28-Jul-2014 17:16 6.3M
Farnell-RF-short-tra..> 28-Jul-2014 17:16 6.3M
Farnell-maxim-integr..> 28-Jul-2014 17:14 6.4M
Farnell-TSV6390-TSV6..> 28-Jul-2014 17:14 6.4M
Farnell-Fast-Charge-..> 28-Jul-2014 17:12 6.4M
Farnell-NVE-datashee..> 28-Jul-2014 17:12 6.5M
Farnell-Excalibur-Hi..> 28-Jul-2014 17:10 2.4M
Farnell-Excalibur-Hi..> 28-Jul-2014 17:10 2.4M
Farnell-REF102-10V-P..> 28-Jul-2014 17:09 2.4M
Farnell-TMS320F28055..> 28-Jul-2014 17:09 2.7M
Farnell-ULINKpro-Deb..> 25-Jul-2014 12:35 5.9M
Farnell-WIRE-WRAP-50..> 25-Jul-2014 12:34 5.9M
Farnell-MICROCHIP-PI..> 25-Jul-2014 12:34 6.7M
Farnell-OMRON-INDUST..> 25-Jul-2014 12:32 6.9M
Farnell-OMRON-INDUST..> 25-Jul-2014 12:31 6.9M
Farnell-TYCO-ELECTRO..> 25-Jul-2014 12:30 6.9M
Farnell-Power-suppli..> 25-Jul-2014 12:29 7.0M
Farnell-Schroff-A108..> 25-Jul-2014 12:27 2.8M
Farnell-Schroff-Main..> 25-Jul-2014 12:26 2.9M
Farnell-Schroff-mult..> 25-Jul-2014 12:26 2.9M
Farnell-Quick-Start-..> 25-Jul-2014 12:25 3.0M
Farnell-PiFace-Digit..> 25-Jul-2014 12:25 3.0M
Farnell-PicoScope-se..> 25-Jul-2014 12:24 3.0M
Farnell-Trust-Digita..> 25-Jul-2014 12:24 3.0M
Farnell-Jeu-multi-la..> 25-Jul-2014 12:23 3.0M
Farnell-PicoScope-42..> 25-Jul-2014 12:23 3.0M
Farnell-LD-WSECO16-P..> 25-Jul-2014 12:22 3.1M
Farnell-Circuit-Impr..> 25-Jul-2014 12:22 3.1M
Farnell-MULTICOMP-Ra..> 22-Jul-2014 12:57 5.9M
Farnell-RASPBERRY-PI..> 22-Jul-2014 12:35 5.9M
Farnell-Dremel-Exper..> 22-Jul-2014 12:34 1.6M
Farnell-STM32F103x8-..> 22-Jul-2014 12:33 1.6M
Farnell-BD6xxx-PDF.htm 22-Jul-2014 12:33 1.6M
Farnell-L78S-STMicro..> 22-Jul-2014 12:32 1.6M
Farnell-RaspiCam-Doc..> 22-Jul-2014 12:32 1.6M
Farnell-SB520-SB5100..> 22-Jul-2014 12:32 1.6M
Farnell-iServer-Micr..> 22-Jul-2014 12:32 1.6M
Farnell-LUMINARY-MIC..> 22-Jul-2014 12:31 3.6M
Farnell-TEXAS-INSTRU..> 22-Jul-2014 12:31 2.4M
Farnell-TEXAS-INSTRU..> 22-Jul-2014 12:30 4.6M
Farnell-CLASS 1-or-2..> 22-Jul-2014 12:30 4.7M
Farnell-TEXAS-INSTRU..> 22-Jul-2014 12:29 4.8M
Farnell-Evaluating-t..> 22-Jul-2014 12:28 4.9M
Farnell-LM3S6952-Mic..> 22-Jul-2014 12:27 5.9M
Farnell-Keyboard-Mou..> 22-Jul-2014 12:27 5.9M
Farnell-0050375063-D..> 18-Jul-2014 17:03 2.5M
Farnell-Mini-Fit-Jr-..> 18-Jul-2014 17:03 2.5M
Farnell-43031-0002-M..> 18-Jul-2014 17:03 2.5M
Farnell-0433751001-D..> 18-Jul-2014 17:02 2.5M
Farnell-Cube-3D-Prin..> 18-Jul-2014 17:02 2.5M
Farnell-MTX-Compact-..> 18-Jul-2014 17:01 2.5M
Farnell-MTX-3250-MTX..> 18-Jul-2014 17:01 2.5M
Farnell-ATtiny26-L-A..> 18-Jul-2014 17:00 2.6M
Farnell-MCP3421-Micr..> 18-Jul-2014 17:00 1.2M
Farnell-LM19-Texas-I..> 18-Jul-2014 17:00 1.2M
Farnell-Data-Sheet-S..> 18-Jul-2014 17:00 1.2M
Farnell-LMH6518-Texa..> 18-Jul-2014 16:59 1.3M
Farnell-AD7719-Low-V..> 18-Jul-2014 16:59 1.4M
Farnell-DAC8143-Data..> 18-Jul-2014 16:59 1.5M
Farnell-BGA7124-400-..> 18-Jul-2014 16:59 1.5M
Farnell-SICK-OPTIC-E..> 18-Jul-2014 16:58 1.5M
Farnell-LT3757-Linea..> 18-Jul-2014 16:58 1.6M
Farnell-LT1961-Linea..> 18-Jul-2014 16:58 1.6M
Farnell-PIC18F2420-2..> 18-Jul-2014 16:57 2.5M
Farnell-DS3231-DS-PD..> 18-Jul-2014 16:57 2.5M
Farnell-RDS-80-PDF.htm 18-Jul-2014 16:57 1.3M
Farnell-AD8300-Data-..> 18-Jul-2014 16:56 1.3M
Farnell-LT6233-Linea..> 18-Jul-2014 16:56 1.3M
Farnell-MAX1365-MAX1..> 18-Jul-2014 16:56 1.4M
Farnell-XPSAF5130-PD..> 18-Jul-2014 16:56 1.4M
Farnell-DP83846A-DsP..> 18-Jul-2014 16:55 1.5M
Farnell-SL3ICS1002-1..> 16-Jul-2014 09:05 2.5M
Farnell-MCOC1-Farnel..> 16-Jul-2014 09:04 1.0M
Farnell-SL3S1203_121..> 16-Jul-2014 09:04 1.1M
Farnell-PN512-Full-N..> 16-Jul-2014 09:03 1.4M
Farnell-SL3S4011_402..> 16-Jul-2014 09:03 1.1M
Farnell-LPC408x-7x 3..> 16-Jul-2014 09:03 1.6M
Farnell-PCF8574-PCF8..> 16-Jul-2014 09:03 1.7M
Farnell-LPC81xM-32-b..> 16-Jul-2014 09:02 2.0M
Farnell-LPC1769-68-6..> 16-Jul-2014 09:02 1.9M
Farnell-Download-dat..> 16-Jul-2014 09:02 2.2M
Farnell-LPC3220-30-4..> 16-Jul-2014 09:02 2.2M
Farnell-LPC11U3x-32-..> 16-Jul-2014 09:01 2.4M
Farnell-Full-Datashe..> 15-Jul-2014 17:08 951K
Farnell-pmbta13_pmbt..> 15-Jul-2014 17:06 959K
Farnell-EE-SPX303N-4..> 15-Jul-2014 17:06 969K
Farnell-Datasheet-NX..> 15-Jul-2014 17:06 1.0M
Farnell-Datasheet-Fa..> 15-Jul-2014 17:05 1.0M
Farnell-MIDAS-un-tra..> 15-Jul-2014 17:05 1.0M
Farnell-SERIAL-TFT-M..> 15-Jul-2014 17:05 1.0M
Farnell-TMR-2-series..> 15-Jul-2014 16:48 787K
Farnell-DC-DC-Conver..> 15-Jul-2014 16:48 781K
Farnell-Full-Datashe..> 15-Jul-2014 16:47 803K
Farnell-TMLM-Series-..> 15-Jul-2014 16:47 810K
Farnell-TEL-5-Series..> 15-Jul-2014 16:47 814K
Farnell-TXL-series-t..> 15-Jul-2014 16:47 829K
Farnell-TEP-150WI-Se..> 15-Jul-2014 16:47 837K
Farnell-AC-DC-Power-..> 15-Jul-2014 16:47 845K
Farnell-TIS-Instruct..> 15-Jul-2014 16:47 845K
Farnell-TOS-tracopow..> 15-Jul-2014 16:47 852K
Farnell-TCL-DC-traco..> 15-Jul-2014 16:46 858K
Farnell-TIS-series-t..> 15-Jul-2014 16:46 875K
Farnell-TMR-2-Series..> 15-Jul-2014 16:46 897K
Farnell-TMR-3-WI-Ser..> 15-Jul-2014 16:46 939K
Farnell-TEN-8-WI-Ser..> 15-Jul-2014 16:46 939K
Farnell-SOURIAU-Cont..> 08-Jul-2014 19:04 3.0M
Farnell-T672-3000-Se..> 08-Jul-2014 18:59 2.0M
Farnell-tesa®pack63..> 08-Jul-2014 18:56 2.0M
Farnell-Encodeur-USB..> 08-Jul-2014 18:56 2.0M
Farnell-CC2530ZDK-Us..> 08-Jul-2014 18:55 2.1M
Farnell-2020-Manuel-..> 08-Jul-2014 18:55 2.1M
Farnell-Synchronous-..> 08-Jul-2014 18:54 2.1M
Farnell-Arithmetic-L..> 08-Jul-2014 18:54 2.1M
Farnell-NA555-NE555-..> 08-Jul-2014 18:53 2.2M
Farnell-4-Bit-Magnit..> 08-Jul-2014 18:53 2.2M
Farnell-LM555-Timer-..> 08-Jul-2014 18:53 2.2M
Farnell-L293d-Texas-..> 08-Jul-2014 18:53 2.2M
Farnell-SN54HC244-SN..> 08-Jul-2014 18:52 2.3M
Farnell-MAX232-MAX23..> 08-Jul-2014 18:52 2.3M
Farnell-High-precisi..> 08-Jul-2014 18:51 2.3M
Farnell-SMU-Instrume..> 08-Jul-2014 18:51 2.3M
Farnell-900-Series-B..> 08-Jul-2014 18:50 2.3M
Farnell-BA-Series-Oh..> 08-Jul-2014 18:50 2.3M
Farnell-UTS-Series-S..> 08-Jul-2014 18:49 2.5M
Farnell-270-Series-O..> 08-Jul-2014 18:49 2.3M
Farnell-UTS-Series-S..> 08-Jul-2014 18:49 2.8M
Farnell-Tiva-C-Serie..> 08-Jul-2014 18:49 2.6M
Farnell-UTO-Souriau-..> 08-Jul-2014 18:48 2.8M
Farnell-Clipper-Seri..> 08-Jul-2014 18:48 2.8M
Farnell-851-Series-P..> 08-Jul-2014 18:47 3.0M
Farnell-HIP4081A-Int..> 07-Jul-2014 19:47 1.0M
Farnell-ISL6251-ISL6..> 07-Jul-2014 19:47 1.1M
Farnell-DG411-DG412-..> 07-Jul-2014 19:47 1.0M
Farnell-3367-ARALDIT..> 07-Jul-2014 19:46 1.2M
Farnell-ICM7228-Inte..> 07-Jul-2014 19:46 1.1M
Farnell-Data-Sheet-K..> 07-Jul-2014 19:46 1.2M
Farnell-Silica-Gel-M..> 07-Jul-2014 19:46 1.2M
Farnell-TKC2-Dusters..> 07-Jul-2014 19:46 1.2M
Farnell-CRC-HANDCLEA..> 07-Jul-2014 19:46 1.2M
Farnell-760G-French-..> 07-Jul-2014 19:45 1.2M
Farnell-Decapant-KF-..> 07-Jul-2014 19:45 1.2M
Farnell-1734-ARALDIT..> 07-Jul-2014 19:45 1.2M
Farnell-Araldite-Fus..> 07-Jul-2014 19:45 1.2M
Farnell-fiche-de-don..> 07-Jul-2014 19:44 1.4M
Farnell-safety-data-..> 07-Jul-2014 19:44 1.4M
Farnell-A-4-Hardener..> 07-Jul-2014 19:44 1.4M
Farnell-CC-Debugger-..> 07-Jul-2014 19:44 1.5M
Farnell-SmartRF06-Ev..> 07-Jul-2014 19:43 1.6M
Farnell-CC2531-USB-H..> 07-Jul-2014 19:43 1.8M
Farnell-Alimentation..> 07-Jul-2014 19:43 1.8M
Farnell-BK889B-PONT-..> 07-Jul-2014 19:42 1.8M
Farnell-User-Guide-M..> 07-Jul-2014 19:41 2.0M
Farnell-SL59830-Inte..> 06-Jul-2014 10:11 1.0M
Farnell-ALF1210-PDF.htm 06-Jul-2014 10:06 4.0M
Farnell-AD7171-16-Bi..> 06-Jul-2014 10:06 1.0M
Farnell-Low-Noise-24..> 06-Jul-2014 10:05 1.0M
Farnell-ESCON-Featur..> 06-Jul-2014 10:05 938K
Farnell-74LCX573-Fai..> 06-Jul-2014 10:05 1.9M
Farnell-1N4148WS-Fai..> 06-Jul-2014 10:04 1.9M
Farnell-FAN6756-Fair..> 06-Jul-2014 10:04 850K
Farnell-Datasheet-Fa..> 06-Jul-2014 10:04 861K
Farnell-ES1F-ES1J-fi..> 06-Jul-2014 10:04 867K
Farnell-QRE1113-Fair..> 06-Jul-2014 10:03 879K
Farnell-2N7002DW-Fai..> 06-Jul-2014 10:03 886K
Farnell-FDC2512-Fair..> 06-Jul-2014 10:03 886K
Farnell-FDV301N-Digi..> 06-Jul-2014 10:03 886K
Farnell-S1A-Fairchil..> 06-Jul-2014 10:03 896K
Farnell-BAV99-Fairch..> 06-Jul-2014 10:03 896K
Farnell-74AC00-74ACT..> 06-Jul-2014 10:03 911K
Farnell-NaPiOn-Panas..> 06-Jul-2014 10:02 911K
Farnell-LQ-RELAYS-AL..> 06-Jul-2014 10:02 924K
Farnell-ev-relays-ae..> 06-Jul-2014 10:02 926K
Farnell-ESCON-Featur..> 06-Jul-2014 10:02 931K
Farnell-Amplifier-In..> 06-Jul-2014 10:02 940K
Farnell-Serial-File-..> 06-Jul-2014 10:02 941K
Farnell-Both-the-Del..> 06-Jul-2014 10:01 948K
Farnell-Videk-PDF.htm 06-Jul-2014 10:01 948K
Farnell-EPCOS-173438..> 04-Jul-2014 10:43 3.3M
Farnell-Sensorless-C..> 04-Jul-2014 10:42 3.3M
Farnell-197.31-KB-Te..> 04-Jul-2014 10:42 3.3M
Farnell-PIC12F609-61..> 04-Jul-2014 10:41 3.7M
Farnell-PADO-semi-au..> 04-Jul-2014 10:41 3.7M
Farnell-03-iec-runds..> 04-Jul-2014 10:40 3.7M
Farnell-ACC-Silicone..> 04-Jul-2014 10:40 3.7M
Farnell-Series-TDS10..> 04-Jul-2014 10:39 4.0M
Farnell-Q48-PDF.htm 23-Jun-2014 10:29 2.1M
Farnell-Panasonic-15..> 23-Jun-2014 10:29 2.1M
Farnell-BZX384-serie..> 23-Jun-2014 10:29 2.1M
Farnell-AN10361-Phil..> 23-Jun-2014 10:29 2.1M
Farnell-KSZ8851SNL-S..> 23-Jun-2014 10:28 2.1M
Farnell-BF545A-BF545..> 23-Jun-2014 10:28 2.1M
Farnell-PIC18F2455-2..> 23-Jun-2014 10:27 3.1M
Farnell-PMBT4403-PNP..> 23-Jun-2014 10:27 3.1M
Farnell-24AA024-24LC..> 23-Jun-2014 10:26 3.1M
Farnell-Leaded-Trans..> 23-Jun-2014 10:26 3.2M
Farnell-SSC7102-Micr..> 23-Jun-2014 10:25 3.2M
Farnell-Fastrack-Sup..> 23-Jun-2014 10:25 3.3M
Farnell-BC847DS-NXP-..> 23-Jun-2014 10:24 3.3M
Farnell-HI-70300-Sol..> 14-Jun-2014 18:27 2.4M
Farnell-Davum-TMC-PD..> 14-Jun-2014 18:27 2.4M
Farnell-Repartiteurs..> 14-Jun-2014 18:26 2.5M
Farnell-Documentatio..> 14-Jun-2014 18:26 2.5M
Farnell-Fiche-de-don..> 14-Jun-2014 18:26 2.5M
Farnell-SPLC780A1-16..> 14-Jun-2014 18:25 2.5M
Farnell-Construction..> 14-Jun-2014 18:25 2.5M
Farnell-Alimentation..> 14-Jun-2014 18:24 2.5M
Farnell-C.A-6150-C.A..> 14-Jun-2014 18:24 2.5M
Farnell-Fluke-1730-E..> 14-Jun-2014 18:23 2.5M
Farnell-Ponts-RLC-po..> 14-Jun-2014 18:23 3.3M
Farnell-Serie-Standa..> 14-Jun-2014 18:23 3.3M
Farnell-FDS-ITW-Spra..> 14-Jun-2014 18:22 3.3M
Farnell-HFE1600-Data..> 14-Jun-2014 18:22 3.3M
Farnell-TDK-Lambda-H..> 14-Jun-2014 18:21 3.3M
Farnell-HC49-4H-Crys..> 14-Jun-2014 18:20 3.3M
Farnell-Avvertenze-e..> 14-Jun-2014 18:20 3.3M
Farnell-Ceramic-tran..> 14-Jun-2014 18:19 3.4M
Farnell-ADL6507-PDF.htm 14-Jun-2014 18:19 3.4M
Farnell-PMEG4002EL-N..> 14-Jun-2014 18:18 3.4M
Farnell-Midas-Active..> 14-Jun-2014 18:17 3.4M
Farnell-Molex-83421-..> 14-Jun-2014 18:17 3.4M
Farnell-Molex-COMMER..> 14-Jun-2014 18:16 3.4M
Farnell-10TPB47M-End..> 14-Jun-2014 18:16 3.4M
Farnell-U2270B-PDF.htm 14-Jun-2014 18:15 3.4M
Farnell-SVPE-series-..> 14-Jun-2014 18:15 2.0M
Farnell-F28069-Picco..> 14-Jun-2014 18:14 2.0M
Farnell-Termometros-..> 14-Jun-2014 18:14 2.0M
Farnell-Cordless-dri..> 14-Jun-2014 18:13 2.0M
Farnell-Battery-GBA-..> 14-Jun-2014 18:13 2.0M
Farnell-CD4536B-Type..> 14-Jun-2014 18:13 2.0M
Farnell-0430300011-D..> 14-Jun-2014 18:13 2.0M
Farnell-Mistral-PDF.htm 14-Jun-2014 18:12 2.1M
Farnell-Connectors-N..> 14-Jun-2014 18:12 2.1M
Farnell-XPS-AC-Octop..> 14-Jun-2014 18:11 2.1M
Farnell-Midas-MCCOG4..> 14-Jun-2014 18:11 2.1M
Farnell-V4N-PDF.htm 14-Jun-2014 18:11 2.1M
Farnell-Signal-PCB-R..> 14-Jun-2014 18:11 2.1M
Farnell-PIC24FJ256GB..> 14-Jun-2014 09:51 2.4M
Farnell-DC-Fan-type-..> 14-Jun-2014 09:51 1.8M
Farnell-12mm-Size-In..> 14-Jun-2014 09:50 2.4M
Farnell-10BQ060-PDF.htm 14-Jun-2014 09:50 2.4M
Farnell-An-Improved-..> 14-Jun-2014 09:49 2.5M
Farnell-ATmega640-VA..> 14-Jun-2014 09:49 2.5M
Farnell-LME49725-Pow..> 14-Jun-2014 09:49 2.5M
Farnell-Produit-3430..> 14-Jun-2014 09:48 2.5M
Farnell-USB-Buccanee..> 14-Jun-2014 09:48 2.5M
Farnell-DC-Fan-type-..> 14-Jun-2014 09:48 2.5M
Farnell-Fiche-de-don..> 14-Jun-2014 09:47 2.5M
Farnell-Nilï¬-sk-E-..> 14-Jun-2014 09:47 2.5M
Farnell-MX670-MX675-..> 14-Jun-2014 09:46 2.5M
Farnell-Tektronix-AC..> 13-Jun-2014 18:44 1.5M
Farnell-PMBT3906-PNP..> 13-Jun-2014 18:44 1.5M
Farnell-PESD5V0F1BL-..> 13-Jun-2014 18:43 1.5M
Farnell-PMEG4010CEH-..> 13-Jun-2014 18:43 1.6M
Farnell-PESD9X5.0L-P..> 13-Jun-2014 18:43 1.6M
Farnell-BTA204-800C-..> 13-Jun-2014 18:42 1.6M
Farnell-BYV29F-600-N..> 13-Jun-2014 18:42 1.6M
Farnell-Low-cost-Enc..> 13-Jun-2014 18:42 1.7M
Farnell-BC846DS-NXP-..> 13-Jun-2014 18:42 1.6M
Farnell-IP4252CZ16-8..> 13-Jun-2014 18:41 1.7M
Farnell-BUJD203AX-NX..> 13-Jun-2014 18:41 1.7M
Farnell-Download-dat..> 13-Jun-2014 18:40 1.8M
Farnell-BT151-650R-N..> 13-Jun-2014 18:40 1.7M
Farnell-OXPCIE958-FB..> 13-Jun-2014 18:40 1.8M
Farnell-ATtiny26-L-A..> 13-Jun-2014 18:40 1.8M
Farnell-Microchip-MC..> 13-Jun-2014 18:27 1.8M
Farnell-Pompes-Charg..> 24-Apr-2014 20:23 3.3M
Farnell-Alimentation..> 01-Apr-2014 07:42 3.4M
Farnell-C.A 8332B-C...> 01-Apr-2014 07:40 3.4M
Farnell-ALF1225-12-V..> 01-Apr-2014 07:40 3.4M
Farnell-CS5532-34-BS..> 01-Apr-2014 07:39 3.5M
Farnell-ALF2412-24-V..> 01-Apr-2014 07:39 3.4M
Sefram-GUIDE_SIMPLIF..> 29-Mar-2014 11:46 422K
Sefram-CAT_ENREGISTR..> 29-Mar-2014 11:46 461K
Sefram-SP270.pdf-PDF..> 29-Mar-2014 11:46 464K
Sefram-7866HD.pdf-PD..> 29-Mar-2014 11:46 472K
Sefram-GUIDE_SIMPLIF..> 29-Mar-2014 11:46 481K
Sefram-CAT_MESUREURS..> 29-Mar-2014 11:46 435K
Sefram-GUIDE_SIMPLIF..> 29-Mar-2014 11:46 442K
Farnell-Portable-Ana..> 29-Mar-2014 11:16 2.8M
Farnell-CC2560-Bluet..> 29-Mar-2014 11:14 2.8M
Farnell-Ferric-Chlor..> 29-Mar-2014 11:14 2.8M
Farnell-MCF532x-7x-E..> 29-Mar-2014 11:14 2.8M
Farnell-A-True-Syste..> 29-Mar-2014 11:13 3.3M
Farnell-ELMA-PDF.htm 29-Mar-2014 11:13 3.3M
Farnell-SMBJ-Transil..> 29-Mar-2014 11:12 3.3M
Farnell-6517b-Electr..> 29-Mar-2014 11:12 3.3M
Farnell-Amplificateu..> 29-Mar-2014 11:11 3.3M
Farnell-ir1150s_fr.p..> 29-Mar-2014 11:11 3.3M
Farnell-De-la-puissa..> 29-Mar-2014 11:10 3.3M
Farnell-BK2650A-BK26..> 29-Mar-2014 11:10 3.3M
Farnell-Lubrifiant-a..> 26-Mar-2014 18:00 2.7M
Farnell-Circuit-Note..> 26-Mar-2014 18:00 2.8M
Farnell-Circuit-Note..> 26-Mar-2014 18:00 2.8M
Farnell-Current-Tran..> 26-Mar-2014 17:59 2.7M
Farnell-Current-Tran..> 26-Mar-2014 17:59 2.7M
Farnell-Current-Tran..> 26-Mar-2014 17:58 2.7M
Farnell-Current-Tran..> 26-Mar-2014 17:58 2.7M
Farnell-Supercapacit..> 26-Mar-2014 17:57 2.7M
Farnell-GALVA-MAT-Re..> 26-Mar-2014 17:57 2.7M
Farnell-GALVA-A-FROI..> 26-Mar-2014 17:56 2.7M
Farnell-1907-2006-PD..> 26-Mar-2014 17:56 2.7M
Farnell-ARALDITE-CW-..> 26-Mar-2014 17:56 2.7M
Farnell-06-6544-8-PD..> 26-Mar-2014 17:56 2.7M
Farnell-Miniature-Ci..> 26-Mar-2014 17:55 2.8M
Farnell-ARADUR-HY-13..> 26-Mar-2014 17:55 2.8M
Farnell-LOCTITE-3463..> 25-Mar-2014 08:19 3.0M
Farnell-LCW-CQ7P.CC-..> 25-Mar-2014 08:19 3.2M
Farnell-ATtiny20-PDF..> 25-Mar-2014 08:19 3.6M
Farnell-3M-VolitionT..> 25-Mar-2014 08:18 3.3M
Farnell-EMC1182-PDF.htm 25-Mar-2014 08:17 3.0M
Farnell-MC3510-PDF.htm 25-Mar-2014 08:17 3.0M
Farnell-Directive-re..> 25-Mar-2014 08:16 3.0M
Farnell-Loctite3455-..> 25-Mar-2014 08:16 3.0M
Farnell-LOCTITE-542-..> 25-Mar-2014 08:15 3.0M
Farnell-5910-PDF.htm 25-Mar-2014 08:15 3.0M
Farnell-china_rohs_o..> 21-Mar-2014 10:04 3.9M
Farnell-Cles-electro..> 21-Mar-2014 08:13 3.9M
Farnell-ARALDITE-201..> 21-Mar-2014 08:12 3.7M
Farnell-Premier-Farn..> 21-Mar-2014 08:11 3.8M
Farnell-celpac-SUL84..> 21-Mar-2014 08:11 3.8M
Farnell-S-TRI-SWT860..> 21-Mar-2014 08:11 3.8M
Farnell-3M-Polyimide..> 21-Mar-2014 08:09 3.9M
Farnell-Strangkuhlko..> 21-Mar-2014 08:09 3.9M
Farnell-Reglement-RE..> 21-Mar-2014 08:08 3.9M
Farnell-techfirst_se..> 21-Mar-2014 08:08 3.9M
Farnell-Septembre-20..> 20-Mar-2014 17:46 3.7M
Farnell-Telemetres-l..> 20-Mar-2014 17:46 3.7M
Farnell-Multi-Functi..> 20-Mar-2014 17:38 3.0M
Farnell-testo-470-Fo..> 20-Mar-2014 17:38 3.0M
Farnell-Novembre-201..> 20-Mar-2014 17:38 3.3M
Farnell-testo-205-20..> 20-Mar-2014 17:37 3.0M
Farnell-Panasonic-Ra..> 20-Mar-2014 17:37 2.6M
Farnell-Panasonic-Ne..> 20-Mar-2014 17:36 2.6M
Farnell-Panasonic-EC..> 20-Mar-2014 17:36 2.6M
Farnell-Panasonic-Id..> 20-Mar-2014 17:35 2.6M
Farnell-cree-Xlamp-X..> 20-Mar-2014 17:35 2.7M
Farnell-cree-Xlamp-X..> 20-Mar-2014 17:34 2.8M
Farnell-ADSP-21362-A..> 20-Mar-2014 17:34 2.8M
Farnell-AD524-PDF.htm 20-Mar-2014 17:33 2.8M
Farnell-MPXV7002-Rev..> 20-Mar-2014 17:33 2.8M
Farnell-cree-Xlamp-m..> 20-Mar-2014 17:32 2.9M
Farnell-cree-Xlamp-m..> 20-Mar-2014 17:32 2.9M
Farnell-50A-High-Pow..> 20-Mar-2014 17:31 2.9M
Farnell-cree-Xlamp-X..> 20-Mar-2014 17:31 2.9M
Farnell-Series-2600B..> 20-Mar-2014 17:30 3.0M
Farnell-ECO-Series-T..> 20-Mar-2014 08:14 2.5M
Farnell-PDTA143X-ser..> 20-Mar-2014 08:12 2.6M
Farnell-Panasonic-TS..> 20-Mar-2014 08:12 2.6M
Farnell-Radial-Lead-..> 20-Mar-2014 08:12 2.6M
Farnell-GN-RELAYS-AG..> 20-Mar-2014 08:11 2.6M
Farnell-Panasonic-Y3..> 20-Mar-2014 08:11 2.6M
Farnell-Panasonic-EZ..> 20-Mar-2014 08:10 2.6M
Farnell-ATMEL-8-bit-..> 19-Mar-2014 18:04 2.1M
Farnell-USB1T11A-PDF..> 19-Mar-2014 18:03 2.1M
Farnell-OSLON-SSL-Ce..> 19-Mar-2014 18:03 2.1M
Farnell-Atmel-ATmega..> 19-Mar-2014 18:03 2.2M
Farnell-PBSS5160T-60..> 19-Mar-2014 18:03 2.1M
Farnell-MICROCHIP-PI..> 19-Mar-2014 18:02 2.5M
Farnell-Ed.081002-DA..> 19-Mar-2014 18:02 2.5M
Farnell-Instructions..> 19-Mar-2014 18:01 2.5M
Farnell-Serie-PicoSc..> 19-Mar-2014 18:01 2.5M
Farnell-F42202-PDF.htm 19-Mar-2014 18:00 2.5M
Farnell-propose-plus..> 11-Mar-2014 08:19 2.8M
Farnell-Haute-vitess..> 11-Mar-2014 08:17 2.4M
Farnell-Controle-de-..> 11-Mar-2014 08:16 2.8M
Farnell-NXP-TEA1703T..> 11-Mar-2014 08:15 2.8M
Farnell-XPS-MC16-XPS..> 11-Mar-2014 08:15 2.8M
Farnell-MC21605-PDF.htm 11-Mar-2014 08:14 2.8M
Farnell-WetTantalum-..> 11-Mar-2014 08:14 2.8M
Farnell-ES2333-PDF.htm 11-Mar-2014 08:14 2.8M
Farnell-SB175-Connec..> 11-Mar-2014 08:14 2.8M
Farnell-Cannon-ZD-PD..> 11-Mar-2014 08:13 2.8M
Farnell-YAGEO-DATA-S..> 11-Mar-2014 08:13 2.8M
Farnell-ATMEL-8-bit-..> 11-Mar-2014 07:55 2.1M
Farnell-NXP-PCA9555 ..> 11-Mar-2014 07:54 2.2M
Farnell-MICREL-KSZ88..> 11-Mar-2014 07:54 2.2M
Farnell-Microship-PI..> 11-Mar-2014 07:53 2.2M
Farnell-EPCOS-Sample..> 11-Mar-2014 07:53 2.2M
Farnell-NXP-BT136-60..> 11-Mar-2014 07:52 2.3M
Farnell-NTE_SEMICOND..> 11-Mar-2014 07:52 2.3M
Farnell-L-efficacite..> 11-Mar-2014 07:52 2.3M
Farnell-LUXEON-Guide..> 11-Mar-2014 07:52 2.3M
Farnell-Realiser-un-..> 11-Mar-2014 07:51 2.3M
Farnell-SOT-23-Multi..> 11-Mar-2014 07:51 2.3M
Farnell-ZigBee-ou-le..> 11-Mar-2014 07:50 2.4M
Farnell-Les-derniers..> 11-Mar-2014 07:50 2.3M
Farnell-Conception-d..> 11-Mar-2014 07:49 2.4M
Farnell-Puissance-ut..> 11-Mar-2014 07:49 2.4M
Farnell-MOLEX-43160-..> 10-Mar-2014 17:21 1.9M
Farnell-MOLEX-87439-..> 10-Mar-2014 17:21 1.9M
Farnell-MOLEX-43020-..> 10-Mar-2014 17:21 1.9M
Farnell-NXP-PBSS9110..> 10-Mar-2014 17:21 1.9M
Farnell-TEKTRONIX-DP..> 10-Mar-2014 17:20 2.0M
Farnell-uC-OS-III-Br..> 10-Mar-2014 17:20 2.0M
Farnell-CIRRUS-LOGIC..> 10-Mar-2014 17:20 2.1M
Farnell-NXP-PSMN7R0-..> 10-Mar-2014 17:19 2.1M
Farnell-MOLEX-39-00-..> 10-Mar-2014 17:19 1.9M
Farnell-manual-bus-p..> 10-Mar-2014 16:29 1.9M
Farnell-Molex-Crimp-..> 10-Mar-2014 16:27 1.7M
Farnell-The-essentia..> 10-Mar-2014 16:27 1.7M
Farnell-OMRON-Master..> 10-Mar-2014 16:26 1.8M
Farnell-Proskit-SS-3..> 10-Mar-2014 16:26 1.8M
Farnell-BYV79E-serie..> 10-Mar-2014 16:19 1.6M
Farnell-NXP-74VHC126..> 10-Mar-2014 16:17 1.6M
Farnell-NXP-PSMN1R7-..> 10-Mar-2014 16:17 1.6M
Farnell-FICHE-DE-DON..> 10-Mar-2014 16:17 1.6M
Farnell-HUNTSMAN-Adv..> 10-Mar-2014 16:17 1.7M
Farnell-NXP-PMBFJ620..> 10-Mar-2014 16:16 1.7M
Farnell-Pico-Spox-Wi..> 10-Mar-2014 16:16 1.7M
CRUCIAL PART NUMBER MODULE TYPE DENSITY SPEED RANK VOLTAGE COMP CONFIG CAS LATENCY MICRON PART NUMBER
CT4G4RFS8213 RDIMM 288-pin 4GB 2133MT/s Single 1.2V 512M x 8 CL15 MTA9ASF51272PZ-2G1A2
CT8G4RFS4213 RDIMM 288-pin 8GB 2133MT/s Single 1.2V 1024M x 4 CL15 MTA18ASF1G72PZ-2G1A2
CT16G4RFD4213 RDIMM 288-pin 16GB 2133MT/s Dual 1.2V 1024M x 4 CL15 MTA36ASF2G72PZ-2G1A2
CT4G4DFS8213 UDIMM 288-pin 4GB 2133MT/s Single 1.2V 512M x 8 CL15 MTA8ATF51264AZ-2G1A1
CT8G4DFD8213 UDIMM 288-pin 8GB 2133MT/s Dual 1.2V 512M x 8 CL15 MTA16ATF1G64AZ-2G1A1
1
Product performance and efficiency improvements are noted as comparisons between DDR3 and DDR4 memory technologies at their introduction. When it was introduced, DDR3-1066 operated at 1.5V and had an
estimated component density of 8Gb, compared to DDR4-2133, which will operate at 1.2V and have an estimated component density of 16Gb. When voltage reductions and all other energy-saving DDR4 features are
factored in, DDR4 modules are projected to consume up to 40% less power.
2Limited lifetime warranty valid everywhere except Germany and France, where warranty is valid for ten years from date of purchase.
3Program benefits may vary and are subject to change without notice. Customer admittance and continued inclusion to the program is up to the sole discretion of Micron Technology, Inc.
REVISION: 04/18/2014
©2014 Micron Technology, Inc. All rights reserved. Information is subject to change without notice. Crucial and the Crucial logo are trademarks or registered trademarks of Micron
Technology, Inc. All other trademarks and service marks are property of their respective owners. Products and specifications are subject to change without notice. Neither Crucial
nor Micron Technology is responsible for omissions or errors in typography or photography.
NOW SAMPLING:
Crucial®
DDR4 Server Memory
Get early access to Crucial DDR4 modules!
Introducing the Crucial DDR4 Technology
Enablement Program (TEP)
HOW IT WORKS
Enroll in the Crucial DDR4 TEP program and get early access to DDR4 modules and
information. Start the enrollment process today by visiting
www.crucial.com/usa/en/memory-ddr4-info.
ELIGIBILITY
Channel partners who are currently developing or evaluating DDR4-capable platforms
BENEFITS3
• Early access to select Crucial DDR4 modules
• Notification of new DDR4 modules as they become available
• Access to technical resources to aid in product development and evaluation
Now Sampling
The following modules are now included as part of the Crucial DDR4 TEP program. Qualified participants are encouraged to inquire about pricing
and availability. Additional module types, densities, and speeds will be available later this year. Stay tuned!
DDR4 Server Memory:
Product Highlights1
• Increase data throughput – up to 50%
more memory bandwidth
• Enable up to twice the installed server
memory capacity
• Reduce power consumption – up to 40%
more energy efficient
• Easier system cooling – less heat
generated per module
• Optimized for future Intel® Xeon®
processor E5-2600 v3 product family
• Compatible with OEM servers and
warranties
• Backed by the Reliance Program
• Limited lifetime warranty2
Overcome one of the greatest server limitations: memory. From cloud computing and
virtualization to HPC, Big Data and more, memory-dependent server applications require
increasingly higher densities of memory and higher levels of performance than are attainable
on current DDR3 technology. Enter Crucial DDR4 server memory.
More speed. More bandwidth. More efficient.
Next generation DDR4 memory is here.
© 2007 Microchip Technology Inc. DS39605F
PIC18F1220/1320
Data Sheet
18/20/28-Pin High-Performance,
Enhanced Flash Microcontrollers
with 10-Bit A/D and nanoWatt TechnologyDS39605F-page ii © 2007 Microchip Technology Inc.
Information contained in this publication regarding device
applications and the like is provided only for your convenience
and may be superseded by updates. It is your responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART,
PRO MATE, PowerSmart, rfPIC and SmartShunt are
registered trademarks of Microchip Technology Incorporated
in the U.S.A. and other countries.
AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB,
SEEVAL, SmartSensor and The Embedded Control Solutions
Company are registered trademarks of Microchip Technology
Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, ECAN,
ECONOMONITOR, FanSense, FlexROM, fuzzyLAB,
In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active
Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, PICkit,
PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal,
PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
rfPICDEM, Select Mode, Smart Serial, SmartTel, Total
Endurance, UNI/O, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2007, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
Printed on recycled paper.
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona, Gresham, Oregon and Mountain View, California. The
Company’s quality system processes and procedures are for its PIC®
MCUs and dsPIC DSCs, KEELOQ® code hopping devices, Serial
EEPROMs, microperipherals, nonvolatile memory and analog
products. In addition, Microchip’s quality system for the design and
manufacture of development systems is ISO 9001:2000 certified.© 2007 Microchip Technology Inc. DS39605F-page 1
Low-Power Features:
• Power Managed modes:
- Run: CPU on, peripherals on
- Idle: CPU off, peripherals on
- Sleep: CPU off, peripherals off
• Power Consumption modes:
- PRI_RUN: 150 μA, 1 MHz, 2V
- PRI_IDLE: 37 μA, 1 MHz, 2V
- SEC_RUN: 14 μA, 32 kHz, 2V
- SEC_IDLE: 5.8 μA, 32 kHz, 2V
- RC_RUN: 110 μA, 1 MHz, 2V
- RC_IDLE: 52 μA, 1 MHz, 2V
- Sleep: 0.1 μA, 1 MHz, 2V
• Timer1 Oscillator: 1.1 μA, 32 kHz, 2V
• Watchdog Timer: 2.1 μA
• Two-Speed Oscillator Start-up
Oscillators:
• Four Crystal modes:
- LP, XT, HS: up to 25 MHz
- HSPLL: 4-10 MHz (16-40 MHz internal)
• Two External RC modes, up to 4 MHz
• Two External Clock modes, up to 40 MHz
• Internal oscillator block:
- 8 user-selectable frequencies: 31 kHz, 125 kHz,
250 kHz, 500 kHz, 1 MHz, 2 MHz, 4 MHz, 8 MHz
- 125 kHz to 8 MHz calibrated to 1%
- Two modes select one or two I/O pins
- OSCTUNE – Allows user to shift frequency
• Secondary oscillator using Timer1 @ 32 kHz
• Fail-Safe Clock Monitor
- Allows for safe shutdown if peripheral clock stops
Peripheral Highlights:
• High current sink/source 25 mA/25 mA
• Three external interrupts
• Enhanced Capture/Compare/PWM (ECCP) module:
- One, two or four PWM outputs
- Selectable polarity
- Programmable dead time
- Auto-Shutdown and Auto-Restart
- Capture is 16-bit, max resolution 6.25 ns (TCY/16)
- Compare is 16-bit, max resolution 100 ns (TCY)
• Compatible 10-bit, up to 13-channel Analog-toDigital
Converter module (A/D) with programmable
acquisition time
• Enhanced USART module:
- Supports RS-485, RS-232 and LIN 1.2
- Auto-Wake-up on Start bit
- Auto-Baud Detect
Special Microcontroller Features:
• 100,000 erase/write cycle Enhanced Flash
program memory typical
• 1,000,000 erase/write cycle Data EEPROM
memory typical
• Flash/Data EEPROM Retention: > 40 years
• Self-programmable under software control
• Priority levels for interrupts
• 8 x 8 Single-Cycle Hardware Multiplier
• Extended Watchdog Timer (WDT):
- Programmable period from 41 ms to 131s
- 2% stability over VDD and Temperature
• Single-supply 5V In-Circuit Serial Programming™
(ICSP™) via two pins
• In-Circuit Debug (ICD) via two pins
• Wide operating voltage range: 2.0V to 5.5V
Device
Program Memory Data Memory
I/O 10-bit
A/D (ch)
ECCP
(PWM) EUSART Timers
Flash 8/16-bit
(bytes)
# Single-Word
Instructions
SRAM
(bytes)
EEPROM
(bytes)
PIC18F1220 4K 2048 256 256 16 7 1 Y 1/3
PIC18F1320 8K 4096 256 256 16 7 1 Y 1/3
18/20/28-Pin High-Performance, Enhanced Flash MCUs
with 10-bit A/D and nanoWatt Technology
PIC18F1220/1320PIC18F1220/1320
DS39605F-page 2 © 2007 Microchip Technology Inc.
Pin Diagrams
RB3/CCP1/P1A
RB2/P1B/INT2
OSC1/CLKI/RA7
OSC2/CLKO/RA6
VDD/AVDD
RB7/PGD/T1OSI/
RB6/PGC/T1OSO/
RB5/PGM/KBI1
RB4/AN6/RX/
RA0/AN0
RA1/AN1/LVDIN
RA4/T0CKI
MCLR/VPP/RA5
VSS/AVSS
RA2/AN2/VREFRA3/AN3/VREF+
RB0/AN4/INT0
RB1/AN5/TX/
1
2
3
4
5
6
7
8
9
18
17
16
15
14
13
12
11
10
PIC18F1X20
18-Pin PDIP, SOIC
RB3/CCP1/P1A
RB2/P1B/INT2
OSC1/CLKI/RA7
OSC2/CLKO/RA6
VDD
RB7/PGD/T1OSI/
RB6/PGC/T1OSO/
RB5/PGM/KBI1
RB4/AN6/RX/
RA0/AN0
RA1/AN1/LVDIN
RA4/T0CKI
MCLR/VPP/RA5
VSS
RA2/AN2/VREFRA3/AN3/VREF+
RB0/AN4/INT0
RB1/AN5/TX/
1
2
3
4
5
7
8
9
10
20
19
18
17
16
14
13
12
11
PIC18F1X20
AVSS 6 15 AVDD
20-Pin SSOP
28-Pin QFN
16
2
RA4/T0CKI
RA0/AN0
NC
MCLR/VPP/RA5
NC
AVSS
NC
RA2/AN2/VREFRA3/AN3/VREF+
RA1/AN1/LVDIN
OSC1/CLKI/RA7
OSC2/CLKO/RA6
VDD
NC
AVDD
RB7/PGD/T1OSI/P1D/KBI3
RB6/PGC/T1OSO/T13CKI/P1C/KBI2
NC
RB5/PGM/KBI1
7
PIC18F1X20
1
3
6
5
4
15
21
19
20
17
18
28
27
26
25
24
23
22
8
9
10
11
12
13
14
VSS
NC
NC
RB2/P1B/INT2
RB0/AN4/INT0
RB1/AN5/TX/CK/INT1
NC
RB4/AN6/RX/DT/KBI0 RB3/CCP1/P1A
T13CKI/P1C/KBI2
P1D/KBI3
CK/INT1 DT/KBI0
P1D/KBI3
T13CKI/P1C/KBI2
CK/INT1 DT/KBI0© 2007 Microchip Technology Inc. DS39605F-page 3
PIC18F1220/1320
Table of Contents
1.0 Device Overview .......................................................................................................................................................................... 5
2.0 Oscillator Configurations ............................................................................................................................................................ 11
3.0 Power Managed Modes ............................................................................................................................................................. 19
4.0 Reset.......................................................................................................................................................................................... 33
5.0 Memory Organization................................................................................................................................................................. 41
6.0 Flash Program Memory.............................................................................................................................................................. 57
7.0 Data EEPROM Memory ............................................................................................................................................................. 67
8.0 8 x 8 Hardware Multiplier............................................................................................................................................................ 71
9.0 Interrupts .................................................................................................................................................................................... 73
10.0 I/O Ports ..................................................................................................................................................................................... 87
11.0 Timer0 Module ........................................................................................................................................................................... 99
12.0 Timer1 Module ......................................................................................................................................................................... 103
13.0 Timer2 Module ......................................................................................................................................................................... 109
14.0 Timer3 Module ......................................................................................................................................................................... 111
15.0 Enhanced Capture/Compare/PWM (ECCP) Module................................................................................................................ 115
16.0 Enhanced Addressable Universal Synchronous Asynchronous Receiver Transmitter (EUSART) .......................................... 131
17.0 10-Bit Analog-to-Digital Converter (A/D) Module ..................................................................................................................... 155
18.0 Low-Voltage Detect.................................................................................................................................................................. 165
19.0 Special Features of the CPU.................................................................................................................................................... 171
20.0 Instruction Set Summary.......................................................................................................................................................... 191
21.0 Development Support............................................................................................................................................................... 233
22.0 Electrical Characteristics.......................................................................................................................................................... 237
23.0 DC and AC Characteristics Graphs and Tables....................................................................................................................... 267
24.0 Packaging Information.............................................................................................................................................................. 285
Appendix A: Revision History............................................................................................................................................................. 291
Appendix B: Device Differences ........................................................................................................................................................ 291
Appendix C: Conversion Considerations ........................................................................................................................................... 292
Appendix D: Migration from Baseline to Enhanced Devices.............................................................................................................. 292
Appendix E: Migration from Mid-Range to Enhanced Devices .......................................................................................................... 293
Appendix F: Migration from High-End to Enhanced Devices............................................................................................................. 293
Index .................................................................................................................................................................................................. 295
The Microchip Web Site..................................................................................................................................................................... 303
Customer Change Notification Service .............................................................................................................................................. 303
Customer Support.............................................................................................................................................................................. 303
Reader Response .............................................................................................................................................................................. 304
PIC18F1220/1320 Product Identification System .............................................................................................................................. 305PIC18F1220/1320
DS39605F-page 4 © 2007 Microchip Technology Inc.
TO OUR VALUED CUSTOMERS
It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip
products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined and
enhanced as new volumes and updates are introduced.
If you have any questions or comments regarding this publication, please contact the Marketing Communications Department via
E-mail at docerrors@microchip.com or fax the Reader Response Form in the back of this data sheet to (480) 792-4150. We
welcome your feedback.
Most Current Data Sheet
To obtain the most up-to-date version of this data sheet, please register at our Worldwide Web site at:
http://www.microchip.com
You can determine the version of a data sheet by examining its literature number found on the bottom outside corner of any page.
The last character of the literature number is the version number, (e.g., DS30000A is version A of document DS30000).
Errata
An errata sheet, describing minor operational differences from the data sheet and recommended workarounds, may exist for current
devices. As device/documentation issues become known to us, we will publish an errata sheet. The errata will specify the revision
of silicon and revision of document to which it applies.
To determine if an errata sheet exists for a particular device, please check with one of the following:
• Microchip’s Worldwide Web site; http://www.microchip.com
• Your local Microchip sales office (see last page)
When contacting a sales office, please specify which device, revision of silicon and data sheet (include literature number) you are
using.
Customer Notification System
Register on our web site at www.microchip.com to receive the most current information on all of our products.© 2007 Microchip Technology Inc. DS39605F-page 5
PIC18F1220/1320
1.0 DEVICE OVERVIEW
This document contains device specific information for
the following devices:
This family offers the advantages of all PIC18 microcontrollers
– namely, high computational performance at an
economical price – with the addition of high endurance
Enhanced Flash program memory. On top of these features,
the PIC18F1220/1320 family introduces design
enhancements that make these microcontrollers a logical
choice for many high-performance, power sensitive
applications.
1.1 New Core Features
1.1.1 nanoWatt TECHNOLOGY
All of the devices in the PIC18F1220/1320 family incorporate
a range of features that can significantly reduce
power consumption during operation. Key items include:
• Alternate Run Modes: By clocking the controller
from the Timer1 source or the internal oscillator
block, power consumption during code execution
can be reduced by as much as 90%.
• Multiple Idle Modes: The controller can also run
with its CPU core disabled, but the peripherals are
still active. In these states, power consumption can
be reduced even further, to as little as 4% of normal
operation requirements.
• On-the-fly Mode Switching: The power managed
modes are invoked by user code during operation,
allowing the user to incorporate power-saving ideas
into their application’s software design.
• Lower Consumption in Key Modules: The power
requirements for both Timer1 and the Watchdog
Timer have been reduced by up to 80%, with typical
values of 1.1 and 2.1 μA, respectively.
1.1.2 MULTIPLE OSCILLATOR OPTIONS
AND FEATURES
All of the devices in the PIC18F1220/1320 family offer
nine different oscillator options, allowing users a wide
range of choices in developing application hardware.
These include:
• Four Crystal modes, using crystals or ceramic
resonators.
• Two External Clock modes, offering the option of
using two pins (oscillator input and a divide-by-4
clock output), or one pin (oscillator input, with the
second pin reassigned as general I/O).
• Two External RC Oscillator modes, with the same
pin options as the External Clock modes.
• An internal oscillator block, which provides an
8 MHz clock (±2% accuracy) and an INTRC source
(approximately 31 kHz, stable over temperature and
VDD), as well as a range of 6 user-selectable clock
frequencies (from 125 kHz to 4 MHz) for a total of
8 clock frequencies.
Besides its availability as a clock source, the internal
oscillator block provides a stable reference source that
gives the family additional features for robust
operation:
• Fail-Safe Clock Monitor: This option constantly
monitors the main clock source against a reference
signal provided by the internal oscillator. If a clock failure
occurs, the controller is switched to the internal
oscillator block, allowing for continued low-speed
operation, or a safe application shutdown.
• Two-Speed Start-up: This option allows the internal
oscillator to serve as the clock source from Poweron
Reset, or wake-up from Sleep mode, until the
primary clock source is available. This allows for
code execution during what would otherwise be the
clock start-up interval and can even allow an application
to perform routine background activities and
return to Sleep without returning to full power
operation.
1.2 Other Special Features
• Memory Endurance: The Enhanced Flash cells for
both program memory and data EEPROM are rated
to last for many thousands of erase/write cycles –
up to 100,000 for program memory and 1,000,000
for EEPROM. Data retention without refresh is
conservatively estimated to be greater than
40 years.
• Self-programmability: These devices can write to
their own program memory spaces under internal
software control. By using a bootloader routine
located in the protected Boot Block at the top of program
memory, it becomes possible to create an
application that can update itself in the field.
• Enhanced CCP module: In PWM mode, this
module provides 1, 2 or 4 modulated outputs for
controlling half-bridge and full-bridge drivers. Other
features include auto-shutdown, for disabling PWM
outputs on interrupt or other select conditions and
auto-restart, to reactivate outputs once the condition
has cleared.
• Enhanced USART: This serial communication
module features automatic wake-up on Start bit and
automatic baud rate detection and supports RS-232,
RS-485 and LIN 1.2 protocols, making it ideally
suited for use in Local Interconnect Network (LIN)
bus applications.
• 10-bit A/D Converter: This module incorporates
programmable acquisition time, allowing for a
channel to be selected and a conversion to be
initiated without waiting for a sampling period and
thus, reduce code overhead.
• Extended Watchdog Timer (WDT): This enhanced
version incorporates a 16-bit prescaler, allowing a
time-out range from 4 ms to over 2 minutes that is
stable across operating voltage and temperature.
• PIC18F1220 • PIC18F1320PIC18F1220/1320
DS39605F-page 6 © 2007 Microchip Technology Inc.
1.3 Details on Individual Family
Members
Devices in the PIC18F1220/1320 family are available
in 18-pin, 20-pin and 28-pin packages. A block diagram
for this device family is shown in Figure 1-1.
The devices are differentiated from each other only in
the amount of on-chip Flash program memory
(4 Kbytes for the PIC18F1220 device, 8 Kbytes for the
PIC18F1320 device). These and other features are
summarized in Table 1-1.
A block diagram of the PIC18F1220/1320 device
architecture is provided in Figure 1-1. The pinouts for
this device family are listed in Table 1-2.
TABLE 1-1: DEVICE FEATURES
Features PIC18F1220 PIC18F1320
Operating Frequency DC – 40 MHz DC – 40 MHz
Program Memory (Bytes) 4096 8192
Program Memory (Instructions) 2048 4096
Data Memory (Bytes) 256 256
Data EEPROM Memory (Bytes) 256 256
Interrupt Sources 15 15
I/O Ports Ports A, B Ports A, B
Timers 4 4
Enhanced Capture/Compare/PWM Modules 1 1
Serial Communications Enhanced USART Enhanced USART
10-bit Analog-to-Digital Module 7 input channels 7 input channels
Resets (and Delays)
POR, BOR,
RESET Instruction, Stack Full,
Stack Underflow (PWRT, OST),
MCLR (optional), WDT
POR, BOR,
RESET Instruction, Stack Full,
Stack Underflow (PWRT, OST),
MCLR (optional), WDT
Programmable Low-Voltage Detect Yes Yes
Programmable Brown-out Reset Yes Yes
Instruction Set 75 Instructions 75 Instructions
Packages
18-pin SDIP
18-pin SOIC
20-pin SSOP
28-pin QFN
18-pin SDIP
18-pin SOIC
20-pin SSOP
28-pin QFN© 2007 Microchip Technology Inc. DS39605F-page 7
PIC18F1220/1320
FIGURE 1-1: PIC18F1220/1320 BLOCK DIAGRAM
Instruction
Decode &
Control
PORTA
PORTB
RA4/T0CKI
MCLR/VPP/RA5(1)
Enhanced
Timer0 Timer1 Timer2
RA3/AN3/VREF+
RA2/AN2/VREFRA1/AN1/LVDIN
RA0/AN0
Data Latch
Data RAM
Address Latch
Address<12>
12(2)
BSR FSR0
FSR1
FSR2
4 12 4
PCH PCL
PCLATH
8
31 Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
WREG
8
BIT OP
8 8
ALU<8>
8
Address Latch
(8 Kbytes)
Data Latch
20
21
21
16
8
8
8
inc/dec logic
21 8
Data Bus<8>
8
Instruction
12
3
ROM Latch
Timer3
Bank0, F
PCLATU
PCU
OSC2/CLKO/RA6(2)
USART
8
Register
Table Latch
Table Pointer <2>
inc/dec
logic
RB0/AN4/INT0
RB4/AN6/RX/DT/KBI0
RB1/AN5/TX/CK/INT1
RB2/P1B/INT2
RB3/CCP1/P1A
RB5/PGM/KBI1
RB6/PGC/T1OSO/
RB7/PGD/T1OSI/
OSC2/CLKI/RA7 Decode (2)
Power-up
Timer
Power-on
Reset
Watchdog
Timer
VDD, VSS
Brown-out
Reset
Precision
Reference
Voltage Low-Voltage
Programming
In-Circuit
Debugger
Oscillator
Start-up Timer
Timing
Generation
OSC1(2)
OSC2(2)
T1OSI
T1OSO
INTRC
Oscillator
Fail-Safe
Clock Monitor
Note 1: RA5 is available only when the MCLR Reset is disabled.
2: OSC1, OSC2, CLKI and CLKO are only available in select oscillator modes and when these pins are not being used as digital
I/O. Refer to Section 2.0 “Oscillator Configurations” for additional information.
8
CCP
Enhanced
T13CKI/P1C/KBI2
Program Memory
(4 Kbytes)
PIC18F1220
PIC18F1320
A/D Converter
Data EEPROM
P1D/KBI3
MCLR(1)PIC18F1220/1320
DS39605F-page 8 © 2007 Microchip Technology Inc.
TABLE 1-2: PIC18F1220/1320 PINOUT I/O DESCRIPTIONS
Pin Name
Pin Number
Pin
Type
Buffer
Type Description PDIP/
SOIC SSOP QFN
MCLR/VPP/RA5
MCLR
VPP
RA5
441
I
P
I
ST
—
ST
Master Clear (input) or programming voltage (input).
Master Clear (Reset) input. This pin is an active-low
Reset to the device.
Programming voltage input.
Digital input.
OSC1/CLKI/RA7
OSC1
CLKI
RA7
16 18 21
I
I
I/O
ST
CMOS
ST
Oscillator crystal or external clock input.
Oscillator crystal input or external clock source
input. ST buffer when configured in RC mode,
CMOS otherwise.
External clock source input. Always associated with
pin function OSC1. (See related OSC1/CLKI,
OSC2/CLKO pins.)
General purpose I/O pin.
OSC2/CLKO/RA6
OSC2
CLKO
RA6
15 17 20
O
O
I/O
—
—
ST
Oscillator crystal or clock output.
Oscillator crystal output. Connects to crystal or
resonator in Crystal Oscillator mode.
In RC, EC and INTRC modes, OSC2 pin outputs
CLKO, which has 1/4 the frequency of OSC1 and
denotes instruction cycle rate.
General purpose I/O pin.
PORTA is a bidirectional I/O port.
RA0/AN0
RA0
AN0
1 1 26
I/O
I
ST
Analog
Digital I/O.
Analog input 0.
RA1/AN1/LVDIN
RA1
AN1
LVDIN
2 2 27
I/O
I
I
ST
Analog
Analog
Digital I/O.
Analog input 1.
Low-Voltage Detect input.
RA2/AN2/VREFRA2
AN2
VREF-
677
I/O
I
I
ST
Analog
Analog
Digital I/O.
Analog input 2.
A/D reference voltage (low) input.
RA3/AN3/VREF+
RA3
AN3
VREF+
788
I/O
I
I
ST
Analog
Analog
Digital I/O.
Analog input 3.
A/D reference voltage (high) input.
RA4/T0CKI
RA4
T0CKI
3 3 28
I/O
I
ST/OD
ST
Digital I/O. Open-drain when configured as output.
Timer0 external clock input.
RA5 See the MCLR/VPP/RA5 pin.
RA6 See the OSC2/CLKO/RA6 pin.
RA7 See the OSC1/CLKI/RA7 pin.
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open-drain (no P diode to VDD) © 2007 Microchip Technology Inc. DS39605F-page 9
PIC18F1220/1320
PORTB is a bidirectional I/O port. PORTB can be software
programmed for internal weak pull-ups on all inputs.
RB0/AN4/INT0
RB0
AN4
INT0
899
I/O
I
I
TTL
Analog
ST
Digital I/O.
Analog input 4.
External interrupt 0.
RB1/AN5/TX/CK/INT1
RB1
AN5
TX
CK
INT1
9 10 10
I/O
I
O
I/O
I
TTL
Analog
—
ST
ST
Digital I/O.
Analog input 5.
EUSART asynchronous transmit.
EUSART synchronous clock (see related RX/DT).
External interrupt 1.
RB2/P1B/INT2
RB2
P1B
INT2
17 19 23
I/O
O
I
TTL
—
ST
Digital I/O.
Enhanced CCP1/PWM output.
External interrupt 2.
RB3/CCP1/P1A
RB3
CCP1
P1A
18 20 24
I/O
I/O
O
TTL
ST
—
Digital I/O.
Capture 1 input/Compare 1 output/PWM 1 output.
Enhanced CCP1/PWM output.
RB4/AN6/RX/DT/KBI0
RB4
AN6
RX
DT
KBI0
10 11 12
I/O
I
I
I/O
I
TTL
Analog
ST
ST
TTL
Digital I/O.
Analog input 6.
EUSART asynchronous receive.
EUSART synchronous data (see related TX/CK).
Interrupt-on-change pin.
RB5/PGM/KBI1
RB5
PGM
KBI1
11 12 13
I/O
I/O
I
TTL
ST
TTL
Digital I/O.
Low-Voltage ICSP Programming enable pin.
Interrupt-on-change pin.
RB6/PGC/T1OSO/
T13CKI/P1C/KBI2
RB6
PGC
T1OSO
T13CKI
P1C
KBI2
12 13 15
I/O
I/O
O
I
O
I
TTL
ST
—
ST
—
TTL
Digital I/O.
In-Circuit Debugger and ICSP programming clock pin.
Timer1 oscillator output.
Timer1/Timer3 external clock output.
Enhanced CCP1/PWM output.
Interrupt-on-change pin.
RB7/PGD/T1OSI/
P1D/KBI3
RB7
PGD
T1OSI
P1D
KBI3
13 14 16
I/O
I/O
I
O
I
TTL
ST
CMOS
—
TTL
Digital I/O.
In-Circuit Debugger and ICSP programming data pin.
Timer1 oscillator input.
Enhanced CCP1/PWM output.
Interrupt-on-change pin.
VSS 5 5, 6 3, 5 P — Ground reference for logic and I/O pins.
VDD 14 15, 16 17, 19 P — Positive supply for logic and I/O pins.
NC — — 18 — — No connect.
TABLE 1-2: PIC18F1220/1320 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number
Pin
Type
Buffer
Type Description PDIP/
SOIC SSOP QFN
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open-drain (no P diode to VDD) PIC18F1220/1320
DS39605F-page 10 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 11
PIC18F1220/1320
2.0 OSCILLATOR
CONFIGURATIONS
2.1 Oscillator Types
The PIC18F1220 and PIC18F1320 devices can be
operated in ten different oscillator modes. The user can
program the configuration bits, FOSC3:FOSC0, in
Configuration Register 1H to select one of these ten
modes:
1. LP Low-Power Crystal
2. XT Crystal/Resonator
3. HS High-Speed Crystal/Resonator
4. HSPLL High-Speed Crystal/Resonator
with PLL enabled
5. RC External Resistor/Capacitor with
FOSC/4 output on RA6
6. RCIO External Resistor/Capacitor with
I/O on RA6
7. INTIO1 Internal Oscillator with FOSC/4
output on RA6 and I/O on RA7
8. INTIO2 Internal Oscillator with I/O on RA6
and RA7
9. EC External Clock with FOSC/4 output
10. ECIO External Clock with I/O on RA6
2.2 Crystal Oscillator/Ceramic
Resonators
In XT, LP, HS or HSPLL Oscillator modes, a crystal or
ceramic resonator is connected to the OSC1 and
OSC2 pins to establish oscillation. Figure 2-1 shows
the pin connections.
The oscillator design requires the use of a parallel cut
crystal.
FIGURE 2-1: CRYSTAL/CERAMIC
RESONATOR OPERATION
(XT, LP, HS OR HSPLL
CONFIGURATION)
TABLE 2-1: CAPACITOR SELECTION FOR
CERAMIC RESONATORS
Note: Use of a series cut crystal may give a
frequency out of the crystal manufacturer’s
specifications.
Typical Capacitor Values Used:
Mode Freq OSC1 OSC2
XT 455 kHz
2.0 MHz
4.0 MHz
56 pF
47 pF
33 pF
56 pF
47 pF
33 pF
HS 8.0 MHz
16.0 MHz
27 pF
22 pF
27 pF
22 pF
Capacitor values are for design guidance only.
These capacitors were tested with the resonators
listed below for basic start-up and operation. These
values are not optimized.
Different capacitor values may be required to produce
acceptable oscillator operation. The user should test
the performance of the oscillator over the expected
VDD and temperature range for the application.
See the notes following Table 2-2 for additional
information.
Resonators Used:
455 kHz 4.0 MHz
2.0 MHz 8.0 MHz
16.0 MHz
Note 1: See Table 2-1 and Table 2-2 for initial
values of C1 and C2.
2: A series resistor (RS) may be required for
AT strip cut crystals.
3: RF varies with the oscillator mode chosen.
C1(1)
C2(1)
XTAL
OSC2
OSC1
RF(3)
Sleep
To
Logic
PIC18FXXXX
RS(2)
InternalPIC18F1220/1320
DS39605F-page 12 © 2007 Microchip Technology Inc.
TABLE 2-2: CAPACITOR SELECTION FOR
CRYSTAL OSCILLATOR
An external clock source may also be connected to the
OSC1 pin in the HS mode, as shown in Figure 2-2.
FIGURE 2-2: EXTERNAL CLOCK INPUT
OPERATION (HS OSC
CONFIGURATION)
2.3 HSPLL
A Phase Locked Loop (PLL) circuit is provided as an
option for users who wish to use a lower frequency
crystal oscillator circuit, or to clock the device up to its
highest rated frequency from a crystal oscillator. This
may be useful for customers who are concerned with
EMI due to high-frequency crystals.
The HSPLL mode makes use of the HS mode oscillator
for frequencies up to 10 MHz. A PLL then multiplies the
oscillator output frequency by 4 to produce an internal
clock frequency up to 40 MHz.
The PLL is enabled only when the oscillator configuration
bits are programmed for HSPLL mode. If
programmed for any other mode, the PLL is not
enabled.
FIGURE 2-3: PLL BLOCK DIAGRAM
Osc Type Crystal
Freq
Typical Capacitor Values
Tested:
C1 C2
LP 32 kHz 33 pF 33 pF
200 kHz 15 pF 15 pF
XT 1 MHz 33 pF 33 pF
4 MHz 27 pF 27 pF
HS 4 MHz 27 pF 27 pF
8 MHz 22 pF 22 pF
20 MHz 15 pF 15 pF
Capacitor values are for design guidance only.
These capacitors were tested with the crystals listed
below for basic start-up and operation. These values
are not optimized.
Different capacitor values may be required to produce
acceptable oscillator operation. The user should test
the performance of the oscillator over the expected
VDD and temperature range for the application.
See the notes following this table for additional
information.
Crystals Used:
32 kHz 4 MHz
200 kHz 8 MHz
1 MHz 20 MHz
Note 1: Higher capacitance increases the stability
of oscillator, but also increases the start-up
time.
2: When operating below 3V VDD, or when
using certain ceramic resonators at any
voltage, it may be necessary to use the
HS mode or switch to a crystal oscillator.
3: Since each resonator/crystal has its own
characteristics, the user should consult
the resonator/crystal manufacturer for
appropriate values of external
components.
4: RS may be required to avoid overdriving
crystals with low drive level specification.
5: Always verify oscillator performance over
the VDD and temperature range that is
expected for the application.
OSC1
Open OSC2
Clock from
Ext. System PIC18FXXXX
(HS Mode) MUX
VCO
Loop
Filter
Crystal
Osc
OSC2
OSC1
PLL Enable
FIN
FOUT
SYSCLK
Phase
Comparator
HS Oscillator Enable
÷4
(from Configuration Register 1H)© 2007 Microchip Technology Inc. DS39605F-page 13
PIC18F1220/1320
2.4 External Clock Input
The EC and ECIO Oscillator modes require an external
clock source to be connected to the OSC1 pin. There is
no oscillator start-up time required after a Power-on
Reset, or after an exit from Sleep mode.
In the EC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes, or to synchronize other
logic. Figure 2-4 shows the pin connections for the EC
Oscillator mode.
FIGURE 2-4: EXTERNAL CLOCK INPUT
OPERATION
(EC CONFIGURATION)
The ECIO Oscillator mode functions like the EC mode,
except that the OSC2 pin becomes an additional general
purpose I/O pin. The I/O pin becomes bit 6 of
PORTA (RA6). Figure 2-5 shows the pin connections
for the ECIO Oscillator mode.
FIGURE 2-5: EXTERNAL CLOCK INPUT
OPERATION
(ECIO CONFIGURATION)
2.5 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, the resistor (REXT) and capacitor (CEXT) values
and the operating temperature. In addition to this,
the oscillator frequency will vary from unit to unit due to
normal manufacturing 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
R and C components used. Figure 2-6 shows how the
R/C combination is connected.
In the RC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes, or to synchronize other
logic.
FIGURE 2-6: RC OSCILLATOR MODE
The RCIO Oscillator mode (Figure 2-7) functions like
the RC mode, except that the OSC2 pin becomes an
additional general purpose I/O pin. The I/O pin
becomes bit 6 of PORTA (RA6).
FIGURE 2-7: RCIO OSCILLATOR MODE
OSC1/CLKI
FOSC/4 OSC2/CLKO
Clock from
Ext. System PIC18FXXXX
OSC1/CLKI
RA6 I/O (OSC2)
Clock from
Ext. System PIC18FXXXX
OSC2/CLKO
CEXT
REXT
PIC18FXXXX
OSC1
FOSC/4
Internal
Clock
VDD
VSS
Recommended values: 3 kΩ ≤ REXT ≤ 100 kΩ
CEXT > 20 pF
CEXT
REXT
PIC18FXXXX
OSC1 Internal
Clock
VDD
VSS
Recommended values: 3 kΩ ≤ REXT ≤ 100 kΩ
CEXT > 20 pF
RA6 I/O (OSC2)PIC18F1220/1320
DS39605F-page 14 © 2007 Microchip Technology Inc.
2.6 Internal Oscillator Block
The PIC18F1220/1320 devices include an internal
oscillator block, which generates two different clock
signals; either can be used as the system’s clock
source. This can eliminate the need for external
oscillator circuits on the OSC1 and/or OSC2 pins.
The main output (INTOSC) is an 8 MHz clock source,
which can be used to directly drive the system clock. It
also drives a postscaler, which can provide a range of
clock frequencies from 125 kHz to 4 MHz. The
INTOSC output is enabled when a system clock
frequency from 125 kHz to 8 MHz is selected.
The other clock source is the internal RC oscillator
(INTRC), which provides a 31 kHz output. The INTRC
oscillator is enabled by selecting the internal oscillator
block as the system clock source, or when any of the
following are enabled:
• Power-up Timer
• Fail-Safe Clock Monitor
• Watchdog Timer
• Two-Speed Start-up
These features are discussed in greater detail in
Section 19.0 “Special Features of the CPU”.
The clock source frequency (INTOSC direct, INTRC
direct or INTOSC postscaler) is selected by configuring
the IRCF bits of the OSCCON register (Register 2-2).
2.6.1 INTIO MODES
Using the internal oscillator as the clock source can
eliminate the need for up to two external oscillator pins,
which can then be used for digital I/O. Two distinct
configurations are available:
• In INTIO1 mode, the OSC2 pin outputs FOSC/4,
while OSC1 functions as RA7 for digital input and
output.
• In INTIO2 mode, OSC1 functions as RA7 and
OSC2 functions as RA6, both for digital input and
output.
2.6.2 INTRC OUTPUT FREQUENCY
The internal oscillator block is calibrated at the factory
to produce an INTOSC output frequency of 8.0 MHz
(see Table 22-6). This changes the frequency of the
INTRC source from its nominal 31.25 kHz. Peripherals
and features that depend on the INTRC source will be
affected by this shift in frequency.
Once set during factory calibration, the INTRC
frequency will remain within ±2% as temperature and
VDD change across their full specified operating
ranges.
2.6.3 OSCTUNE REGISTER
The internal oscillator’s output has been calibrated at
the factory, but can be adjusted in the user’s application.
This is done by writing to the OSCTUNE register
(Register 2-1). The tuning sensitivity is constant
throughout the tuning range.
When the OSCTUNE register is modified, the INTOSC
and INTRC frequencies will begin shifting to the new
frequency. The INTRC clock will reach the new
frequency within 8 clock cycles (approximately
8 * 32 μs = 256 μs). The INTOSC clock will stabilize
within 1 ms. Code execution continues during this shift.
There is no indication that the shift has occurred.
Operation of features that depend on the INTRC clock
source frequency, such as the WDT, Fail-Safe Clock
Monitor and peripherals, will also be affected by the
change in frequency.© 2007 Microchip Technology Inc. DS39605F-page 15
PIC18F1220/1320
REGISTER 2-1: OSCTUNE: OSCILLATOR TUNING REGISTER
2.7 Clock Sources and Oscillator
Switching
Like previous PIC18 devices, the PIC18F1220/1320
devices include a feature that allows the system clock
source to be switched from the main oscillator to an
alternate low-frequency clock source. PIC18F1220/
1320 devices offer two alternate clock sources. When
enabled, these give additional options for switching to
the various power managed operating modes.
Essentially, there are three clock sources for these
devices:
• Primary oscillators
• Secondary oscillators
• Internal oscillator block
The primary oscillators include the External Crystal
and Resonator modes, the External RC modes, the
External Clock modes and the internal oscillator block.
The particular mode is defined on POR by the contents
of Configuration Register 1H. The details of these
modes are covered earlier in this chapter.
The secondary oscillators are those external sources
not connected to the OSC1 or OSC2 pins. These
sources may continue to operate even after the
controller is placed in a power managed mode.
PIC18F1220/1320 devices offer only the Timer1
oscillator as a secondary oscillator. This oscillator, in all
power managed modes, is often the time base for
functions such as a real-time clock.
Most often, a 32.768 kHz watch crystal is connected
between the RB6/T1OSO and RB7/T1OSI pins. Like
the LP mode oscillator circuit, loading capacitors are
also connected from each pin to ground. These pins
are also used during ICSP operations.
The Timer1 oscillator is discussed in greater detail in
Section 12.2 “Timer1 Oscillator”.
In addition to being a primary clock source, the internal
oscillator block is available as a power managed
mode clock source. The INTRC source is also used as
the clock source for several special features, such as
the WDT and Fail-Safe Clock Monitor.
The clock sources for the PIC18F1220/1320 devices
are shown in Figure 2-8. See Section 12.0 “Timer1
Module” for further details of the Timer1 oscillator. See
Section 19.1 “Configuration Bits” for configuration
register details.
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — TUN5 TUN4 TUN3 TUN2 TUN1 TUN0
bit 7 bit 0
bit 7-6 Unimplemented: Read as ‘0’
bit 5-0 TUN<5:0>: Frequency Tuning bits
011111 = Maximum frequency
• •
• •
000001
000000 = Center frequency. Oscillator module is running at the calibrated frequency.
111111
• •
• •
100000 = Minimum frequency
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 16 © 2007 Microchip Technology Inc.
2.7.1 OSCILLATOR CONTROL REGISTER
The OSCCON register (Register 2-2) controls several
aspects of the system clock’s operation, both in full
power operation and in power managed modes.
The System Clock Select bits, SCS1:SCS0, select the
clock source that is used when the device is operating in
power managed modes. The available clock sources are
the primary clock (defined in Configuration Register 1H),
the secondary clock (Timer1 oscillator) and the internal
oscillator block. The clock selection has no effect until a
SLEEP instruction is executed and the device enters a
power managed mode of operation. The SCS bits are
cleared on all forms of Reset.
The Internal Oscillator Select bits, IRCF2:IRCF0, select
the frequency output of the internal oscillator block that
is used to drive the system clock. The choices are the
INTRC source, the INTOSC source (8 MHz), or one of
the six frequencies derived from the INTOSC
postscaler (125 kHz to 4 MHz). If the internal oscillator
block is supplying the system clock, changing the
states of these bits will have an immediate change on
the internal oscillator’s output.
The OSTS, IOFS and T1RUN bits indicate which clock
source is currently providing the system clock. The
OSTS indicates that the Oscillator Start-up Timer has
timed out and the primary clock is providing the system
clock in Primary Clock modes. The IOFS bit indicates
when the internal oscillator block has stabilized and is
providing the system clock in RC Clock modes or
during Two-Speed Start-ups. The T1RUN bit
(T1CON<6>) indicates when the Timer1 oscillator is
providing the system clock in Secondary Clock modes.
In power managed modes, only one of these three bits
will be set at any time. If none of these bits are set, the
INTRC is providing the system clock, or the internal
oscillator block has just started and is not yet stable.
The IDLEN bit controls the selective shutdown of the
controller’s CPU in power managed modes. The uses
of these bits are discussed in more detail in
Section 3.0 “Power Managed Modes”.
FIGURE 2-8: PIC18F1220/1320 CLOCK DIAGRAM
Note 1: The Timer1 oscillator must be enabled to
select the secondary clock source. The
Timer1 oscillator is enabled by setting the
T1OSCEN bit in the Timer1 Control register
(T1CON<3>). If the Timer1 oscillator
is not enabled, then any attempt to select
a secondary clock source when
executing a SLEEP instruction will be
ignored.
2: It is recommended that the Timer1 oscillator
be operating and stable before executing
the SLEEP instruction or a very
long delay may occur while the Timer1
oscillator starts.
PIC18F1220/1320
4 x PLL
CONFIG1H <3:0>
Secondary Oscillator
T1OSCEN
Enable
Oscillator
T1OSO
T1OSI
Clock Source Option
for Other Modules
OSC1
OSC2
Sleep
Primary Oscillator
HSPLL
LP, XT, HS, RC, EC
T1OSC
CPU
Peripherals
IDLEN
Postscaler
MUX
MUX
8
4 MHz
2 MHz
1 MHz
500 kHz
125 kHz
250 kHz
OSCCON<6:4>
111
110
101
100
011
010
001
000 31 kHz
INTRC
Source
Internal
Oscillator
Block
WDT, FSCM
8 MHz
Internal Oscillator
(INTOSC)
OSCCON<6:4>
Clock
Control OSCCON<1:0>© 2007 Microchip Technology Inc. DS39605F-page 17
PIC18F1220/1320
REGISTER 2-2: OSCCON REGISTER
R/W-0 R/W-0 R/W-0 R/W-0 R(1) R-0 R/W-0 R/W-0
IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0
bit 7 bit 0
bit 7 IDLEN: Idle Enable bits
1 = Idle mode enabled; CPU core is not clocked in power managed modes
0 = Run mode enabled; CPU core is clocked in Run modes, but not Sleep mode
bit 6-4 IRCF2:IRCF0: Internal Oscillator Frequency Select bits
111 = 8 MHz (8 MHz source drives clock directly)
110 = 4 MHz
101 = 2 MHz
100 = 1 MHz
011 = 500 kHz
010 = 250 kHz
001 = 125 kHz
000 = 31 kHz (INTRC source drives clock directly)
bit 3 OSTS: Oscillator Start-up Time-out Status bit
1 = Oscillator Start-up Timer time-out has expired; primary oscillator is running
0 = Oscillator Start-up Timer time-out is running; primary oscillator is not ready
bit 2 IOFS: INTOSC Frequency Stable bit
1 = INTOSC frequency is stable
0 = INTOSC frequency is not stable
bit 1-0 SCS1:SCS0: System Clock Select bits
1x = Internal oscillator block (RC modes)
01 = Timer1 oscillator (Secondary modes)
00 = Primary oscillator (Sleep and PRI_IDLE modes)
Note 1: Depends on state of the IESO bit in Configuration Register 1H.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 18 © 2007 Microchip Technology Inc.
2.7.2 OSCILLATOR TRANSITIONS
The PIC18F1220/1320 devices contain circuitry to
prevent clocking “glitches” when switching between
clock sources. A short pause in the system clock
occurs during the clock switch. The length of this pause
is between 8 and 9 clock periods of the new clock
source. This ensures that the new clock source is
stable and that its pulse width will not be less than the
shortest pulse width of the two clock sources.
Clock transitions are discussed in greater detail in
Section 3.1.2 “Entering Power Managed Modes”.
2.8 Effects of Power Managed Modes
on the Various Clock Sources
When the device executes a SLEEP instruction, the
system is switched to one of the power managed
modes, depending on the state of the IDLEN and
SCS1:SCS0 bits of the OSCCON register. See
Section 3.0 “Power Managed Modes” for details.
When PRI_IDLE mode is selected, the designated primary
oscillator continues to run without interruption.
For all other power managed modes, the oscillator
using the OSC1 pin is disabled. The OSC1 pin (and
OSC2 pin, if used by the oscillator) will stop oscillating.
In Secondary Clock modes (SEC_RUN and
SEC_IDLE), the Timer1 oscillator is operating and
providing the system clock. The Timer1 oscillator may
also run in all power managed modes if required to
clock Timer1 or Timer3.
In Internal Oscillator modes (RC_RUN and RC_IDLE),
the internal oscillator block provides the system clock
source. The INTRC output can be used directly to
provide the system clock and may be enabled to
support various special features, regardless of the
power managed mode (see Section 19.2 “Watchdog
Timer (WDT)” through Section 19.4 “Fail-Safe Clock
Monitor”). The INTOSC output at 8 MHz may be used
directly to clock the system, or may be divided down
first. The INTOSC output is disabled if the system clock
is provided directly from the INTRC output.
If the Sleep mode is selected, all clock sources are
stopped. Since all the transistor switching currents
have been stopped, Sleep mode achieves the lowest
current consumption of the device (only leakage
currents).
Enabling any on-chip feature that will operate during
Sleep will increase the current consumed during Sleep.
The INTRC is required to support WDT operation. The
Timer1 oscillator may be operating to support a realtime
clock. Other features may be operating that do not
require a system clock source (i.e., INTn pins, A/D
conversions and others).
2.9 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 is stable under normal
circumstances and the primary clock is operating
and stable. For additional information on power-up
delays, see Sections 4.1 through 4.5.
The first timer is the Power-up Timer (PWRT), which
provides a fixed delay on power-up (parameter 33,
Table 22-8) if enabled in Configuration Register 2L.
The second timer is the Oscillator Start-up Timer
(OST), intended to keep the chip in Reset until the
crystal oscillator is stable (LP, XT and HS modes). The
OST does this by counting 1024 oscillator cycles
before allowing the oscillator to clock the device.
When the HSPLL Oscillator mode is selected, the
device is kept in Reset for an additional 2 ms following
the HS mode OST delay, so the PLL can lock to the
incoming clock frequency.
There is a delay of 5 to 10 μs following POR while the
controller becomes ready to execute instructions. This
delay runs concurrently with any other delays. This
may be the only delay that occurs when any of the EC,
RC or INTIO modes are used as the primary clock
source.
TABLE 2-3: OSC1 AND OSC2 PIN STATES IN SLEEP MODE
Oscillator Mode OSC1 Pin OSC2 Pin
RC, INTIO1 Floating, external resistor should pull high At logic low (clock/4 output)
RCIO, INTIO2 Floating, external resistor should pull high Configured as PORTA, bit 6
ECIO Floating, pulled by external clock Configured as PORTA, bit 6
EC Floating, pulled by external clock At logic low (clock/4 output)
LP, XT and HS Feedback inverter disabled at quiescent
voltage level
Feedback inverter disabled at quiescent
voltage level
Note: See Table 4-1 in Section 4.0 “Reset” for time-outs due to Sleep and MCLR Reset.© 2007 Microchip Technology Inc. DS39605F-page 19
PIC18F1220/1320
3.0 POWER MANAGED MODES
The PIC18F1220/1320 devices offer a total of six operating
modes for more efficient power management
(see Table 3-1). These provide a variety of options for
selective power conservation in applications where
resources may be limited (i.e., battery powered
devices).
There are three categories of power managed modes:
• Sleep mode
• Idle modes
• Run modes
These categories define which portions of the device
are clocked and sometimes, what speed. The Run and
Idle modes may use any of the three available clock
sources (primary, secondary or INTOSC multiplexer);
the Sleep mode does not use a clock source.
The clock switching feature offered in other PIC18
devices (i.e., using the Timer1 oscillator in place of the
primary oscillator) and the Sleep mode offered by all
PIC® devices (where all system clocks are stopped) are
both offered in the PIC18F1220/1320 devices
(SEC_RUN and Sleep modes, respectively). However,
additional power managed modes are available that
allow the user greater flexibility in determining what
portions of the device are operating. The power managed
modes are event driven; that is, some specific
event must occur for the device to enter or (more
particularly) exit these operating modes.
For PIC18F1220/1320 devices, the power managed
modes are invoked by using the existing SLEEP
instruction. All modes exit to PRI_RUN mode when triggered
by an interrupt, a Reset or a WDT time-out
(PRI_RUN mode is the normal full power execution
mode; the CPU and peripherals are clocked by the primary
oscillator source). In addition, power managed
Run modes may also exit to Sleep mode, or their
corresponding Idle mode.
3.1 Selecting Power Managed Modes
Selecting a power managed mode requires deciding if
the CPU is to be clocked or not and selecting a clock
source. The IDLEN bit controls CPU clocking, while the
SCS1:SCS0 bits select a clock source. The individual
modes, bit settings, clock sources and affected
modules are summarized in Table 3-1.
3.1.1 CLOCK SOURCES
The clock source is selected by setting the SCS bits of
the OSCCON register (Register 2-2). Three clock
sources are available for use in power managed Idle
modes: the primary clock (as configured in Configuration
Register 1H), the secondary clock (Timer1 oscillator)
and the internal oscillator block. The secondary and
internal oscillator block sources are available for the
power managed modes (PRI_RUN mode is the normal
full power execution mode; the CPU and peripherals are
clocked by the primary oscillator source).
TABLE 3-1: POWER MANAGED MODES
Mode
OSCCON Bits Module Clocking
Available Clock and Oscillator Source IDLEN
<7>
SCS1:SCS0
<1:0> CPU Peripherals
Sleep 0 00 Off Off None – All clocks are disabled
PRI_RUN 0 00 Clocked Clocked Primary – LP, XT, HS, HSPLL, RC, EC, INTRC(1)
This is the normal full power execution mode.
SEC_RUN 0 01 Clocked Clocked Secondary – Timer1 Oscillator
RC_RUN 0 1x Clocked Clocked Internal Oscillator Block(1)
PRI_IDLE 1 00 Off Clocked Primary – LP, XT, HS, HSPLL, RC, EC
SEC_IDLE 1 01 Off Clocked Secondary – Timer1 Oscillator
RC_IDLE 1 1x Off Clocked Internal Oscillator Block(1)
Note 1: Includes INTOSC and INTOSC postscaler, as well as the INTRC source.PIC18F1220/1320
DS39605F-page 20 © 2007 Microchip Technology Inc.
3.1.2 ENTERING POWER MANAGED
MODES
In general, entry, exit and switching between power
managed clock sources requires clock source
switching. In each case, the sequence of events is the
same.
Any change in the power managed mode begins with
loading the OSCCON register and executing a SLEEP
instruction. The SCS1:SCS0 bits select one of three
power managed clock sources; the primary clock (as
defined in Configuration Register 1H), the secondary
clock (the Timer1 oscillator) and the internal oscillator
block (used in RC modes). Modifying the SCS bits will
have no effect until a SLEEP instruction is executed.
Entry to the power managed mode is triggered by the
execution of a SLEEP instruction.
Figure 3-5 shows how the system is clocked while
switching from the primary clock to the Timer1 oscillator.
When the SLEEP instruction is executed, clocks to
the device are stopped at the beginning of the next
instruction cycle. Eight clock cycles from the new clock
source are counted to synchronize with the new clock
source. After eight clock pulses from the new clock
source are counted, clocks from the new clock source
resume clocking the system. The actual length of the
pause is between eight and nine clock periods from the
new clock source. This ensures that the new clock
source is stable and that its pulse width will not be less
than the shortest pulse width of the two clock sources.
Three bits indicate the current clock source: OSTS and
IOFS in the OSCCON register and T1RUN in the
T1CON register. Only one of these bits will be set while
in a power managed mode. When the OSTS bit is set,
the primary clock is providing the system clock. When
the IOFS bit is set, the INTOSC output is providing a
stable 8 MHz clock source and is providing the system
clock. When the T1RUN bit is set, the Timer1 oscillator
is providing the system clock. If none of these bits are
set, then either the INTRC clock source is clocking the
system, or the INTOSC source is not yet stable.
If the internal oscillator block is configured as the primary
clock source in Configuration Register 1H, then
both the OSTS and IOFS bits may be set when in
PRI_RUN or PRI_IDLE modes. This indicates that the
primary clock (INTOSC output) is generating a stable
8 MHz output. Entering an RC power managed mode
(same frequency) would clear the OSTS bit.
3.1.3 MULTIPLE SLEEP COMMANDS
The power managed mode that is invoked with the
SLEEP instruction is determined by the settings of the
IDLEN and SCS bits at the time the instruction is executed.
If another SLEEP instruction is executed, the
device will enter the power managed mode specified by
these same bits at that time. If the bits have changed,
the device will enter the new power managed mode
specified by the new bit settings.
3.1.4 COMPARISONS BETWEEN RUN
AND IDLE MODES
Clock source selection for the Run modes is identical to
the corresponding Idle modes. When a SLEEP instruction
is executed, the SCS bits in the OSCCON register
are used to switch to a different clock source. As a
result, if there is a change of clock source at the time a
SLEEP instruction is executed, a clock switch will occur.
In Idle modes, the CPU is not clocked and is not running.
In Run modes, the CPU is clocked and executing
code. This difference modifies the operation of the
WDT when it times out. In Idle modes, a WDT time-out
results in a wake from power managed modes. In Run
modes, a WDT time-out results in a WDT Reset (see
Table 3-2).
During a wake-up from an Idle mode, the CPU starts
executing code by entering the corresponding Run
mode until the primary clock becomes ready. When the
primary clock becomes ready, the clock source is automatically
switched to the primary clock. The IDLEN and
SCS bits are unchanged during and after the wake-up.
Figure 3-2 shows how the system is clocked during the
clock source switch. The example assumes the device
was in SEC_IDLE or SEC_RUN mode when a wake is
triggered (the primary clock was configured in HSPLL
mode).
Note 1: Caution should be used when modifying a
single IRCF bit. If VDD is less than 3V, it is
possible to select a higher clock speed
than is supported by the low VDD.
Improper device operation may result if
the VDD/FOSC specifications are violated.
2: Executing a SLEEP instruction does not
necessarily place the device into Sleep
mode; executing a SLEEP instruction is
simply a trigger to place the controller into
a power managed mode selected by the
OSCCON register, one of which is Sleep
mode.© 2007 Microchip Technology Inc. DS39605F-page 21
PIC18F1220/1320
3.2 Sleep Mode
The power managed Sleep mode in the PIC18F1220/
1320 devices is identical to that offered in all other PIC
microcontrollers. It is entered by clearing the IDLEN
and SCS1:SCS0 bits (this is the Reset state) and
executing the SLEEP instruction. This shuts down the
primary oscillator and the OSTS bit is cleared (see
Figure 3-1).
When a wake event occurs in Sleep mode (by interrupt,
Reset or WDT time-out), the system will not be clocked
until the primary clock source becomes ready (see
Figure 3-2), or it will be clocked from the internal
oscillator block if either the Two-Speed Start-up or the
Fail-Safe Clock Monitor are enabled (see Section 19.0
“Special Features of the CPU”). In either case, the
OSTS bit is set when the primary clock is providing the
system clocks. The IDLEN and SCS bits are not
affected by the wake-up.
3.3 Idle Modes
The IDLEN bit allows the microcontroller’s CPU to be
selectively shut down while the peripherals continue to
operate. Clearing IDLEN allows the CPU to be clocked.
Setting IDLEN disables clocks to the CPU, effectively
stopping program execution (see Register 2-2). The
peripherals continue to be clocked regardless of the
setting of the IDLEN bit.
There is one exception to how the IDLEN bit functions.
When all the low-power OSCCON bits are cleared
(IDLEN:SCS1:SCS0 = 000), the device enters Sleep
mode upon the execution of the SLEEP instruction. This
is both the Reset state of the OSCCON register and the
setting that selects Sleep mode. This maintains
compatibility with other PIC devices that do not offer
power managed modes.
If the Idle Enable bit, IDLEN (OSCCON<7>), is set to a
‘1’ when a SLEEP instruction is executed, the
peripherals will be clocked from the clock source
selected using the SCS1:SCS0 bits; however, the CPU
will not be clocked. Since the CPU is not executing
instructions, the only exits from any of the Idle modes
are by interrupt, WDT time-out or a Reset.
When a wake event occurs, CPU execution is delayed
approximately 10 μs while it becomes ready to execute
code. When the CPU begins executing code, it is
clocked by the same clock source as was selected in
the power managed mode (i.e., when waking from
RC_IDLE mode, the internal oscillator block will clock
the CPU and peripherals until the primary clock source
becomes ready – this is essentially RC_RUN mode).
This continues until the primary clock source becomes
ready. When the primary clock becomes ready, the
OSTS bit is set and the system clock source is
switched to the primary clock (see Figure 3-4). The
IDLEN and SCS bits are not affected by the wake-up.
While in any Idle mode or the Sleep mode, a WDT
time-out will result in a WDT wake-up to full power
operation.
TABLE 3-2: COMPARISON BETWEEN POWER MANAGED MODES
Power
Managed
Mode
CPU is Clocked by ... WDT Time-out
causes a ...
Peripherals are
Clocked by ...
Clock during Wake-up
(while primary becomes
ready)
Sleep Not clocked (not running) Wake-up Not clocked None or INTOSC multiplexer
if Two-Speed Start-up or
Fail-Safe Clock Monitor are
enabled
Any Idle mode Not clocked (not running) Wake-up Primary, Secondary or
INTOSC multiplexer
Unchanged from Idle mode
(CPU operates as in
corresponding Run mode)
Any Run mode Primary or secondary
clocks or INTOSC
multiplexer
Reset Primary or secondary
clocks or INTOSC
multiplexer
Unchanged from Run modePIC18F1220/1320
DS39605F-page 22 © 2007 Microchip Technology Inc.
FIGURE 3-1: TIMING TRANSITION FOR ENTRY TO SLEEP MODE
FIGURE 3-2: TRANSITION TIMING FOR WAKE FROM SLEEP (HSPLL)
Q2 Q3 Q4
OSC1
Peripheral
Sleep
Program
Q1 Q1
Counter
Clock
CPU
Clock
PC PC + 2
Q3 Q4 Q1 Q2
OSC1
Peripheral
Program PC
PLL Clock
Q3 Q4
Output
CPU Clock
Q1 Q2 Q3 Q4 Q1 Q2
Clock
Counter PC + 6 PC + 8
Q1 Q2 Q3 Q4
Wake Event
Note 1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
TOST(1) TPLL(1)
OSTS bit Set
PC + 2 PC + 4© 2007 Microchip Technology Inc. DS39605F-page 23
PIC18F1220/1320
3.3.1 PRI_IDLE MODE
This mode is unique among the three Low-Power Idle
modes, in that it does not disable the primary system
clock. For timing sensitive applications, this allows for
the fastest resumption of device operation with its more
accurate primary clock source, since the clock source
does not have to “warm up” or transition from another
oscillator.
PRI_IDLE mode is entered by setting the IDLEN bit,
clearing the SCS bits and executing a SLEEP instruction.
Although the CPU is disabled, the peripherals
continue to be clocked from the primary clock source
specified in Configuration Register 1H. The OSTS bit
remains set in PRI_IDLE mode (see Figure 3-3).
When a wake event occurs, the CPU is clocked from
the primary clock source. A delay of approximately
10 μs is required between the wake event and code
execution starts. This is required to allow the CPU to
become ready to execute instructions. After the wakeup,
the OSTS bit remains set. The IDLEN and SCS bits
are not affected by the wake-up (see Figure 3-4).
FIGURE 3-3: TRANSITION TIMING TO PRI_IDLE MODE
FIGURE 3-4: TRANSITION TIMING FOR WAKE FROM PRI_IDLE MODE
Q1
Peripheral
Program PC PC + 2
OSC1
Q3 Q4 Q1
CPU Clock
Clock
Counter
Q2
OSC1
Peripheral
Program PC
CPU Clock
PC + 2
Q1 Q3 Q4
Clock
Counter
Q2
Wake Event
CPU Start-up DelayPIC18F1220/1320
DS39605F-page 24 © 2007 Microchip Technology Inc.
3.3.2 SEC_IDLE MODE
In SEC_IDLE mode, the CPU is disabled, but the
peripherals continue to be clocked from the Timer1
oscillator. This mode is entered by setting the Idle bit,
modifying bits, SCS1:SCS0 = 01 and executing a
SLEEP instruction. When the clock source is switched
(see Figure 3-5) to the Timer1 oscillator, the primary
oscillator is shut down, the OSTS bit is cleared and the
T1RUN bit is set.
When a wake event occurs, the peripherals continue to
be clocked from the Timer1 oscillator. After a 10 μs
delay following the wake event, the CPU begins executing
code, being clocked by the Timer1 oscillator. The
microcontroller operates in SEC_RUN mode until the
primary clock becomes ready. When the primary clock
becomes ready, a clock switchback to the primary clock
occurs (see Figure 3-6). When the clock switch is complete,
the T1RUN bit is cleared, the OSTS bit is set and
the primary clock is providing the system clock. The
IDLEN and SCS bits are not affected by the wake-up.
The Timer1 oscillator continues to run.
FIGURE 3-5: TIMING TRANSITION FOR ENTRY TO SEC_IDLE MODE
FIGURE 3-6: TIMING TRANSITION FOR WAKE FROM SEC_RUN MODE (HSPLL)
Note: The Timer1 oscillator should already be
running prior to entering SEC_IDLE mode.
If the T1OSCEN bit is not set when the
SLEEP instruction is executed, the SLEEP
instruction will be ignored and entry to
SEC_IDLE mode will not occur. If the
Timer1 oscillator is enabled, but not yet
running, peripheral clocks will be delayed
until the oscillator has started; in such situations,
initial oscillator operation is far
from stable and unpredictable operation
may result.
Q2 Q3 Q4
OSC1
Peripheral
Program
Q1
T1OSI
Q1
Counter
Clock
CPU
Clock
PC PC + 2
12345678
Clock Transition
Q1 Q3 Q4
OSC1
Peripheral
Program PC PC + 2
T1OSI
PLL Clock
Q1
PC + 6
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 4
Clock
Counter
Q2 Q2 Q3
Note 1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
Wake from Interrupt Event
TPLL(1)
1 2 3 45678
Clock Transition
OSTS bit Set
TOST(1)© 2007 Microchip Technology Inc. DS39605F-page 25
PIC18F1220/1320
3.3.3 RC_IDLE MODE
In RC_IDLE mode, the CPU is disabled, but the peripherals
continue to be clocked from the internal oscillator
block using the INTOSC multiplexer. This mode allows
for controllable power conservation during Idle periods.
This mode is entered by setting the IDLEN bit, setting
SCS1 (SCS0 is ignored) and executing a SLEEP
instruction. The INTOSC multiplexer may be used to
select a higher clock frequency by modifying the IRCF
bits before executing the SLEEP instruction. When the
clock source is switched to the INTOSC multiplexer
(see Figure 3-7), the primary oscillator is shut down
and the OSTS bit is cleared.
If the IRCF bits are set to a non-zero value (thus,
enabling the INTOSC output), the IOFS bit becomes
set after the INTOSC output becomes stable, in about
1 ms. Clocks to the peripherals continue while the
INTOSC source stabilizes. If the IRCF bits were
previously at a non-zero value before the SLEEP
instruction was executed and the INTOSC source was
already stable, the IOFS bit will remain set. If the IRCF
bits are all clear, the INTOSC output is not enabled and
the IOFS bit will remain clear; there will be no indication
of the current clock source.
When a wake event occurs, the peripherals continue to
be clocked from the INTOSC multiplexer. After a 10 μs
delay following the wake event, the CPU begins executing
code, being clocked by the INTOSC multiplexer.
The microcontroller operates in RC_RUN mode until
the primary clock becomes ready. When the primary
clock becomes ready, a clock switchback to the primary
clock occurs (see Figure 3-8). When the clock switch is
complete, the IOFS bit is cleared, the OSTS bit is set
and the primary clock is providing the system clock.
The IDLEN and SCS bits are not affected by the wakeup.
The INTRC source will continue to run if either the
WDT or the Fail-Safe Clock Monitor is enabled.
FIGURE 3-7: TIMING TRANSITION TO RC_IDLE MODE
FIGURE 3-8: TIMING TRANSITION FOR WAKE FROM RC_RUN MODE (RC_RUN TO PRI_RUN)
Q2 Q3 Q4
OSC1
Peripheral
Program
Q1
INTRC
Q1
Counter
Clock
CPU
Clock
PC PC + 2
12345678
Clock Transition
Q1 Q3 Q4
OSC1
Peripheral
Program PC PC + 2
INTOSC
PLL Clock
Q1
PC + 6
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 4
Clock
Counter
Q2 Q2 Q3
Note 1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
Wake from Interrupt Event
TOST(1) TPLL(1)
12345678
Clock Transition
OSTS bit Set
Multiplexer
Q4PIC18F1220/1320
DS39605F-page 26 © 2007 Microchip Technology Inc.
3.4 Run Modes
If the IDLEN bit is clear when a SLEEP instruction is
executed, the CPU and peripherals are both clocked
from the source selected using the SCS1:SCS0 bits.
While these operating modes may not afford the power
conservation of Idle or Sleep modes, they do allow the
device to continue executing instructions by using a
lower frequency clock source. RC_RUN mode also
offers the possibility of executing code at a frequency
greater than the primary clock.
Wake-up from a power managed Run mode can be
triggered by an interrupt, or any Reset, to return to full
power operation. As the CPU is executing code in Run
modes, several additional exits from Run modes are
possible. They include exit to Sleep mode, exit to a corresponding
Idle mode and exit by executing a RESET
instruction. While the device is in any of the power
managed Run modes, a WDT time-out will result in a
WDT Reset.
3.4.1 PRI_RUN MODE
The PRI_RUN mode is the normal full power execution
mode. If the SLEEP instruction is never executed, the
microcontroller operates in this mode (a SLEEP instruction
is executed to enter all other power managed
modes). All other power managed modes exit to
PRI_RUN mode when an interrupt or WDT time-out
occur.
There is no entry to PRI_RUN mode. The OSTS bit is
set. The IOFS bit may be set if the internal oscillator
block is the primary clock source (see Section 2.7.1
“Oscillator Control Register”).
3.4.2 SEC_RUN MODE
The SEC_RUN mode is the compatible mode to the
“clock switching” feature offered in other PIC18
devices. In this mode, the CPU and peripherals are
clocked from the Timer1 oscillator. This gives users the
option of lower power consumption while still using a
high accuracy clock source.
SEC_RUN mode is entered by clearing the IDLEN bit,
setting SCS1:SCS0 = 01 and executing a SLEEP
instruction. The system clock source is switched to the
Timer1 oscillator (see Figure 3-9), the primary oscillator
is shut down, the T1RUN bit (T1CON<6>) is set and
the OSTS bit is cleared.
When a wake event occurs, the peripherals and CPU
continue to be clocked from the Timer1 oscillator while
the primary clock is started. When the primary clock
becomes ready, a clock switchback to the primary clock
occurs (see Figure 3-6). When the clock switch is complete,
the T1RUN bit is cleared, the OSTS bit is set and
the primary clock is providing the system clock. The
IDLEN and SCS bits are not affected by the wake-up.
The Timer1 oscillator continues to run.
Firmware can force an exit from SEC_RUN mode. By
clearing the T1OSCEN bit (T1CON<3>), an exit from
SEC_RUN back to normal full power operation is triggered.
The Timer1 oscillator will continue to run and
provide the system clock, even though the T1OSCEN
bit is cleared. The primary clock is started. When the
primary clock becomes ready, a clock switchback to the
primary clock occurs (see Figure 3-6). When the clock
switch is complete, the Timer1 oscillator is disabled, the
T1RUN bit is cleared, the OSTS bit is set and the primary
clock is providing the system clock. The IDLEN
and SCS bits are not affected by the wake-up.
FIGURE 3-9: TIMING TRANSITION FOR ENTRY TO SEC_RUN MODE
Note: The Timer1 oscillator should already be
running prior to entering SEC_RUN mode.
If the T1OSCEN bit is not set when the
SLEEP instruction is executed, the SLEEP
instruction will be ignored and entry to
SEC_RUN mode will not occur. If the
Timer1 oscillator is enabled, but not yet
running, system clocks will be delayed
until the oscillator has started; in such
situations, initial oscillator operation is far
from stable and unpredictable operation
may result.
Q2 Q3 Q4
OSC1
Peripheral
Program
Q1
T1OSI
Q1
Counter
Clock
CPU
Clock
PC PC + 2
12345678
Clock Transition
Q2 Q3 Q4 Q1 Q2 Q3
PC + 2© 2007 Microchip Technology Inc. DS39605F-page 27
PIC18F1220/1320
3.4.3 RC_RUN MODE
In RC_RUN mode, the CPU and peripherals are
clocked from the internal oscillator block using the
INTOSC multiplexer and the primary clock is shut
down. When using the INTRC source, this mode provides
the best power conservation of all the Run
modes, while still executing code. It works well for user
applications which are not highly timing sensitive, or do
not require high-speed clocks at all times.
If the primary clock source is the internal oscillator
block (either of the INTIO1 or INTIO2 oscillators), there
are no distinguishable differences between PRI_RUN
and RC_RUN modes during execution. However, a
clock switch delay will occur during entry to and exit
from RC_RUN mode. Therefore, if the primary clock
source is the internal oscillator block, the use of
RC_RUN mode is not recommended.
This mode is entered by clearing the IDLEN bit, setting
SCS1 (SCS0 is ignored) and executing a SLEEP
instruction. The IRCF bits may select the clock
frequency before the SLEEP instruction is executed.
When the clock source is switched to the INTOSC
multiplexer (see Figure 3-10), the primary oscillator is
shut down and the OSTS bit is cleared.
The IRCF bits may be modified at any time to immediately
change the system clock speed. Executing a
SLEEP instruction is not required to select a new clock
frequency from the INTOSC multiplexer.
If the IRCF bits are all clear, the INTOSC output is not
enabled and the IOFS bit will remain clear; there will be
no indication of the current clock source. The INTRC
source is providing the system clocks.
If the IRCF bits are changed from all clear (thus,
enabling the INTOSC output), the IOFS bit becomes
set after the INTOSC output becomes stable. Clocks to
the system continue while the INTOSC source
stabilizes, in approximately 1 ms.
If the IRCF bits were previously at a non-zero value
before the SLEEP instruction was executed and the
INTOSC source was already stable, the IOFS bit will
remain set.
When a wake event occurs, the system continues to be
clocked from the INTOSC multiplexer while the primary
clock is started. When the primary clock becomes
ready, a clock switch to the primary clock occurs (see
Figure 3-8). When the clock switch is complete, the
IOFS bit is cleared, the OSTS bit is set and the primary
clock is providing the system clock. The IDLEN and
SCS bits are not affected by the wake-up. The INTRC
source will continue to run if either the WDT or the
Fail-Safe Clock Monitor is enabled.
FIGURE 3-10: TIMING TRANSITION TO RC_RUN MODE
Note: Caution should be used when modifying a
single IRCF bit. If VDD is less than 3V, it is
possible to select a higher clock speed
than is supported by the low VDD.
Improper device operation may result if
the VDD/FOSC specifications are violated.
Q1 Q2 Q3
OSC1
Peripheral
Program
Q4
INTRC
Q4
Counter
Clock
CPU
Clock
PC PC + 2
12345678
Clock Transition
Q1 Q2 Q3 Q4 Q1 Q2 Q3
PC + 4PIC18F1220/1320
DS39605F-page 28 © 2007 Microchip Technology Inc.
3.4.4 EXIT TO IDLE MODE
An exit from a power managed Run mode to its
corresponding Idle mode is executed by setting the
IDLEN bit and executing a SLEEP instruction. The CPU
is halted at the beginning of the instruction following the
SLEEP instruction. There are no changes to any of the
clock source status bits (OSTS, IOFS or T1RUN).
While the CPU is halted, the peripherals continue to be
clocked from the previously selected clock source.
3.4.5 EXIT TO SLEEP MODE
An exit from a power managed Run mode to Sleep
mode is executed by clearing the IDLEN and
SCS1:SCS0 bits and executing a SLEEP instruction.
The code is no different than the method used to invoke
Sleep mode from the normal operating (full power)
mode.
The primary clock and internal oscillator block are
disabled. The INTRC will continue to operate if the
WDT is enabled. The Timer1 oscillator will continue to
run, if enabled in the T1CON register (Register 12-1).
All clock source status bits are cleared (OSTS, IOFS
and T1RUN).
3.5 Wake from Power Managed Modes
An exit from any of the power managed modes is triggered
by an interrupt, a Reset or a WDT time-out. This
section discusses the triggers that cause exits from
power managed modes. The clocking subsystem
actions are discussed in each of the power managed
modes (see Sections 3.2 through 3.4).
Device behavior during Low-Power mode exits is
summarized in Table 3-3.
3.5.1 EXIT BY INTERRUPT
Any of the available interrupt sources can cause the
device to exit a power managed mode and resume full
power operation. To enable this functionality, an interrupt
source must be enabled by setting its enable bit in
one of the INTCON or PIE registers. The exit sequence
is initiated when the corresponding interrupt flag bit is
set. On all exits from Low-Power mode by interrupt,
code execution branches to the interrupt vector if the
GIE/GIEH bit (INTCON<7>) is set. Otherwise, code
execution continues or resumes without branching
(see Section 9.0 “Interrupts”).
Note: If application code is timing sensitive, it
should wait for the OSTS bit to become set
before continuing. Use the interval during
the low-power exit sequence (before
OSTS is set) to perform timing insensitive
“housekeeping” tasks.© 2007 Microchip Technology Inc. DS39605F-page 29
PIC18F1220/1320
TABLE 3-3: ACTIVITY AND EXIT DELAY ON WAKE FROM SLEEP MODE OR ANY IDLE MODE
(BY CLOCK SOURCES)
Clock in Power
Managed Mode
Primary System
Clock
Power
Managed
Mode Exit
Delay
Clock Ready
Status Bit
(OSCCON)
Activity during Wake-up from
Power Managed Mode
Exit by Interrupt Exit by Reset
Primary System
Clock
(PRI_IDLE mode)
LP, XT, HS
5-10 μs(5)
OSTS CPU and peripherals
clocked by primary
clock and executing
instructions.
Not clocked or
Two-Speed Start-up
(if enabled)(3). HSPLL
EC, RC, INTRC(1) —
INTOSC(2) IOFS
T1OSC or
INTRC(1)
LP, XT, HS OST OSTS CPU and peripherals
clocked by selected
power managed mode
clock and executing
instructions until
primary clock source
becomes ready.
HSPLL OST + 2 ms
EC, RC, INTRC(1) 5-10 μs(5) —
INTOSC(2) 1 ms(4) IOFS
INTOSC(2)
LP, XT, HS OST OSTS
HSPLL OST + 2 ms
EC, RC, INTRC(1) 5-10 μs(5) —
INTOSC(2) None IOFS
Sleep mode
LP, XT, HS OST OSTS
Not clocked or
Two-Speed Start-up (if
enabled) until primary
clock source becomes
ready(3).
HSPLL OST + 2 ms
EC, RC, INTRC(1) 5-10 μs(5) —
INTOSC(2) 1 ms(4) IOFS
Note 1: In this instance, refers specifically to the INTRC clock source.
2: Includes both the INTOSC 8 MHz source and postscaler derived frequencies.
3: Two-Speed Start-up is covered in greater detail in Section 19.3 “Two-Speed Start-up”.
4: Execution continues during the INTOSC stabilization period.
5: Required delay when waking from Sleep and all Idle modes. This delay runs concurrently with any other
required delays (see Section 3.3 “Idle Modes”).PIC18F1220/1320
DS39605F-page 30 © 2007 Microchip Technology Inc.
3.5.2 EXIT BY RESET
Normally, the device is held in Reset by the Oscillator
Start-up Timer (OST) until the primary clock (defined in
Configuration Register 1H) becomes ready. At that
time, the OSTS bit is set and the device begins
executing code.
Code execution can begin before the primary clock
becomes ready. If either the Two-Speed Start-up (see
Section 19.3 “Two-Speed Start-up”) or Fail-Safe
Clock Monitor (see Section 19.4 “Fail-Safe Clock
Monitor”) are enabled in Configuration Register 1H,
the device may begin execution as soon as the Reset
source has cleared. Execution is clocked by the
INTOSC multiplexer driven by the internal oscillator
block. Since the OSCCON register is cleared following
all Resets, the INTRC clock source is selected. A
higher speed clock may be selected by modifying the
IRCF bits in the OSCCON register. Execution is
clocked by the internal oscillator block until either the
primary clock becomes ready, or a power managed
mode is entered before the primary clock becomes
ready; the primary clock is then shut down.
3.5.3 EXIT BY WDT TIME-OUT
A WDT time-out will cause different actions, depending
on which power managed mode the device is in when
the time-out occurs.
If the device is not executing code (all Idle modes and
Sleep mode), the time-out will result in a wake from the
power managed mode (see Sections 3.2 through 3.4).
If the device is executing code (all Run modes), the
time-out will result in a WDT Reset (see Section 19.2
“Watchdog Timer (WDT)”).
The WDT timer and postscaler are cleared by
executing a SLEEP or CLRWDT instruction, the loss of a
currently selected clock source (if the Fail-Safe Clock
Monitor is enabled) and modifying the IRCF bits in the
OSCCON register if the internal oscillator block is the
system clock source.
3.5.4 EXIT WITHOUT AN OSCILLATOR
START-UP DELAY
Certain exits from power managed modes do not
invoke the OST at all. These are:
• PRI_IDLE mode, where the primary clock source
is not stopped; or
• the primary clock source is not any of LP, XT, HS
or HSPLL modes.
In these cases, the primary clock source either does
not require an oscillator start-up delay, since it is
already running (PRI_IDLE), or normally does not
require an oscillator start-up delay (RC, EC and INTIO
Oscillator modes).
However, a fixed delay (approximately 10 μs) following
the wake event is required when leaving Sleep and Idle
modes. This delay is required for the CPU to prepare
for execution. Instruction execution resumes on the first
clock cycle following this delay.
3.6 INTOSC Frequency Drift
The factory calibrates the internal oscillator block
output (INTOSC) for 8 MHz (see Table 22-6). However,
this frequency may drift as VDD or temperature
changes, which can affect the controller operation in a
variety of ways.
It is possible to adjust the INTOSC frequency by
modifying the value in the OSCTUNE register
(Register 2-1). This has the side effect that the INTRC
clock source frequency is also affected. However, the
features that use the INTRC source often do not require
an exact frequency. These features include the Fail-Safe
Clock Monitor, the Watchdog Timer and the RC_RUN/
RC_IDLE modes when the INTRC clock source is
selected.
Being able to adjust the INTOSC requires knowing
when an adjustment is required, in which direction it
should be made and in some cases, how large a
change is needed. Three examples follow but other
techniques may be used.© 2007 Microchip Technology Inc. DS39605F-page 31
PIC18F1220/1320
3.6.1 EXAMPLE – EUSART
An adjustment may be indicated when the EUSART
begins to generate framing errors, or receives data with
errors while in Asynchronous mode. Framing errors
indicate that the system clock frequency is too high –
try decrementing the value in the OSCTUNE register to
reduce the system clock frequency. Errors in data may
suggest that the system clock speed is too low –
increment OSCTUNE.
3.6.2 EXAMPLE – TIMERS
This technique compares system clock speed to some
reference clock. Two timers may be used; one timer is
clocked by the peripheral clock, while the other is
clocked by a fixed reference source, such as the
Timer1 oscillator.
Both timers are cleared, but the timer clocked by the
reference generates interrupts. When an interrupt
occurs, the internally clocked timer is read and both
timers are cleared. If the internally clocked timer value
is greater than expected, then the internal oscillator
block is running too fast – decrement OSCTUNE.
3.6.3 EXAMPLE – CCP IN CAPTURE
MODE
A CCP module can use free running Timer1 (or
Timer3), clocked by the internal oscillator block and an
external event with a known period (i.e., AC power
frequency). The time of the first event is captured in the
CCPRxH:CCPRxL registers and is recorded for use
later. When the second event causes a capture, the
time of the first event is subtracted from the time of the
second event. Since the period of the external event is
known, the time difference between events can be
calculated.
If the measured time is much greater than the
calculated time, the internal oscillator block is running
too fast – decrement OSCTUNE. If the measured time
is much less than the calculated time, the internal
oscillator block is running too slow – increment
OSCTUNE.PIC18F1220/1320
DS39605F-page 32 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 33
PIC18F1220/1320
4.0 RESET
The PIC18F1220/1320 devices differentiate between
various kinds of Reset:
a) Power-on Reset (POR)
b) MCLR Reset during normal operation
c) MCLR Reset during Sleep
d) Watchdog Timer (WDT) Reset (during
execution)
e) Programmable Brown-out Reset (BOR)
f) RESET Instruction
g) Stack Full Reset
h) 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”, depending on the type of Reset that occurred.
Most registers are not affected by a WDT wake-up,
since this is viewed as the resumption of normal
operation. Status bits from the RCON register
(Register 4-1), RI, TO, PD, POR and BOR, are set or
cleared differently in different Reset situations, as
indicated in Table 4-2. These bits are used in software
to determine the nature of the Reset. See Table 4-3 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 4-1.
The Enhanced MCU devices have a MCLR noise filter
in the MCLR Reset path. The filter will detect and
ignore small pulses.
The MCLR pin is not driven low by any internal Resets,
including the WDT.
The MCLR input provided by the MCLR pin can be
disabled with the MCLRE bit in Configuration
Register 3H (CONFIG3H<7>).
FIGURE 4-1: SIMPLIFIED BLOCK DIAGRAM OF ON-CHIP RESET CIRCUIT
S
R Q
External Reset
MCLR
VDD
OSC1
WDT
Time-out
VDD Rise
Detect
OST/PWRT
INTRC(1)
POR Pulse
OST
10-bit Ripple Counter
PWRT
Chip_Reset
11-bit Ripple Counter
Enable OST(2)
Enable PWRT
Note 1: This is a separate oscillator from the RC oscillator of the CLKI pin.
2: See Table 4-1 for time-out situations.
Brown-out
Reset
BOR
RESET
Instruction
Stack
Pointer
Stack Full/Underflow Reset
Sleep
( )_IDLE
1024 Cycles
65.5 ms 32 μs
MCLREPIC18F1220/1320
DS39605F-page 34 © 2007 Microchip Technology Inc.
4.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
circuitry, just tie the MCLR pin through a resistor (1k to
10 kΩ) to VDD. This will eliminate external RC components
usually needed to create a Power-on Reset
delay. A minimum rise rate for VDD is specified
(parameter D004). For a slow rise time, see Figure 4-2.
When the device starts normal operation (i.e., exits the
Reset condition), device operating parameters (voltage,
frequency, temperature, etc.) must be met to
ensure operation. If these conditions are not met, the
device must be held in Reset until the operating
conditions are met.
FIGURE 4-2: EXTERNAL POWER-ON
RESET CIRCUIT (FOR
SLOW VDD POWER-UP)
4.2 Power-up Timer (PWRT)
The Power-up Timer (PWRT) of the PIC18F1220/1320 is
an 11-bit counter, which uses the INTRC source as the
clock input. This yields a count of 2048 x 32 μs = 65.6 ms.
While the PWRT is counting, the device is held in Reset.
The power-up time delay will vary from chip-to-chip due
to VDD, temperature and process variation. See DC
parameter 33 for details.
The PWRT is enabled by clearing configuration bit,
PWRTEN.
4.3 Oscillator Start-up Timer (OST)
The Oscillator Start-up Timer (OST) provides a 1024
oscillator cycle (from OSC1 input) delay after the
PWRT delay is over (parameter 33). This ensures that
the crystal oscillator or resonator has started and
stabilized.
The OST time-out is invoked only for XT, LP, HS and
HSPLL modes and only on Power-on Reset, or on exit
from most low-power modes.
4.4 PLL Lock Time-out
With the PLL enabled in its PLL mode, the time-out
sequence following a Power-on Reset is slightly
different from other oscillator modes. A 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) is typically 2 ms
and follows the Oscillator Start-up Time-out.
4.5 Brown-out Reset (BOR)
A configuration bit, BOR, can disable (if clear/
programmed), or enable (if set) the Brown-out Reset
circuitry. If VDD falls below VBOR (parameter D005) for
greater than TBOR (parameter 35), the brown-out situation
will reset the chip. A Reset may not occur if VDD
falls below VBOR for less than TBOR. The chip will
remain in Brown-out Reset until VDD rises above VBOR.
If the Power-up Timer is enabled, it will be invoked after
VDD rises above VBOR; it then will keep the chip in
Reset for an additional time delay, TPWRT
(parameter 33). If VDD drops below VBOR while the
Power-up Timer is running, the chip will go back into a
Brown-out Reset and the Power-up Timer will be initialized.
Once VDD rises above VBOR, the Power-up Timer
will execute the additional time delay. Enabling BOR
Reset does not automatically enable the PWRT.
4.6 Time-out Sequence
On power-up, the time-out sequence is as follows:
First, after the POR pulse has cleared, PWRT time-out
is invoked (if enabled). Then, the OST is activated. The
total time-out will vary based on oscillator configuration
and the status of the PWRT. For example, in RC mode
with the PWRT disabled, there will be no time-out at all.
Figure 4-3, Figure 4-4, Figure 4-5, Figure 4-6 and
Figure 4-7 depict time-out sequences on power-up.
Since the time-outs occur from the POR pulse, if MCLR
is kept low long enough, all time-outs will expire. Bringing
MCLR high will begin execution immediately
(Figure 4-5). This is useful for testing purposes or to
synchronize more than one PIC18FXXXX device
operating in parallel.
Table 4-2 shows the Reset conditions for some Special
Function Registers, while Table 4-3 shows the Reset
conditions for all the registers.
Note 1: External Power-on Reset circuit is required
only if the VDD power-up slope is too slow.
The diode D helps discharge the capacitor
quickly when VDD powers down.
2: R < 40 kΩ is recommended to make sure that
the voltage drop across R does not violate
the device’s electrical specification.
3: R1 ≥ 1 kΩ will limit any current flowing into
MCLR from external capacitor C, in the event
of MCLR/VPP pin breakdown due to Electrostatic
Discharge (ESD) or Electrical
Overstress (EOS).
C
R1
D R
VDD
MCLR
PIC18FXXXX
VDD© 2007 Microchip Technology Inc. DS39605F-page 35
PIC18F1220/1320
TABLE 4-1: TIME-OUT IN VARIOUS SITUATIONS
REGISTER 4-1: RCON REGISTER BITS AND POSITIONS
TABLE 4-2: STATUS BITS, THEIR SIGNIFICANCE AND THE INITIALIZATION CONDITION FOR
RCON REGISTER
Oscillator
Configuration
Power-up(2) and Brown-out Exit from
Low-Power Mode PWRTEN = 0 PWRTEN = 1
HSPLL 66 ms(1) + 1024 TOSC + 2 ms(2) 1024 TOSC + 2 ms(2) 1024 TOSC + 2 ms(2)
HS, XT, LP 66 ms(1) + 1024 TOSC 1024 TOSC 1024 TOSC
EC, ECIO 66 ms(1) 5-10 μs(3) 5-10 μs(3)
RC, RCIO 66 ms(1) 5-10 μs(3) 5-10 μs(3)
INTIO1, INTIO2 66 ms(1) 5-10 μs(3) 5-10 μs(3)
Note 1: 66 ms (65.5 ms) is the nominal Power-up Timer (PWRT) delay.
2: 2 ms is the nominal time required for the 4x PLL to lock.
3: The program memory bias start-up time is always invoked on POR, wake-up from Sleep, or on any exit
from power managed mode that disables the CPU and instruction execution.
R/W-0 U-0 U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
IPEN — — RI TO PD POR BOR
bit 7 bit 0
Note: Refer to Section 5.14 “RCON Register” for bit definitions.
Condition Program
Counter
RCON
Register RI TO PD POR BOR STKFUL STKUNF
Power-on Reset 0000h 0--1 1100 1 1 1 0 0 0 0
RESET Instruction 0000h 0--0 uuuu 0 u u u u u u
Brown-out 0000h 0--1 11u- 1 1 1 u 0 u u
MCLR during Power Managed
Run modes
0000h 0--u 1uuu u 1 u u u u u
MCLR during Power Managed
Idle modes and Sleep
0000h 0--u 10uu u 1 0 u u u u
WDT Time-out during Full
Power or Power Managed Run
0000h 0--u 0uuu u 0 u u u u u
MCLR during Full Power
Execution
0000h 0--u uuuu u u u u u
u u
Stack Full Reset (STVR = 1) 1 u
Stack Underflow Reset
(STVR = 1)
u 1
Stack Underflow Error (not an
actual Reset, STVR = 0)
0000h u--u uuuu u u u u u u 1
WDT Time-out during Power
Managed Idle or Sleep
PC + 2 u--u 00uu u 0 0 u u u u
Interrupt Exit from Power
Managed modes
PC + 2 u--u u0uu u u 0 u u u u
Legend: u = unchanged, x = unknown, – = unimplemented bit, read as ‘0’
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 (0x000008h or 0x000018h).PIC18F1220/1320
DS39605F-page 36 © 2007 Microchip Technology Inc.
TABLE 4-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS
Register Applicable
Devices
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
TOSU 1220 1320 ---0 0000 ---0 0000 ---0 uuuu(3)
TOSH 1220 1320 0000 0000 0000 0000 uuuu uuuu(3)
TOSL 1220 1320 0000 0000 0000 0000 uuuu uuuu(3)
STKPTR 1220 1320 00-0 0000 00-0 0000 uu-u uuuu(3)
PCLATU 1220 1320 ---0 0000 ---0 0000 ---u uuuu
PCLATH 1220 1320 0000 0000 0000 0000 uuuu uuuu
PCL 1220 1320 0000 0000 0000 0000 PC + 2(2)
TBLPTRU 1220 1320 --00 0000 --00 0000 --uu uuuu
TBLPTRH 1220 1320 0000 0000 0000 0000 uuuu uuuu
TBLPTRL 1220 1320 0000 0000 0000 0000 uuuu uuuu
TABLAT 1220 1320 0000 0000 0000 0000 uuuu uuuu
PRODH 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
PRODL 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
INTCON 1220 1320 0000 000x 0000 000u uuuu uuuu(1)
INTCON2 1220 1320 1111 -1-1 1111 -1-1 uuuu -u-u(1)
INTCON3 1220 1320 11-0 0-00 11-0 0-00 uu-u u-uu(1)
INDF0 1220 1320 N/A N/A N/A
POSTINC0 1220 1320 N/A N/A N/A
POSTDEC0 1220 1320 N/A N/A N/A
PREINC0 1220 1320 N/A N/A N/A
PLUSW0 1220 1320 N/A N/A N/A
FSR0H 1220 1320 ---- 0000 ---- 0000 ---- uuuu
FSR0L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
WREG 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
INDF1 1220 1320 N/A N/A N/A
POSTINC1 1220 1320 N/A N/A N/A
POSTDEC1 1220 1320 N/A N/A N/A
PREINC1 1220 1320 N/A N/A N/A
PLUSW1 1220 1320 N/A N/A N/A
FSR1H 1220 1320 ---- 0000 ---- 0000 ---- uuuu
FSR1L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the
interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 4-2 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled, depending on the Oscillator mode selected. When
not enabled as PORTA pins, they are disabled and read ‘0’.
6: Bit 5 of PORTA is enabled if MCLR is disabled.© 2007 Microchip Technology Inc. DS39605F-page 37
PIC18F1220/1320
BSR 1220 1320 ---- 0000 ---- 0000 ---- uuuu
INDF2 1220 1320 N/A N/A N/A
POSTINC2 1220 1320 N/A N/A N/A
POSTDEC2 1220 1320 N/A N/A N/A
PREINC2 1220 1320 N/A N/A N/A
PLUSW2 1220 1320 N/A N/A N/A
FSR2H 1220 1320 ---- 0000 ---- 0000 ---- uuuu
FSR2L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
STATUS 1220 1320 ---x xxxx ---u uuuu ---u uuuu
TMR0H 1220 1320 0000 0000 0000 0000 uuuu uuuu
TMR0L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
T0CON 1220 1320 1111 1111 1111 1111 uuuu uuuu
OSCCON 1220 1320 0000 q000 0000 q000 uuuu qquu
LVDCON 1220 1320 --00 0101 --00 0101 --uu uuuu
WDTCON 1220 1320 ---- ---0 ---- ---0 ---- ---u
RCON(4) 1220 1320 0--1 11q0 0--q qquu u--u qquu
TMR1H 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
TMR1L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
T1CON 1220 1320 0000 0000 u0uu uuuu uuuu uuuu
TMR2 1220 1320 0000 0000 0000 0000 uuuu uuuu
PR2 1220 1320 1111 1111 1111 1111 1111 1111
T2CON 1220 1320 -000 0000 -000 0000 -uuu uuuu
ADRESH 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
ADRESL 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
ADCON0 1220 1320 00-0 0000 00-0 0000 uu-u uuuu
ADCON1 1220 1320 -000 0000 -000 0000 -uuu uuuu
ADCON2 1220 1320 0-00 0000 0-00 0000 u-uu uuuu
CCPR1H 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
CCPR1L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
CCP1CON 1220 1320 0000 0000 0000 0000 uuuu uuuu
PWM1CON 1220 1320 0000 0000 0000 0000 uuuu uuuu
ECCPAS 1220 1320 0000 0000 0000 0000 uuuu uuuu
TABLE 4-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable
Devices
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the
interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 4-2 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled, depending on the Oscillator mode selected. When
not enabled as PORTA pins, they are disabled and read ‘0’.
6: Bit 5 of PORTA is enabled if MCLR is disabled.PIC18F1220/1320
DS39605F-page 38 © 2007 Microchip Technology Inc.
TMR3H 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
TMR3L 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
T3CON 1220 1320 0-00 0000 u-uu uuuu u-uu uuuu
SPBRGH 1220 1320 0000 0000 0000 0000 uuuu uuuu
SPBRG 1220 1320 0000 0000 0000 0000 uuuu uuuu
RCREG 1220 1320 0000 0000 0000 0000 uuuu uuuu
TXREG 1220 1320 0000 0000 0000 0000 uuuu uuuu
TXSTA 1220 1320 0000 0010 0000 0010 uuuu uuuu
RCSTA 1220 1320 0000 000x 0000 000x uuuu uuuu
BAUDCTL 1220 1320 -1-1 0-00 -1-1 0-00 -u-u u-uu
EEADR 1220 1320 0000 0000 0000 0000 uuuu uuuu
EEDATA 1220 1320 0000 0000 0000 0000 uuuu uuuu
EECON2 1220 1320 0000 0000 0000 0000 0000 0000
EECON1 1220 1320 xx-0 x000 uu-0 u000 uu-0 u000
IPR2 1220 1320 1--1 -11- 1--1 -11- u--u -uuPIR2
1220 1320 0--0 -00- 0--0 -00- u--u -uu-(1)
PIE2 1220 1320 0--0 -00- 0--0 -00- u--u -uuIPR1
1220 1320 -111 -111 -111 -111 -uuu -uuu
PIR1 1220 1320 -000 -000 -000 -000 -uuu -uuu(1)
PIE1 1220 1320 -000 -000 -000 -000 -uuu -uuu
OSCTUNE 1220 1320 --00 0000 --00 0000 --uu uuuu
TRISB 1220 1320 1111 1111 1111 1111 uuuu uuuu
TRISA(5) 1220 1320 11-1 1111(5) 11-1 1111(5) uu-u uuuu(5)
LATB 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
LATA(5) 1220 1320 xx-x xxxx(5) uu-u uuuu(5) uu-u uuuu(5)
PORTB 1220 1320 xxxx xxxx uuuu uuuu uuuu uuuu
PORTA(5,6) 1220 1320 xx0x 0000(5,6) uu0u 0000(5,6) uuuu uuuu(5,6)
TABLE 4-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable
Devices
Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the
interrupt vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 4-2 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled, depending on the Oscillator mode selected. When
not enabled as PORTA pins, they are disabled and read ‘0’.
6: Bit 5 of PORTA is enabled if MCLR is disabled.© 2007 Microchip Technology Inc. DS39605F-page 39
PIC18F1220/1320
FIGURE 4-3: TIME-OUT SEQUENCE ON POWER-UP (MCLR TIED TO VDD, VDD RISE < TPWRT)
FIGURE 4-4: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 1
FIGURE 4-5: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 2
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOSTPIC18F1220/1320
DS39605F-page 40 © 2007 Microchip Technology Inc.
FIGURE 4-6: SLOW RISE TIME (MCLR TIED TO VDD, VDD RISE > TPWRT)
FIGURE 4-7: TIME-OUT SEQUENCE ON POR W/PLL ENABLED (MCLR TIED TO VDD)
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
0V 1V
5V
TPWRT
TOST
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
PLL TIME-OUT
TPLL
Note: TOST = 1024 clock cycles.
TPLL ≈ 2 ms max. First three stages of the PWRT timer.© 2007 Microchip Technology Inc. DS39605F-page 41
PIC18F1220/1320
5.0 MEMORY ORGANIZATION
There are three memory types in Enhanced MCU
devices. These memory types are:
• Program Memory
• Data RAM
• Data EEPROM
Data and program memory use separate busses,
which allows for concurrent access of these types.
Additional detailed information for Flash program memory
and data EEPROM is provided in Section 6.0
“Flash Program Memory” and Section 7.0 “Data
EEPROM Memory”, respectively.
FIGURE 5-1: PROGRAM MEMORY MAP
AND STACK FOR
PIC18F1220
5.1 Program Memory Organization
A 21-bit program counter is capable of addressing the
2-Mbyte program memory space. Accessing a location
between the physically implemented memory and the
2-Mbyte address will cause a read of all ‘0’s (a NOP
instruction).
The PIC18F1220 has 4 Kbytes of Flash memory and
can store up to 2,048 single-word instructions.
The PIC18F1320 has 8 Kbytes of Flash memory and
can store up to 4,096 single-word instructions.
The Reset vector address is at 0000h and the interrupt
vector addresses are at 0008h and 0018h.
The program memory maps for the PIC18F1220 and
PIC18F1320 devices are shown in Figure 5-1 and
Figure 5-2, respectively.
FIGURE 5-2: PROGRAM MEMORY MAP
AND STACK FOR
PIC18F1320
PC<20:0>
Stack Level 1 •
Stack Level 31
Reset Vector
Low Priority Interrupt Vector
•
•
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
On-Chip
Program Memory
High Priority Interrupt Vector 0008h
User Memory Space
1FFFFFh
1000h
0FFFh
Read ‘0’
200000h
PC<20:0>
Stack Level 1 •
Stack Level 31
Reset Vector
Low Priority Interrupt Vector
•
•
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
2000h
1FFFh
On-Chip
Program Memory
High Priority Interrupt Vector 0008h
User Memory Space
Read ‘0’
1FFFFFh
200000hPIC18F1220/1320
DS39605F-page 42 © 2007 Microchip Technology Inc.
5.2 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 or
CALL instructions.
The stack operates as a 31-word by 21-bit RAM and a
5-bit stack pointer, with the Stack Pointer initialized to
00000B after all Resets. There is no RAM associated
with Stack Pointer, 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
(STKPTR) register is written with the contents of the PC
(already pointing to the instruction following the CALL).
During a RETURN type instruction, causing a pop from
the stack, the contents of the RAM location pointed to
by the STKPTR are transferred to the PC and then the
Stack Pointer is decremented.
The stack space is not part of either program or data
space. The Stack Pointer is readable and writable and
the address on the top of the stack is readable and
writable through the top-of-stack Special File
Registers. Data can also be pushed to or popped from
the stack using the top-of-stack SFRs. Status bits
indicate if the stack is full, has overflowed or
underflowed.
5.2.1 TOP-OF-STACK ACCESS
The top of the stack is readable and writable. Three
register locations, TOSU, TOSH and TOSL, hold the
contents of the stack location pointed to by the
STKPTR register (Figure 5-3). 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
while accessing the stack to prevent inadvertent stack
corruption.
5.2.2 RETURN STACK POINTER
(STKPTR)
The STKPTR register (Register 5-1) contains the stack
pointer value, the STKFUL (Stack Full) status bit and
the STKUNF (Stack Underflow) status bits. The value
of the Stack Pointer can be 0 through 31. The Stack
Pointer increments before values are pushed onto the
stack and decrements after values are popped off the
stack. At Reset, the Stack Pointer value will be zero.
The user may read and write the Stack Pointer value.
This feature can be used by a Real-Time Operating
System for return stack maintenance.
After the PC is pushed onto the stack 31 times (without
popping any values off the stack), the STKFUL bit is
set. The STKFUL bit is cleared by software or by a
POR.
The action that takes place when the stack becomes
full depends on the state of the STVR (Stack Overflow
Reset Enable) configuration bit. (Refer to Section 19.1
“Configuration Bits” for a description of the device
configuration bits.) If STVR is set (default), the 31st
push will push the (PC + 2) value onto the stack, set the
STKFUL bit and reset the device. The STKFUL bit will
remain set and the Stack Pointer will be set to zero.
If STVR is cleared, the STKFUL bit will be set on the
31st push and the Stack Pointer will increment to 31.
Any additional pushes will not overwrite the 31st push
and STKPTR will remain at 31.
When the stack has been popped enough times to
unload the stack, the next pop will return a value of zero
to the PC and sets the STKUNF bit, while the Stack
Pointer remains at zero. The STKUNF bit will remain
set until cleared by software or a POR occurs.
FIGURE 5-3: RETURN ADDRESS STACK AND ASSOCIATED REGISTERS
Note: Returning a value of 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. This is
not the same as a Reset, as the contents
of the SFRs are not affected.
00011
001A34h
11111
11110
11101
00010
00001
00000
00010
Return Address Stack
Top-of-Stack 000D58h
TOSU TOSH TOSL
00h 1Ah 34h
STKPTR<4:0>© 2007 Microchip Technology Inc. DS39605F-page 43
PIC18F1220/1320
REGISTER 5-1: STKPTR REGISTER
5.2.3 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 or a return address
on the stack.
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.
5.2.4 STACK FULL/UNDERFLOW RESETS
These Resets are enabled by programming the STVR
bit in Configuration Register 4L. When the STVR bit is
cleared, a full or underflow condition will set the appropriate
STKFUL or STKUNF bit, but not cause a device
Reset. When the STVR bit is set, a full or underflow
condition will set the appropriate STKFUL or STKUNF
bit and then cause a device Reset. The STKFUL or
STKUNF bits are cleared by the user software or a
Power-on Reset.
R/C-0 R/C-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
STKFUL STKUNF — SP4 SP3 SP2 SP1 SP0
bit 7 bit 0
bit 7(1) STKFUL: Stack Full Flag bit
1 = Stack became full or overflowed
0 = Stack has not become full or overflowed
bit 6(1) STKUNF: Stack Underflow Flag bit
1 = Stack underflow occurred
0 = Stack underflow did not occur
bit 5 Unimplemented: Read as ‘0’
bit 4-0 SP4:SP0: Stack Pointer Location bits
Note 1: Bit 7 and bit 6 are cleared by user software or by a POR.
Legend:
R = Readable bit W = Writable bit U = Unimplemented C = Clearable only bit
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 44 © 2007 Microchip Technology Inc.
5.3 Fast Register Stack
A “fast return” option is available for interrupts. A fast
register stack is provided for the Status, WREG and
BSR registers and is only one in depth. The stack is not
readable or 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
RETFIE, FAST instruction is used to return from the
interrupt.
All interrupt sources will push values into the stack
registers. If both low and high priority interrupts are
enabled, the stack registers cannot be used reliably to
return from low priority interrupts. If a high priority interrupt
occurs while servicing a low priority interrupt, the
stack register values stored by the low priority interrupt
will be overwritten. Users must save the key registers
in software during a low priority interrupt.
If interrupt priority is not used, all interrupts may use the
fast register stack for returns from 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 CALL LABEL, FAST
instruction must be executed to save the Status,
WREG and BSR registers to the fast register stack. A
RETURN, FAST instruction is then executed to restore
these registers from the fast register stack.
Example 5-1 shows a source code example that uses
the fast register stack during a subroutine call and
return.
EXAMPLE 5-1: FAST REGISTER STACK
CODE EXAMPLE
5.4 PCL, PCLATH and PCLATU
The Program Counter (PC) specifies the address of the
instruction to fetch for execution. The PC is 21-bits
wide. The low byte, known as the PCL register, is both
readable and writable. The high byte, or PCH register,
contains the PC<15:8> bits and is not directly readable
or writable. Updates to the PCH register may be performed
through the PCLATH register. The upper byte is
called PCU. This register contains the PC<20:16> bits
and is not directly readable or writable. Updates to the
PCU register may be performed through the PCLATU
register.
The contents of PCLATH and PCLATU will be
transferred to the program counter by any operation
that writes PCL. Similarly, the upper two bytes of the
program counter will be transferred to PCLATH and
PCLATU by an operation that reads PCL. This is useful
for computed offsets to the PC (see Section 5.8.1
“Computed GOTO”).
The PC addresses bytes in the program memory. To
prevent the PC from becoming misaligned with word
instructions, the LSB of PCL is fixed to a value of ‘0’.
The PC increments by 2 to address sequential
instructions in the program memory.
The CALL, RCALL, GOTO and program branch instructions
write to the program counter directly. For these
instructions, the contents of PCLATH and PCLATU are
not transferred to the program counter.
CALL SUB1, FAST ;STATUS, WREG, BSR
;SAVED IN FAST REGISTER
;STACK
•
•
SUB1 •
•
RETURN, FAST ;RESTORE VALUES SAVED
;IN FAST REGISTER STACK© 2007 Microchip Technology Inc. DS39605F-page 45
PIC18F1220/1320
5.5 Clocking Scheme/Instruction
Cycle
The clock input (from OSC1) is internally divided by
four to generate four non-overlapping quadrature
clocks, namely Q1, Q2, Q3 and Q4. Internally, the
Program Counter (PC) is incremented every Q1, the
instruction is fetched from the program memory and
latched into the instruction register in Q4. The instruction
is decoded and executed during the following Q1
through Q4. The clocks and instruction execution flow
are shown in Figure 5-4.
5.6 Instruction Flow/Pipelining
An “Instruction Cycle” consists of four Q cycles (Q1,
Q2, Q3 and Q4). The instruction fetch and execute are
pipelined such that fetch takes one instruction cycle,
while decode and execute takes another instruction
cycle. However, due to the pipelining, each instruction
effectively executes in one cycle. If an instruction
causes the program counter to change (e.g., GOTO),
then two cycles are required to complete the instruction
(Example 5-2).
A fetch cycle begins with the Program Counter (PC)
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).
FIGURE 5-4: CLOCK/INSTRUCTION CYCLE
EXAMPLE 5-2: INSTRUCTION PIPELINE FLOW
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
Q1
Q2
Q3
Q4
PC
OSC2/CLKO
(RC Mode)
PC PC + 2 PC + 4
Fetch INST (PC)
Execute INST (PC – 2)
Fetch INST (PC + 2)
Execute INST (PC)
Fetch INST (PC + 4)
Execute INST (PC + 2)
Internal
Phase
Clock
All instructions are single cycle, except for any program branches. These take two cycles, since the fetch instruction
is “flushed” from the pipeline, while the new instruction is being fetched and then executed.
TCY0 TCY1 TCY2 TCY3 TCY4 TCY5
1. MOVLW 55h Fetch 1 Execute 1
2. MOVWF PORTB Fetch 2 Execute 2
3. BRA SUB_1 Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP) Fetch 4 Flush (NOP)
5. Instruction @ address SUB_1 Fetch SUB_1 Execute SUB_1PIC18F1220/1320
DS39605F-page 46 © 2007 Microchip Technology Inc.
5.7 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 5-5 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’ (see Section 5.4 “PCL,
PCLATH and PCLATU”).
The CALL and GOTO instructions have the absolute
program memory address embedded into the instruction.
Since instructions are always stored on word
boundaries, the data contained in the instruction is a
word address. The word address is written to
PC<20:1>, which accesses the desired byte address in
program memory. Instruction #2 in Figure 5-5 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. Section 20.0 “Instruction Set
Summary” provides further details of the instruction
set.
FIGURE 5-5: INSTRUCTIONS IN PROGRAM MEMORY
5.7.1 TWO-WORD INSTRUCTIONS
PIC18F1220/1320 devices have four two-word
instructions: MOVFF, CALL, GOTO and LFSR. The second
word of these instructions has the 4 MSBs set to ‘1’s and
is decoded as a NOP instruction. The lower 12 bits of the
second word contain data to be used by the instruction.
If the first word of the instruction is executed, the data in
the second word is accessed. If the second word of the
instruction is executed by itself (first word was skipped),
it will execute as a NOP. This action is necessary when
the two-word instruction is preceded by a conditional
instruction that results in a skip operation. A program
example that demonstrates this concept is shown in
Example 5-3. Refer to Section 20.0 “Instruction Set
Summary” for further details of the instruction set.
EXAMPLE 5-3: TWO-WORD INSTRUCTIONS
Word Address
LSB = 1 LSB = 0 ↓
Program Memory
Byte Locations →
000000h
000002h
000004h
000006h
Instruction 1: MOVLW 055h 0Fh 55h 000008h
Instruction 2: GOTO 000006h EFh 03h 00000Ah
F0h 00h 00000Ch
Instruction 3: MOVFF 123h, 456h C1h 23h 00000Eh
F4h 56h 000010h
000012h
000014h
CASE 1:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; No, skip this word
1111 0100 0101 0110 ; Execute this word as a NOP
0010 0100 0000 0000 ADDWF REG3 ; continue code
CASE 2:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; Yes, execute this word
1111 0100 0101 0110 ; 2nd word of instruction
0010 0100 0000 0000 ADDWF REG3 ; continue code© 2007 Microchip Technology Inc. DS39605F-page 47
PIC18F1220/1320
5.8 Look-up Tables
Look-up tables are implemented two ways:
• Computed GOTO
• Table Reads
5.8.1 COMPUTED GOTO
A computed GOTO is accomplished by adding an offset
to the program counter (see Example 5-4).
A look-up 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.
The offset value (in WREG) specifies the number of
bytes that the program counter should advance and
should be multiples of 2 (LSB = 0).
In this method, only one data byte may be stored in
each instruction location and room on the return
address stack is required.
EXAMPLE 5-4: COMPUTED GOTO USING
AN OFFSET VALUE
5.8.2 TABLE READS/TABLE WRITES
A better method of storing data in program memory
allows two bytes of data to be stored in each instruction
location.
Look-up table data may be stored two bytes per program
word by using table reads and writes. The Table
Pointer (TBLPTR) register specifies the byte address
and the Table Latch (TABLAT) register contains the
data that is read from or written to program memory.
Data is transferred to/from program memory, one byte
at a time.
The table read/table write operation is discussed
further in Section 6.1 “Table Reads and Table
Writes”.
5.9 Data Memory Organization
The data memory is implemented as static RAM. Each
register in the data memory has a 12-bit address,
allowing up to 4096 bytes of data memory. Figure 5-6
shows the data memory organization for the
PIC18F1220/1320 devices.
The data memory map is divided into as many as
16 banks that contain 256 bytes each. The lower 4 bits
of the Bank Select Register (BSR<3:0>) select which
bank will be accessed. The upper 4 bits for the BSR are
not implemented.
The data memory contains Special Function Registers
(SFR) and General Purpose Registers (GPR). The
SFRs are used for control and status of the controller
and peripheral functions, while GPRs are used for data
storage and scratch pad operations in the user’s application.
The SFRs start at the last location of Bank 15
(FFFh) and extend towards F80h. Any remaining space
beyond the SFRs in the Bank may be implemented as
GPRs. GPRs start at the first location of Bank 0 and
grow upwards. Any read of an unimplemented location
will read as ‘0’s.
The entire data memory may be accessed directly or
indirectly. Direct addressing may require the use of the
BSR register. Indirect addressing requires the use of a
File Select Register (FSRn) and a corresponding Indirect
File Operand (INDFn). Each FSR holds a 12-bit
address value that can be used to access any location
in the Data Memory map without banking. See
Section 5.12 “Indirect Addressing, INDF and FSR
Registers” for indirect addressing details.
The instruction set and architecture allow operations
across all banks. This may be accomplished by indirect
addressing or by the use of the MOVFF instruction. The
MOVFF instruction is a two-word/two-cycle instruction
that moves a value from one register to another.
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. A segment of Bank 0 and a segment of
Bank 15 comprise the Access RAM. Section 5.10
“Access Bank” provides a detailed description of the
Access RAM.
5.9.1 GENERAL PURPOSE
REGISTER FILE
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.
Data RAM is available for use as GPR registers by all
instructions. The second half of Bank 15 (F80h to
FFFh) contains SFRs. All other banks of data memory
contain GPRs, starting with Bank 0.
MOVFW OFFSET
CALL TABLE
ORG 0xnn00
TABLE ADDWF PCL
RETLW 0xnn
RETLW 0xnn
RETLW 0xnn
.
.
.PIC18F1220/1320
DS39605F-page 48 © 2007 Microchip Technology Inc.
FIGURE 5-6: DATA MEMORY MAP FOR PIC18F1220/1320 DEVICES
Bank 0
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000
= 1111
080h
07Fh
F80h
FFFh
00h
7Fh
80h
FFh
Access Bank
When a = 0,
The BSR is ignored and the
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).
When a = 1,
The BSR specifies the Bank
used by the instruction.
F7Fh
F00h
EFFh
0FFh
000h Access RAM
FFh
00h
FFh
00h
GPR
SFR
Unused
Access RAM High
Access RAM Low
Bank 1
to Unused
= 1110 Read ‘00h’
= 0001
(SFRs)© 2007 Microchip Technology Inc. DS39605F-page 49
PIC18F1220/1320
5.9.2 SPECIAL FUNCTION REGISTERS
The Special Function Registers (SFRs) are registers
used by the CPU and peripheral modules for controlling
the desired operation of the device. These registers are
implemented as static RAM. A list of these registers is
given in Table 5-1 and Table 5-2.
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.
The unused SFR locations will be unimplemented and
read as ‘0’s.
TABLE 5-1: SPECIAL FUNCTION REGISTER MAP FOR PIC18F1220/1320 DEVICES
Address Name Address Name Address Name Address Name
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 — F9Ch —
FFBh PCLATU FDBh PLUSW2(2) FBBh — F9Bh OSCTUNE
FFAh PCLATH FDAh FSR2H FBAh — F9Ah —
FF9h PCL FD9h FSR2L FB9h — F99h —
FF8h TBLPTRU FD8h STATUS FB8h — F98h —
FF7h TBLPTRH FD7h TMR0H FB7h PWM1CON F97h —
FF6h TBLPTRL FD6h TMR0L FB6h ECCPAS F96h —
FF5h TABLAT FD5h T0CON FB5h — F95h —
FF4h PRODH FD4h — FB4h — F94h —
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 SPBRGH 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 —
FECh PREINC0(2) FCCh TMR2 FACh TXSTA F8Ch —
FEBh PLUSW0(2) FCBh PR2 FABh RCSTA F8Bh —
FEAh FSR0H FCAh T2CON FAAh BAUDCTL F8Ah LATB
FE9h FSR0L FC9h — FA9h EEADR F89h LATA
FE8h WREG FC8h — FA8h EEDATA F88h —
FE7h INDF1(2) FC7h — FA7h EECON2 F87h —
FE6h POSTINC1(2) FC6h — FA6h EECON1 F86h —
FE5h POSTDEC1(2) FC5h — FA5h — F85h —
FE4h PREINC1(2) FC4h ADRESH FA4h — F84h —
FE3h PLUSW1(2) FC3h ADRESL FA3h — F83h —
FE2h FSR1H FC2h ADCON0 FA2h IPR2 F82h —
FE1h FSR1L FC1h ADCON1 FA1h PIR2 F81h PORTB
FE0h BSR FC0h ADCON2 FA0h PIE2 F80h PORTA
Note 1: Unimplemented registers are read as ‘0’.
2: This is not a physical register.PIC18F1220/1320
DS39605F-page 50 © 2007 Microchip Technology Inc.
TABLE 5-2: REGISTER FILE SUMMARY (PIC18F1220/1320)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details on
page:
TOSU — — — Top-of-Stack Upper Byte (TOS<20:16>) ---0 0000 36, 42
TOSH Top-of-Stack High Byte (TOS<15:8>) 0000 0000 36, 42
TOSL Top-of-Stack Low Byte (TOS<7:0>) 0000 0000 36, 42
STKPTR STKFUL STKUNF — Return Stack Pointer 00-0 0000 36, 43
PCLATU — — bit 21(3) Holding Register for PC<20:16> ---0 0000 36, 44
PCLATH Holding Register for PC<15:8> 0000 0000 36, 44
PCL PC Low Byte (PC<7:0>) 0000 0000 36, 44
TBLPTRU — — bit 21 Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) --00 0000 36, 60
TBLPTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 0000 0000 36, 60
TBLPTRL Program Memory Table Pointer Low Byte (TBLPTR<7:0>) 0000 0000 36, 60
TABLAT Program Memory Table Latch 0000 0000 36, 60
PRODH Product Register High Byte xxxx xxxx 36, 71
PRODL Product Register Low Byte xxxx xxxx 36, 71
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 36, 75
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 36, 76
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 36, 77
INDF0 Uses contents of FSR0 to address data memory – value of FSR0 not changed (not a physical register) N/A 36, 53
POSTINC0 Uses contents of FSR0 to address data memory – value of FSR0 post-incremented (not a physical register) N/A 36, 53
POSTDEC0 Uses contents of FSR0 to address data memory– value of FSR0 post-decremented (not a physical register) N/A 36, 53
PREINC0 Uses contents of FSR0 to address data memory – value of FSR0 pre-incremented (not a physical register) N/A 36, 53
PLUSW0 Uses contents of FSR0 to address data memory – value of FSR0 offset by W (not a physical register) N/A 36, 53
FSR0H — — — — Indirect Data Memory Address Pointer 0 High ---- 0000 36, 53
FSR0L Indirect Data Memory Address Pointer 0 Low Byte xxxx xxxx 36, 53
WREG Working Register xxxx xxxx 36
INDF1 Uses contents of FSR1 to address data memory – value of FSR1 not changed (not a physical register) N/A 36, 53
POSTINC1 Uses contents of FSR1 to address data memory – value of FSR1 post-incremented (not a physical register) N/A 36, 53
POSTDEC1 Uses contents of FSR1 to address data memory – value of FSR1 post-decremented (not a physical register) N/A 36, 53
PREINC1 Uses contents of FSR1 to address data memory – value of FSR1 pre-incremented (not a physical register) N/A 36, 53
PLUSW1 Uses contents of FSR1 to address data memory – value of FSR1 offset by W (not a physical register) N/A 36, 53
FSR1H — — — — Indirect Data Memory Address Pointer 1 High ---- 0000 36, 53
FSR1L Indirect Data Memory Address Pointer 1 Low Byte xxxx xxxx 36, 53
BSR — — — — Bank Select Register ---- 0000 37, 52
INDF2 Uses contents of FSR2 to address data memory – value of FSR2 not changed (not a physical register) N/A 37, 53
POSTINC2 Uses contents of FSR2 to address data memory – value of FSR2 post-incremented (not a physical register) N/A 37, 53
POSTDEC2 Uses contents of FSR2 to address data memory – value of FSR2 post-decremented (not a physical register) N/A 37, 53
PREINC2 Uses contents of FSR2 to address data memory – value of FSR2 pre-incremented (not a physical register) N/A 37, 53
PLUSW2 Uses contents of FSR2 to address data memory – value of FSR2 offset by W (not a physical register) N/A 37, 53
FSR2H — — — — Indirect Data Memory Address Pointer 2 High ---- 0000 37, 53
FSR2L Indirect Data Memory Address Pointer 2 Low Byte xxxx xxxx 37, 53
STATUS — — — N OV Z DC C ---x xxxx 37, 55
TMR0H Timer0 Register High Byte 0000 0000 37, 101
TMR0L Timer0 Register Low Byte xxxx xxxx 37, 101
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 37, 99
OSCCON IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 0000 q000 37, 17
LVDCON — — IVRST LVDEN LVDL3 LVDL2 LVDL1 LVDL0 --00 0101 37, 167
WDTCON — — — — — — — SWDTEN --- ---0 37, 180
RCON IPEN — — RI TO PD POR BOR 0--1 11q0 35, 56, 84
Legend: x = unknown, u = unchanged, – = unimplemented, q = value depends on condition
Note 1: RA6 and associated bits are configured as port pins in RCIO, ECIO and INTIO2 (with port function on RA6) Oscillator mode only and read ‘0’
in all other oscillator modes.
2: RA7 and associated bits are configured as port pins in INTIO2 Oscillator mode only and read ‘0’ in all other modes.
3: Bit 21 of the PC is only available in Test mode and Serial Programming modes.
4: The RA5 port bit is only available when MCLRE fuse (CONFIG3H<7>) is programmed to ‘0’. Otherwise, RA5 reads ‘0’. This bit is read-only.© 2007 Microchip Technology Inc. DS39605F-page 51
PIC18F1220/1320
TMR1H Timer1 Register High Byte xxxx xxxx 37, 108
TMR1L Timer1 Register Low Byte xxxx xxxx 37, 108
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0000 0000 37, 103
TMR2 Timer2 Register 0000 0000 37, 109
PR2 Timer2 Period Register 1111 1111 37, 109
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 37, 109
ADRESH A/D Result Register High Byte xxxx xxxx 37, 164
ADRESL A/D Result Register Low Byte xxxx xxxx 37, 164
ADCON0 VCFG1 VCFG0 — CHS2 CHS1 CHS0 GO/DONE ADON 00-0 0000 37, 155
ADCON1 — PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0 -000 0000 37, 156
ADCON2 ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 0-00 0000 37, 157
CCPR1H Capture/Compare/PWM Register 1 High Byte xxxx xxxx 37. 116
CCPR1L Capture/Compare/PWM Register 1 Low Byte xxxx xxxx 37, 116
CCP1CON P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 0000 0000 37, 115
PWM1CON PRSEN PDC6 PDC5 PDC4 PDC3 PDC2 PDC1 PDC0 0000 0000 37, 126
ECCPAS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1 PSSBD0 0000 0000 37, 127
TMR3H Timer3 Register High Byte xxxx xxxx 38, 113
TMR3L Timer3 Register Low Byte xxxx xxxx 38, 113
T3CON RD16 — T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0-00 0000 38, 111
SPBRGH EUSART Baud Rate Generator High Byte 0000 0000 38
SPBRG EUSART Baud Rate Generator Low Byte 0000 0000 38, 135
RCREG EUSART Receive Register 0000 0000 38, 143,
142
TXREG EUSART Transmit Register 0000 0000 38, 140,
142
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 38, 132
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 38, 133
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 38
EEADR EEPROM Address Register 0000 0000 38, 67
EEDATA EEPROM Data Register 0000 0000 38, 70
EECON2 EEPROM Control Register 2 (not a physical register) 0000 0000 38, 58, 67
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 38, 59, 68
IPR2 OSCFIP — — EEIP — LVDIP TMR3IP — 1--1 -11- 38, 83
PIR2 OSCFIF — — EEIF — LVDIF TMR3IF — 0--0 -00- 38, 79
PIE2 OSCFIE — — EEIE — LVDIE TMR3IE — 0--0 -00- 38, 81
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 38, 82
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 38, 78
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 38, 80
OSCTUNE — — TUN5 TUN4 TUN3 TUN2 TUN1 TUN0 --00 0000 38, 15
TRISB Data Direction Control Register for PORTB 1111 1111 38, 98
TRISA TRISA7(2) TRISA6(1) — Data Direction Control Register for PORTA 11-1 1111 38, 89
LATB Read/Write PORTB Data Latch xxxx xxxx 38, 98
LATA LATA<7>(2) LATA<6>(1) — Read/Write PORTA Data Latch xx-x xxxx 38, 89
PORTB Read PORTB pins, Write PORTB Data Latch xxxx xxxx 38, 98
PORTA RA7(2) RA6(1) RA5(4) Read PORTA pins, Write PORTA Data Latch xx0x 0000 38, 89
TABLE 5-2: REGISTER FILE SUMMARY (PIC18F1220/1320) (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details on
page:
Legend: x = unknown, u = unchanged, – = unimplemented, q = value depends on condition
Note 1: RA6 and associated bits are configured as port pins in RCIO, ECIO and INTIO2 (with port function on RA6) Oscillator mode only and read ‘0’
in all other oscillator modes.
2: RA7 and associated bits are configured as port pins in INTIO2 Oscillator mode only and read ‘0’ in all other modes.
3: Bit 21 of the PC is only available in Test mode and Serial Programming modes.
4: The RA5 port bit is only available when MCLRE fuse (CONFIG3H<7>) is programmed to ‘0’. Otherwise, RA5 reads ‘0’. This bit is read-only.PIC18F1220/1320
DS39605F-page 52 © 2007 Microchip Technology Inc.
5.10 Access Bank
The Access Bank is an architectural enhancement
which 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 last 128 bytes in
Bank 15 (SFRs) and the first 128 bytes in Bank 0.
These two sections will be referred to as Access RAM
High and Access RAM Low, respectively. Figure 5-6
indicates the Access RAM areas.
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 as 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 these registers can
be accessed without any software overhead. This is
useful for testing status flags and modifying control bits.
5.11 Bank Select Register (BSR)
The need for a large general purpose memory space
dictates a RAM banking scheme. The data memory is
partitioned into as many as sixteen banks. When using
direct addressing, the BSR should be configured for the
desired bank.
BSR<3:0> holds the upper 4 bits of the 12-bit RAM
address. The BSR<7:4> bits will always read ‘0’s and
writes will have no effect (see Figure 5-7).
A MOVLB 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. The
Status register bits will be set/cleared as appropriate for
the instruction performed.
Each Bank extends up to FFh (256 bytes). All data
memory is implemented as static RAM.
A MOVFF instruction ignores the BSR, since the 12-bit
addresses are embedded into the instruction word.
Section 5.12 “Indirect Addressing, INDF and FSR
Registers” provides a description of indirect addressing,
which allows linear addressing of the entire RAM
space.
FIGURE 5-7: DIRECT ADDRESSING
Note 1: For register file map detail, see Table 5-1.
2: The access bit of the instruction can be used to force an override of the selected bank (BSR<3:0>) to the registers
of the Access Bank.
3: The MOVFF instruction embeds the entire 12-bit address in the instruction.
Data
Memory(1)
Direct Addressing
Bank Select(2) Location Select(3)
BSR<3:0> 7 From Opcode 0 (3)
00h 01h 0Eh 0Fh
Bank 0 Bank 1 Bank 14 Bank 15
1FFh
100h
0FFh
000h
EFFh
E00h
FFFh
F00h
BSR<7:4>
000 0© 2007 Microchip Technology Inc. DS39605F-page 53
PIC18F1220/1320
5.12 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 FSR 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 5-8
shows how the fetched instruction is modified prior to
being executed.
Indirect addressing is possible by using one of the
INDF registers. 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 (NOP). The
FSR register contains a 12-bit address, which is shown
in Figure 5-9.
The INDFn register is not a physical register. Addressing
INDFn actually addresses the register whose
address is contained in the FSRn register (FSRn is a
pointer). This is indirect addressing.
Example 5-5 shows a simple use of indirect addressing
to clear the RAM in Bank 1 (locations 100h-1FFh) in a
minimum number of instructions.
EXAMPLE 5-5: HOW TO CLEAR RAM
(BANK 1) USING
INDIRECT ADDRESSING
There are three indirect addressing registers. To
address the entire data memory space (4096 bytes),
these registers are 12-bit wide. To store the 12 bits of
addressing information, two 8-bit registers are required:
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 reads
the data from the address pointed to by
FSR1H:FSR1L. INDFn can be used in code anywhere
an operand can be used.
If INDF0, INDF1 or INDF2 are read indirectly via an
FSR, all ‘0’s are read (zero bit is set). Similarly, if
INDF0, INDF1 or INDF2 are written to indirectly, the
operation will be equivalent to a NOP instruction and the
Status bits are not affected.
5.12.1 INDIRECT ADDRESSING
OPERATION
Each FSR register has an INDF register associated with
it, plus four additional register addresses. Performing an
operation using one of these five registers determines
how the FSR will be modified during indirect addressing.
When data access is performed using 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
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.
Auto-incrementing or auto-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. The WREG offset range is -128 to +127.
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 write is performed when the target
address is an FSRnH or FSRnL register, the data is
written to the FSR register, but no pre- or post-increment/
decrement is performed.
LFSR FSR0,0x100 ;
NEXT CLRF POSTINC0 ; Clear INDF
; register then
; inc pointer
BTFSS FSR0H, 1 ; All done with
; Bank1?
GOTO NEXT ; NO, clear next
CONTINUE ; YES, continue PIC18F1220/1320
DS39605F-page 54 © 2007 Microchip Technology Inc.
FIGURE 5-8: INDIRECT ADDRESSING OPERATION
FIGURE 5-9: INDIRECT ADDRESSING
Opcode Address
File Address = Access of an Indirect Addressing Register
FSR
Instruction
Executed
Instruction
Fetched
RAM
Opcode File
12 12
12
BSR<3:0>
4 8
0h
FFFh
Note 1: For register file map detail, see Table 5-1.
Data
Memory(1)
Indirect Addressing
FSRnH:FSRnL
3 0
0FFFh
0000h
Location Select
11 0
0 7© 2007 Microchip Technology Inc. DS39605F-page 55
PIC18F1220/1320
5.13 Status Register
The Status register, shown in Register 5-2, contains the
arithmetic status of the ALU. As with any other SFR, it
can be the operand for any instruction.
If the Status register is the destination for an instruction
that affects the Z, DC, C, OV or N bits, the results of the
instruction are not written; instead, the status is
updated according to the instruction performed. Therefore,
the result of an instruction with the Status register
as its destination may be different than intended. As an
example, CLRF STATUS will set the Z bit and leave the
remaining Status bits unchanged (‘000u u1uu’).
It is recommended that only BCF, BSF, SWAPF, MOVFF
and MOVWF instructions are used to alter the Status register,
because these instructions do not affect the Z, C,
DC, OV or N bits in the Status register.
For other instructions that do not affect Status bits, see
the instruction set summaries in Table 20-1.
REGISTER 5-2: STATUS REGISTER
Note: The C and DC bits operate as the borrow
and digit borrow bits, respectively, in
subtraction.
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 (bit 7) 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: 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 bit 4 or bit 3 of the source register.
bit 0 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 W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 56 © 2007 Microchip Technology Inc.
5.14 RCON Register
The Reset Control (RCON) register contains flag bits
that allow differentiation between the sources of a
device Reset. These flags include the TO, PD, POR,
BOR and RI bits. This register is readable and writable.
REGISTER 5-3: RCON REGISTER
Note 1: If the BOR configuration bit is set (Brownout
Reset enabled), the BOR bit is ‘1’ on
a Power-on Reset. After a Brown-out
Reset has occurred, the BOR bit will be
cleared and must be set by firmware to
indicate the occurrence of the next
Brown-out Reset.
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.
R/W-0 U-0 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN — — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6-5 Unimplemented: Read as ‘0’
bit 4 RI: RESET Instruction Flag bit
1 = The RESET instruction was not executed (set by firmware only)
0 = The RESET instruction was executed causing a device Reset
(must be set in software after a Brown-out Reset occurs)
bit 3 TO: Watchdog Time-out Flag bit
1 = Set by power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred
bit 2 PD: Power-down Detection Flag bit
1 = Set by power-up or by the CLRWDT instruction
0 = Cleared by execution of the SLEEP instruction
bit 1 POR: Power-on Reset Status bit
1 = A Power-on Reset has not occurred (set by firmware only)
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 = A Brown-out Reset has not occurred (set by firmware only)
0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset occurs)
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 57
PIC18F1220/1320
6.0 FLASH PROGRAM MEMORY
The Flash program memory is readable, writable and
erasable during normal operation over the entire VDD
range.
A read from program memory is executed on one byte
at a time. A write to program memory is executed on
blocks of 8 bytes at a time. Program memory is erased
in blocks of 64 bytes at a time. A “Bulk Erase” operation
may not be issued from user code.
While writing or erasing program memory, instruction
fetches cease until the operation is complete. The
program memory cannot be accessed during the write
or erase, therefore, code cannot execute. An internal
programming timer terminates program memory writes
and erases.
A value written to program memory does not need to be
a valid instruction. Executing a program memory
location that forms an invalid instruction results in a
NOP.
6.1 Table Reads and Table Writes
In order to read and write program memory, there are
two operations that allow the processor to move bytes
between the program memory space and the data
RAM:
• Table Read (TBLRD)
• Table Write (TBLWT)
The program memory space is 16 bits wide, while the
data RAM space is 8 bits wide. Table reads and table
writes move data between these two memory spaces
through an 8-bit register (TABLAT).
Table read operations retrieve data from program
memory and place it into TABLAT in the data RAM
space. Figure 6-1 shows the operation of a table read
with program memory and data RAM.
Table write operations store data from TABLAT in the
data memory space into holding registers in program
memory. The procedure to write the contents of the
holding registers into program memory is detailed in
Section 6.5 “Writing to Flash Program Memory”.
Figure 6-2 shows the operation of a table write with
program memory and data RAM.
Table operations work with byte entities. A table block
containing data, rather than program instructions, is not
required to be word aligned. Therefore, a table block
can start and end at any byte address. If a table write is
being used to write executable code into program
memory, program instructions will need to be word
aligned (TBLPTRL<0> = 0).
The EEPROM on-chip timer controls the write and
erase times. The write and erase voltages are generated
by an on-chip charge pump rated to operate over
the voltage range of the device for byte or word
operations.
FIGURE 6-1: TABLE READ OPERATION
Table Pointer(1)
Table Latch (8-bit)
Program Memory
TBLPTRH TBLPTRL
TABLAT
TBLPTRU
Instruction: TBLRD*
Note 1: Table Pointer points to a byte in program memory.
Program Memory
(TBLPTR)PIC18F1220/1320
DS39605F-page 58 © 2007 Microchip Technology Inc.
FIGURE 6-2: TABLE WRITE OPERATION
6.2 Control Registers
Several control registers are used in conjunction with
the TBLRD and TBLWT instructions. These include the:
• EECON1 register
• EECON2 register
• TABLAT register
• TBLPTR registers
6.2.1 EECON1 AND EECON2 REGISTERS
EECON1 is the control register for memory accesses.
EECON2 is not a physical register. Reading EECON2
will read all ‘0’s. The EECON2 register is used
exclusively in the memory write and erase sequences.
Control bit, EEPGD, determines if the access will be to
program or data EEPROM memory. When clear,
operations will access the data EEPROM memory.
When set, program memory is accessed.
Control bit, CFGS, determines if the access will be to
the configuration registers, or to program memory/data
EEPROM memory. When set, subsequent operations
access configuration registers. When CFGS is clear,
the EEPGD bit selects either program Flash or data
EEPROM memory.
The FREE bit controls program memory erase operations.
When the FREE bit is set, the erase operation is
initiated on the next WR command. When FREE is
clear, only writes are enabled.
The WREN bit enables and disables erase and write
operations. When set, erase and write operations are
allowed. When clear, erase and write operations are
disabled – the WR bit cannot be set while the WREN bit
is clear. This process helps to prevent accidental writes
to memory due to errant (unexpected) code execution.
Firmware should keep the WREN bit clear at all times,
except when starting erase or write operations. Once
firmware has set the WR bit, the WREN bit may be
cleared. Clearing the WREN bit will not affect the
operation in progress.
The WRERR bit is set when a write operation is
interrupted by a Reset. In these situations, the user can
check the WRERR bit and rewrite the location. It will be
necessary to reload the data and address registers
(EEDATA and EEADR) as these registers have cleared
as a result of the Reset.
Control bits, RD and WR, start read and erase/write
operations, respectively. These bits are set by firmware
and cleared by hardware at the completion of the
operation.
The RD bit cannot be set when accessing program
memory (EEPGD = 1). Program memory is read using
table read instructions. See Section 6.3 “Reading the
Flash Program Memory” regarding table reads.
Table Pointer(1) Table Latch (8-bit)
TBLPTRH TBLPTRL TABLAT
Program Memory
(TBLPTR)
TBLPTRU
Instruction: TBLWT*
Note 1: Table Pointer actually points to one of eight holding registers, the address of which is determined by
TBLPTRL<2:0>. The process for physically writing data to the program memory array is discussed
in Section 6.5 “Writing to Flash Program Memory”.
Holding Registers
Program Memory
Note: Interrupt flag bit, EEIF in the PIR2 register,
is set when the write is complete. It must
be cleared in software.© 2007 Microchip Technology Inc. DS39605F-page 59
PIC18F1220/1320
REGISTER 6-1: EECON1 REGISTER
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR WREN WR RD
bit 7 bit 0
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access program Flash memory
0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EE or Configuration Select bit
1 = Access configuration registers
0 = Access program Flash or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’
bit 4 FREE: Flash Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command
(cleared by completion of erase operation – TBLPTR<5:0> are ignored)
0 = Perform write only
bit 3 WRERR: EEPROM Error Flag bit
1 = A write operation was prematurely terminated (any Reset during self-timed programming)
0 = The write operation completed normally
Note: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows
tracing of the error condition.
bit 2 WREN: Write Enable bit
1 = Allows erase or write cycles
0 = Inhibits erase or write cycles
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle.
(The operation is self-timed and the bit is cleared by hardware once write is complete. The
WR bit can only be set (not cleared) in software.)
0 = Write cycle completed
bit 0 RD: Read Control bit
1 = Initiates a memory read
(Read takes one cycle. RD is cleared in hardware. The RD bit can only be set (not cleared)
in software. RD bit cannot be set when EEPGD = 1.)
0 = Read completed
Legend:
R = Readable bit S = Settable only U = Unimplemented bit, read as ‘0’
W = Writable bit -n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared
x = Bit is unknownPIC18F1220/1320
DS39605F-page 60 © 2007 Microchip Technology Inc.
6.2.2 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 RAM.
6.2.3 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, Table
Pointer High Byte and Table Pointer Low Byte
(TBLPTRU:TBLPTRH:TBLPTRL). These three registers
join to form a 22-bit wide pointer. The low-order
21 bits allow the device to address up to 2 Mbytes of
program memory space. Setting the 22nd bit allows
access to the device ID, the user ID and the
configuration bits.
The Table Pointer (TBLPTR) register 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 6-1. These operations on the TBLPTR only affect
the low-order 21 bits.
6.2.4 TABLE POINTER BOUNDARIES
TBLPTR is used in reads, writes and erases of the
Flash program memory.
When a TBLRD is executed, all 22 bits of the Table
Pointer determine which byte is read from program or
configuration memory into TABLAT.
When a TBLWT is executed, the three LSbs of the Table
Pointer (TBLPTR<2:0>) determine which of the eight
program memory holding registers is written to. When
the timed write to program memory (long write) begins,
the 19 MSbs of the Table Pointer (TBLPTR<21:3>) will
determine which program memory block of 8 bytes is
written to (TBLPTR<2:0> are ignored). For more detail,
see Section 6.5 “Writing to Flash Program Memory”.
When an erase of program memory is executed, the
16 MSbs of the Table Pointer (TBLPTR<21:6>) point to
the 64-byte block that will be erased. The Least
Significant bits (TBLPTR<5:0>) are ignored.
Figure 6-3 describes the relevant boundaries of
TBLPTR based on Flash program memory operations.
TABLE 6-1: TABLE POINTER OPERATIONS WITH TBLRD AND TBLWT INSTRUCTIONS
FIGURE 6-3: TABLE POINTER BOUNDARIES BASED ON OPERATION
Example 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
21 16 15 8 7 0
ERASE – TBLPTR<21:6>
LONG WRITE – TBLPTR<21:3>
READ or WRITE – TBLPTR<21:0>
TBLPTRU TBLPTRH TBLPTRL© 2007 Microchip Technology Inc. DS39605F-page 61
PIC18F1220/1320
6.3 Reading the Flash Program
Memory
The TBLRD instruction is used to retrieve data from
program memory and place it into data RAM. Table
reads from program memory are performed one byte at
a time.
TBLPTR points to a byte address in program space.
Executing a TBLRD instruction places the byte pointed
to into TABLAT. In addition, TBLPTR can be modified
automatically for the next table read operation.
The internal program memory is typically organized by
words. The Least Significant bit of the address selects
between the high and low bytes of the word. Figure 6-4
shows the interface between the internal program
memory and the TABLAT.
FIGURE 6-4: READS FROM FLASH PROGRAM MEMORY
EXAMPLE 6-1: READING A FLASH PROGRAM MEMORY WORD
Odd (High) Byte
Program Memory
Even (Low) Byte
TABLAT
TBLPTR
Instruction Register
(IR) Read Register
LSB = 1
TBLPTR
LSB = 0
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the word
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
READ_WORD
TBLRD*+ ; read into TABLAT and increment TBLPTR
MOVFW TABLAT ; get data
MOVWF WORD_EVEN
TBLRD*+ ; read into TABLAT and increment TBLPTR
MOVFW TABLAT ; get data
MOVWF WORD_ODDPIC18F1220/1320
DS39605F-page 62 © 2007 Microchip Technology Inc.
6.4 Erasing Flash Program Memory
The minimum erase block size is 32 words or 64 bytes
under firmware control. Only through the use of an
external programmer, or through ICSP control, can
larger blocks of program memory be bulk erased. Word
erase in Flash memory is not supported.
When initiating an erase sequence from the microcontroller
itself, a block of 64 bytes of program memory
is erased. The Most Significant 16 bits of the
TBLPTR<21:6> point to the block being erased.
TBLPTR<5:0> are ignored.
The EECON1 register commands the erase operation.
The EEPGD bit must be set to point to the Flash
program memory. The CFGS bit must be clear to
access program Flash and data EEPROM memory.
The WREN bit must be set to enable write operations.
The FREE bit is set to select an erase operation. The
WR bit is set as part of the required instruction
sequence (as shown in Example 6-2) and starts the
actual erase operation. It is not necessary to load the
TABLAT register with any data as it is ignored.
For protection, the write initiate sequence using
EECON2 must be used.
A long write is necessary for erasing the internal Flash.
Instruction execution is halted while in a long write
cycle. The long write will be terminated by the internal
programming timer.
6.4.1 FLASH PROGRAM MEMORY
ERASE SEQUENCE
The sequence of events for erasing a block of internal
program memory location is:
1. Load Table Pointer with address of row being
erased.
2. Set the EECON1 register for the erase operation:
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program
memory;
• set WREN bit to enable writes;
• set FREE bit to enable the erase.
3. Disable interrupts.
4. Write 55h to EECON2.
5. Write AAh to EECON2.
6. Set the WR bit. This will begin the row erase
cycle.
7. The CPU will stall for duration of the erase
(about 2 ms using internal timer).
8. Execute a NOP.
9. Re-enable interrupts.
EXAMPLE 6-2: ERASING A FLASH PROGRAM MEMORY ROW
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
ERASE_ROW
BSF EECON1, EEPGD ; point to FLASH program memory
BSF EECON1, WREN ; enable write to memory
BSF EECON1, FREE ; enable Row Erase operation
BCF INTCON, GIE ; disable interrupts
MOVLW 55h
MOVWF EECON2 ; write 55H
Required MOVLW AAh
Sequence MOVWF EECON2 ; write AAH
BSF EECON1, WR ; start erase (CPU stall)
NOP
BSF INTCON, GIE ; re-enable interrupts© 2007 Microchip Technology Inc. DS39605F-page 63
PIC18F1220/1320
6.5 Writing to Flash Program Memory
The programming block size is 4 words or 8 bytes.
Word or byte programming is not supported.
Table writes are used internally to load the holding
registers needed to program the Flash memory. There
are 8 holding registers used by the table writes for
programming.
Since the Table Latch (TABLAT) is only a single byte,
the TBLWT instruction must be executed 8 times for
each programming operation. All of the table write
operations will essentially be short writes, because only
the holding registers are written. At the end of updating
8 registers, the EECON1 register must be written to, to
start the programming operation with a long write.
The long write is necessary for programming the
internal Flash. Instruction execution is halted while in a
long write cycle. The long write will be terminated by
the internal programming timer.
FIGURE 6-5: TABLE WRITES TO FLASH PROGRAM MEMORY
6.5.1 FLASH PROGRAM MEMORY WRITE
SEQUENCE
The sequence of events for programming an internal
program memory location should be:
1. Read 64 bytes into RAM.
2. Update data values in RAM as necessary.
3. Load Table Pointer with address being erased.
4. Do the row erase procedure (see Section 6.4.1
“Flash Program Memory Erase Sequence”).
5. Load Table Pointer with address of first byte
being written.
6. Write the first 8 bytes into the holding registers
with auto-increment.
7. Set the EECON1 register for the write operation:
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program
memory;
• set WREN bit to enable byte writes.
8. Disable interrupts.
9. Write 55h to EECON2.
10. Write AAh to EECON2.
11. Set the WR bit. This will begin the write cycle.
12. The CPU will stall for duration of the write (about
2 ms using internal timer).
13. Execute a NOP.
14. Re-enable interrupts.
15. Repeat steps 6-14 seven times to write
64 bytes.
16. Verify the memory (table read).
This procedure will require about 18 ms to update one
row of 64 bytes of memory. An example of the required
code is given in Example 6-3.
Holding Register
TABLAT
Holding Register
TBLPTR = xxxxx7
Holding Register
TBLPTR = xxxxx1
Holding Register
TBLPTR = xxxxx0
8 8 8 8
Write Register
TBLPTR = xxxxx2
Program MemoryPIC18F1220/1320
DS39605F-page 64 © 2007 Microchip Technology Inc.
EXAMPLE 6-3: WRITING TO FLASH PROGRAM MEMORY
MOVLW D'64 ; number of bytes in erase block
MOVWF COUNTER
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW ; 6 LSB = 0
MOVWF TBLPTRL
READ_BLOCK
TBLRD*+ ; read into TABLAT, and inc
MOVF TABLAT, W ; get data
MOVWF POSTINC0 ; store data and increment FSR0
DECFSZ COUNTER ; done?
GOTO READ_BLOCK ; repeat
MODIFY_WORD
MOVLW DATA_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW DATA_ADDR_LOW
MOVWF FSR0L
MOVLW NEW_DATA_LOW ; update buffer word and increment FSR0
MOVWF POSTINC0
MOVLW NEW_DATA_HIGH ; update buffer word
MOVWF INDF0
ERASE_BLOCK
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW ; 6 LSB = 0
MOVWF TBLPTRL
BCF EECON1, CFGS ; point to PROG/EEPROM memory
BSF EECON1, EEPGD ; point to FLASH program memory
BSF EECON1, WREN ; enable write to memory
BSF EECON1, FREE ; enable Row Erase operation
BCF INTCON, GIE ; disable interrupts
MOVLW 55h ; Required sequence
MOVWF EECON2 ; write 55H
MOVLW AAh
MOVWF EECON2 ; write AAH
BSF EECON1, WR ; start erase (CPU stall)
NOP
BSF INTCON, GIE ; re-enable interrupts
WRITE_BUFFER_BACK
MOVLW 8 ; number of write buffer groups of 8 bytes
MOVWF COUNTER_HI
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
PROGRAM_LOOP
MOVLW 8 ; number of bytes in holding register
MOVWF COUNTER© 2007 Microchip Technology Inc. DS39605F-page 65
PIC18F1220/1320
EXAMPLE 6-3: WRITING TO FLASH PROGRAM MEMORY (CONTINUED)
6.5.2 WRITE VERIFY
Depending on the application, good programming
practice may dictate that the value written to the memory
should be verified against the original value. This
should be used in applications where excessive writes
can stress bits near the specification limit.
6.5.3 UNEXPECTED TERMINATION OF
WRITE OPERATION
If a write is terminated by an unplanned event, such as
loss of power or an unexpected Reset, the memory
location just programmed should be verified and reprogrammed
if needed. The WRERR bit is set when a
write operation is interrupted by a MCLR Reset, or a
WDT Time-out Reset during normal operation. In these
situations, users can check the WRERR bit and rewrite
the location.
6.6 Flash Program Operation During
Code Protection
See Section 19.0 “Special Features of the CPU” for
details on code protection of Flash program memory.
TABLE 6-2: REGISTERS ASSOCIATED WITH PROGRAM FLASH MEMORY
WRITE_WORD_TO_HREGS
MOVF POSTINC0, W ; get low byte of buffer data and increment FSR0
MOVWF TABLAT ; present data to table latch
TBLWT+* ; short write
; to internal TBLWT holding register, increment
TBLPTR
DECFSZ COUNTER ; loop until buffers are full
GOTO WRITE_WORD_TO_HREGS
PROGRAM_MEMORY
BCF INTCON, GIE ; disable interrupts
MOVLW 55h ; required sequence
MOVWF EECON2 ; write 55H
MOVLW AAh
MOVWF EECON2 ; write AAH
BSF EECON1, WR ; start program (CPU stall)
NOP
BSF INTCON, GIE ; re-enable interrupts
DECFSZ COUNTER_HI ; loop until done
GOTO PROGRAM_LOOP
BCF EECON1, WREN ; disable write to memory
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
TBLPTRU — — bit 21 Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) --00 0000 --00 0000
TBPLTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 0000 0000 0000 0000
TBLPTRL Program Memory Table Pointer High Byte (TBLPTR<7:0>) 0000 0000 0000 0000
TABLAT Program Memory Table Latch 0000 0000 0000 0000
INTCON GIE/GIEH PEIE/GIEL TMR0IE INTE RBIE TMR0IF INTF RBIF 0000 000x 0000 000u
EECON2 EEPROM Control Register 2 (not a physical register) — —
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 uu-0 u000
IPR2 OSCFIP — — EEIP — LVDIP TMR3IP — 1--1 -11- 1--1 -11-
PIR2 OSCFIF — — EEIF — LVDIF TMR3IF — 0--0 -00- 0--0 -00-
PIE2 OSCFIE — — EEIE — LVDIE TMR3IE — 0--0 -00- 0--0 -00-
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’.
Shaded cells are not used during Flash/EEPROM access.PIC18F1220/1320
DS39605F-page 66 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 67
PIC18F1220/1320
7.0 DATA EEPROM MEMORY
The data EEPROM is readable and writable during
normal operation over the entire VDD range. The data
memory is not directly mapped in the register file
space. Instead, it is indirectly addressed through the
Special Function Registers (SFR).
There are four SFRs used to read and write the
program and data EEPROM memory. These registers
are:
• EECON1
• EECON2
• EEDATA
• EEADR
The EEPROM data memory allows byte read and write.
When interfacing to the data memory block, EEDATA
holds the 8-bit data for read/write and EEADR holds the
address of the EEPROM location being accessed.
These devices have 256 bytes of data EEPROM with
an address range from 00h to FFh.
The EEPROM data memory is rated for high erase/
write cycle endurance. A byte write automatically
erases the location and writes the new data (erasebefore-write).
The write time is controlled by an on-chip
timer. The write time will vary with voltage and
temperature, as well as from chip to chip. Please
refer to parameter D122 (Table 22-1 in Section 22.0
“Electrical Characteristics”) for exact limits.
7.1 EEADR
The address register can address 256 bytes of data
EEPROM.
7.2 EECON1 and EECON2 Registers
EECON1 is the control register for memory accesses.
EECON2 is not a physical register. Reading EECON2
will read all ‘0’s. The EECON2 register is used
exclusively in the memory write and erase sequences.
Control bit, EEPGD, determines if the access will be to
program or data EEPROM memory. When clear,
operations will access the data EEPROM memory.
When set, program memory is accessed.
Control bit, CFGS, determines if the access will be to
the configuration registers or to program memory/data
EEPROM memory. When set, subsequent operations
access configuration registers. When CFGS is clear,
the EEPGD bit selects either program Flash or data
EEPROM memory.
The WREN bit enables and disables erase and write
operations. When set, erase and write operations are
allowed. When clear, erase and write operations are
disabled – the WR bit cannot be set while the WREN bit
is clear. This mechanism helps to prevent accidental
writes to memory due to errant (unexpected) code
execution.
Firmware should keep the WREN bit clear at all times,
except when starting erase or write operations. Once
firmware has set the WR bit, the WREN bit may be
cleared. Clearing the WREN bit will not affect the
operation in progress.
The WRERR bit is set when a write operation is
interrupted by a Reset. In these situations, the user can
check the WRERR bit and rewrite the location. It is
necessary to reload the data and address registers
(EEDATA and EEADR), as these registers have
cleared as a result of the Reset.
Control bits, RD and WR, start read and erase/write
operations, respectively. These bits are set by firmware
and cleared by hardware at the completion of the
operation.
The RD bit cannot be set when accessing program
memory (EEPGD = 1). Program memory is read using
table read instructions. See Section 6.1 “Table Reads
and Table Writes” regarding table reads.
Note: Interrupt flag bit, EEIF in the PIR2 register,
is set when write is complete. It must be
cleared in software.PIC18F1220/1320
DS39605F-page 68 © 2007 Microchip Technology Inc.
REGISTER 7-1: EECON1 REGISTER
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR WREN WR RD
bit 7 bit 0
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access program Flash memory
0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access configuration or calibration registers
0 = Access program Flash or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’
bit 4 FREE: Flash Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command
(cleared by completion of erase operation)
0 = Perform write only
bit 3 WRERR: EEPROM Error Flag bit
1 = A write operation was prematurely terminated
(MCLR or WDT Reset during self-timed erase or program operation)
0 = The write operation completed normally
Note: When a WRERR occurs, the EEPGD or FREE bits are not cleared. This allows
tracing of the error condition.
bit 2 WREN: Erase/Write Enable bit
1 = Allows erase/write cycles
0 = Inhibits erase/write cycles
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle, or a program memory erase cycle, or write cycle.
(The operation is self-timed and the bit is cleared by hardware once write is complete. The
WR bit can only be set (not cleared) in software.)
0 = Write cycle is completed
bit 0 RD: Read Control bit
1 = Initiates a memory read
(Read takes one cycle. RD is cleared in hardware. The RD bit can only be set (not cleared)
in software. RD bit cannot be set when EEPGD = 1.)
0 = Read completed
Legend:
R = Readable bit S = Settable only U = Unimplemented bit, read as ‘0’
W = Writable bit -n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared
x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 69
PIC18F1220/1320
7.3 Reading the Data EEPROM
Memory
To read a data memory location, the user must write the
address to the EEADR register, clear the EEPGD
control bit (EECON1<7>) and then set control bit, RD
(EECON1<0>). The data is available for the very next
instruction cycle; therefore, the EEDATA register can
be read by the next instruction. EEDATA will hold this
value until another read operation, or until it is written to
by the user (during a write operation).
7.4 Writing to the Data EEPROM
Memory
To write an EEPROM data location, the address must
first be written to the EEADR register and the data
written to the EEDATA register. The sequence in
Example 7-2 must be followed to initiate the write cycle.
The write will not begin if this sequence is not exactly
followed (write 55h to EECON2, write AAh to EECON2,
then set WR bit) for each byte. It is strongly recommended
that interrupts be disabled during this
code segment.
Additionally, the WREN bit in EECON1 must be set to
enable writes. This mechanism prevents accidental
writes to data EEPROM due to unexpected code execution
(i.e., runaway programs). The WREN bit should
be kept clear at all times, except when updating the
EEPROM. The WREN bit is not cleared by hardware.
After a write sequence has been initiated, EECON1,
EEADR and EEDATA cannot be modified. The WR bit
will be inhibited from being set unless the WREN bit is
set. The WREN bit must be set on a previous instruction.
Both WR and WREN cannot be set with the same
instruction.
At the completion of the write cycle, the WR bit is
cleared in hardware and the EEPROM Interrupt Flag bit
(EEIF) is set. The user may either enable this interrupt
or poll this bit. EEIF must be cleared by software.
7.5 Write Verify
Depending on the application, good programming
practice may dictate that the value written to the
memory should be verified against the original value.
This should be used in applications where excessive
writes can stress bits near the specification limit.
7.6 Protection Against Spurious Write
There are conditions when the device may not want to
write to the data EEPROM memory. To protect against
spurious EEPROM writes, various mechanisms have
been built-in. On power-up, the WREN bit is cleared.
Also, the Power-up Timer (72 ms duration) prevents
EEPROM write.
The write initiate sequence and the WREN bit together
help prevent an accidental write during brown-out,
power glitch or software malfunction.
EXAMPLE 7-1: DATA EEPROM READ
EXAMPLE 7-2: DATA EEPROM WRITE
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to read
BCF EECON1, EEPGD ; Point to DATA memory
BSF EECON1, RD ; EEPROM Read
MOVF EEDATA, W ; W = EEDATA
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to write
MOVLW DATA_EE_DATA ;
MOVWF EEDATA ; Data Memory Value to write
BCF EECON1, EEPGD ; Point to DATA memory
BSF EECON1, WREN ; Enable writes
BCF INTCON, GIE ; Disable Interrupts
MOVLW 55h ;
Required MOVWF EECON2 ; Write 55h
Sequence MOVLW AAh ;
MOVWF EECON2 ; Write AAh
BSF EECON1, WR ; Set WR bit to begin write
BSF INTCON, GIE ; Enable Interrupts
SLEEP ; Wait for interrupt to signal write complete
BCF EECON1, WREN ; Disable writesPIC18F1220/1320
DS39605F-page 70 © 2007 Microchip Technology Inc.
7.7 Operation During Code-Protect
Data EEPROM memory has its own code-protect bits in
configuration words. External read and write
operations are disabled if either of these mechanisms
are enabled.
The microcontroller itself can both read and write to the
internal data EEPROM, regardless of the state of the
code-protect configuration bit. Refer to Section 19.0
“Special Features of the CPU” for additional
information.
7.8 Using the Data EEPROM
The data EEPROM is a high endurance, byte addressable
array that has been optimized for the storage of frequently
changing information (e.g., program variables or
other data that are updated often). Frequently changing
values will typically be updated more often than specification
D124. If this is not the case, an array refresh must
be performed. For this reason, variables that change
infrequently (such as constants, IDs, calibration, etc.)
should be stored in Flash program memory.
A simple data EEPROM refresh routine is shown in
Example 7-3.
EXAMPLE 7-3: DATA EEPROM REFRESH ROUTINE
TABLE 7-1: REGISTERS ASSOCIATED WITH DATA EEPROM MEMORY
Note: If data EEPROM is only used to store
constants and/or data that changes rarely,
an array refresh is likely not required. See
specification D124.
CLRF EEADR ; Start at address 0
BCF EECON1, CFGS ; Set for memory
BCF EECON1, EEPGD ; Set for Data EEPROM
BCF INTCON, GIE ; Disable interrupts
BSF EECON1, WREN ; Enable writes
Loop ; Loop to refresh array
BSF EECON1, RD ; Read current address
MOVLW 55h ;
MOVWF EECON2 ; Write 55h
MOVLW AAh ;
MOVWF EECON2 ; Write AAh
BSF EECON1, WR ; Set WR bit to begin write
BTFSC EECON1, WR ; Wait for write to complete
BRA $-2
INCFSZ EEADR, F ; Increment address
BRA Loop ; Not zero, do it again
BCF EECON1, WREN ; Disable writes
BSF INTCON, GIE ; Enable interrupts
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 INTE RBIE TMR0IF INTF RBIF 0000 000x 0000 000u
EEADR EEPROM Address Register 0000 0000 0000 0000
EEDATA EEPROM Data Register 0000 0000 0000 0000
EECON2 EEPROM Control Register 2 (not a physical register) — —
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 uu-0 u000
IPR2 OSCFIP — — EEIP — LVDIP TMR3IP — 1--1 -11- 1--1 -11-
PIR2 OSCFIF — — EEIF — LVDIF TMR3IF — 0--0 -00- 0--0 -00-
PIE2 OSCFIE — — EEIE — LVDIE TMR3IE — 0--0 -00- 0--0 -00-
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.© 2007 Microchip Technology Inc. DS39605F-page 71
PIC18F1220/1320
8.0 8 x 8 HARDWARE MULTIPLIER
8.1 Introduction
An 8 x 8 hardware multiplier is included in the ALU of
the PIC18F1220/1320 devices. By making the multiply
a hardware operation, it completes in a single instruction
cycle. This is an unsigned multiply that gives a
16-bit result. The result is stored into the 16-bit product
register pair (PRODH:PRODL). The multiplier does not
affect any flags in the Status register.
Making the 8 x 8 multiplier execute in a single cycle
gives the following advantages:
• Higher computational throughput
• Reduces code size requirements for multiply
algorithms
The performance increase allows the device to be used
in applications previously reserved for Digital Signal
Processors.
Table 8-1 shows a performance comparison between
Enhanced devices using the single-cycle hardware
multiply and performing the same function without the
hardware multiply.
TABLE 8-1: PERFORMANCE COMPARISON
8.2 Operation
Example 8-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.
Example 8-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 8-1: 8 x 8 UNSIGNED
MULTIPLY ROUTINE
EXAMPLE 8-2: 8 x 8 SIGNED MULTIPLY
ROUTINE
Routine Multiply Method
Program
Memory
(Words)
Cycles
(Max)
Time
@ 40 MHz @ 10 MHz @ 4 MHz
8 x 8 unsigned Without hardware multiply 13 69 6.9 μs 27.6 μs 69 μs
Hardware multiply 1 1 100 ns 400 ns 1 μs
8 x 8 signed Without hardware multiply 33 91 9.1 μs 36.4 μs 91 μs
Hardware multiply 6 6 600 ns 2.4 μs 6 μs
16 x 16 unsigned Without hardware multiply 21 242 24.2 μs 96.8 μs 242 μs
Hardware multiply 28 28 2.8 μs 11.2 μs 28 μs
16 x 16 signed Without hardware multiply 52 254 25.4 μs 102.6 μs 254 μs
Hardware multiply 35 40 4 μs 16 μs 40 μs
MOVF ARG1, W ;
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
MOVF ARG1, W
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
BTFSC ARG2, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG1
MOVF ARG2, W
BTFSC ARG1, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG2 PIC18F1220/1320
DS39605F-page 72 © 2007 Microchip Technology Inc.
Example 8-3 shows the sequence to do a 16 x 16
unsigned multiply. Equation 8-1 shows the algorithm
that is used. The 32-bit result is stored in four registers,
RES3:RES0.
EQUATION 8-1: 16 x 16 UNSIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 8-3: 16 x 16 UNSIGNED
MULTIPLY ROUTINE
Example 8-4 shows the sequence to do a 16 x 16
signed multiply. Equation 8-2 shows the algorithm
used. The 32-bit result is stored in four registers,
RES3: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 8-2: 16 x 16 SIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 8-4: 16 x 16 SIGNED
MULTIPLY ROUTINE
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3,F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
RES3:RES0
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28
) +
(ARG1L • ARG2H • 28
) +
(ARG1L • ARG2L)
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
BTFSS ARG2H, 7 ; ARG2H:ARG2L neg?
BRA SIGN_ARG1 ; no, check ARG1
MOVF ARG1L, W ;
SUBWF RES2 ;
MOVF ARG1H, W ;
SUBWFB RES3
;
SIGN_ARG1
BTFSS ARG1H, 7 ; ARG1H:ARG1L neg?
BRA CONT_CODE ; no, done
MOVF ARG2L, W ;
SUBWF RES2 ;
MOVF ARG2H, W ;
SUBWFB RES3
;
CONT_CODE
:
RES3:RES0
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28) +
(ARG1L • ARG2H • 28) +
(ARG1L • ARG2L) +
(-1 • ARG2H<7> • ARG1H:ARG1L • 216) +
(-1 • ARG1H<7> • ARG2H:ARG2L • 216) © 2007 Microchip Technology Inc. DS39605F-page 73
PIC18F1220/1320
9.0 INTERRUPTS
The PIC18F1220/1320 devices have multiple interrupt
sources and an interrupt priority feature that allows
each interrupt source to be assigned a high priority
level or a low priority level. The high priority interrupt
vector is at 000008h and the low priority interrupt vector
is at 000018h. High priority interrupt events will
interrupt any low priority interrupts that may be in
progress.
There are ten registers which are used to control
interrupt operation. These registers are:
• RCON
• INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
It is recommended that the Microchip header files
supplied with MPLAB® IDE be used for the symbolic bit
names in these registers. This allows the assembler/
compiler to automatically take care of the placement of
these bits within the specified register.
In general, each interrupt source has three bits to
control its operation. The functions of these bits are:
• Flag bit to indicate that an interrupt event
occurred
• Enable bit that allows program execution to
branch to the interrupt vector address when the
flag bit is set
• Priority bit to select high priority or low priority
(INT0 has no priority bit and is always high priority)
The interrupt priority feature is enabled by setting the
IPEN bit (RCON<7>). When interrupt priority is
enabled, there are two bits which enable interrupts
globally. Setting the GIEH bit (INTCON<7>) enables all
interrupts that have the priority bit set (high priority).
Setting the GIEL bit (INTCON<6>) enables all
interrupts that have the priority bit cleared (low priority).
When the interrupt flag, enable bit and appropriate
global interrupt enable bit are set, the interrupt will
vector immediately to address 000008h or 000018h,
depending on the priority bit setting. Individual
interrupts can be disabled through their corresponding
enable bits.
When the IPEN bit is cleared (default state), the
interrupt priority feature is disabled and interrupts are
compatible with PIC mid-range devices. In
Compatibility mode, the interrupt priority bits for each
source have no effect. INTCON<6> is the PEIE bit,
which enables/disables all peripheral interrupt sources.
INTCON<7> is the GIE bit, which enables/disables all
interrupt sources. All interrupts branch to address
000008h in Compatibility mode.
When an interrupt is responded to, the global interrupt
enable bit is cleared to disable further interrupts. If the
IPEN bit is cleared, this is the GIE bit. If interrupt priority
levels are used, this will be either the GIEH or GIEL bit.
High priority interrupt sources can interrupt a low
priority interrupt. Low priority interrupts are not
processed while high priority interrupts are in progress.
The return address is pushed onto the stack and the
PC is loaded with the interrupt vector address
(000008h or 000018h). Once in the Interrupt Service
Routine, the source(s) of the interrupt can be determined
by polling the interrupt flag bits. The interrupt
flag bits must be cleared in software before re-enabling
interrupts to avoid recursive interrupts.
The “return from interrupt” instruction, RETFIE, exits
the interrupt routine and sets the GIE bit (GIEH or
GIEL, if priority levels are used), which re-enables
interrupts.
For external interrupt events, such as the INT pins or
the PORTB input change interrupt, the interrupt latency
will be three to four instruction cycles. The exact
latency is the same for one or two-cycle instructions.
Individual interrupt flag bits are set, regardless of the
status of their corresponding enable bit or the GIE bit.
Note: Do not use the MOVFF instruction to modify
any of the interrupt control registers while
any interrupt is enabled. Doing so may
cause erratic microcontroller behavior.PIC18F1220/1320
DS39605F-page 74 © 2007 Microchip Technology Inc.
FIGURE 9-1: INTERRUPT LOGIC
TMR0IE
GIEH/GIE
GIEL/PEIE
Wake-up if in Low-Power Mode
Interrupt to CPU
Vector to Location
0008h
INT2IF
INT2IE
INT2IP
INT1IF
INT1IE
INT1IP
TMR0IF
TMR0IE
TMR0IP
INT0IF
INT0IE
RBIF
RBIE
RBIP
IPEN
TMR0IF
TMR0IP
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
RBIF
RBIE
RBIP
INT0IF
INT0IE
GIEL\PEIE
Interrupt to CPU
Vector to Location
IPEN
IPEN
0018h
INT0IF
INT0IE
INT0IF
INT0IE
ADIF
ADIE
ADIP
RCIF
RCIE
RCIP
Additional Peripheral Interrupts
ADIF
ADIE
ADIP
High Priority Interrupt Generation
Low Priority Interrupt Generation
RCIF
RCIE
RCIP
Additional Peripheral Interrupts
GIE\GIEH© 2007 Microchip Technology Inc. DS39605F-page 75
PIC18F1220/1320
9.1 INTCON Registers
The INTCON registers are readable and writable
registers, which contain various enable, priority and
flag bits.
REGISTER 9-1: INTCON REGISTER
Note: Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the global
interrupt enable bit. User software should
ensure the appropriate interrupt flag bits
are clear prior to enabling an interrupt.
This feature allows for software polling.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x
GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF
bit 7 bit 0
bit 7 GIE/GIEH: Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all high priority interrupts
0 = Disables all interrupts
bit 6 PEIE/GIEL: Peripheral Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low priority peripheral interrupts
0 = Disables all low 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
Note: A mismatch condition will continue to set this bit. Reading PORTB will end the
mismatch condition and allow the bit to be cleared.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 76 © 2007 Microchip Technology Inc.
REGISTER 9-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 Interrupt 0 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 5 INTEDG1: External Interrupt 1 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 4 INTEDG2: External Interrupt 2 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 3 Unimplemented: Read as ‘0’
bit 2 TMR0IP: TMR0 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 Unimplemented: Read as ‘0’
bit 0 RBIP: RB Port Change Interrupt Priority bit
1 = High priority
0 = Low priority
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global interrupt enable bit. User software
should ensure the appropriate interrupt flag bits are clear prior to enabling an
interrupt. This feature allows for software polling.© 2007 Microchip Technology Inc. DS39605F-page 77
PIC18F1220/1320
REGISTER 9-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 = High priority
0 = Low priority
bit 6 INT1IP: INT1 External Interrupt Priority bit
1 = High priority
0 = Low priority
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 W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global interrupt enable bit. User software
should ensure the appropriate interrupt flag bits are clear prior to enabling an
interrupt. This feature allows for software polling.PIC18F1220/1320
DS39605F-page 78 © 2007 Microchip Technology Inc.
9.2 PIR Registers
The PIR registers contain the individual flag bits for the
peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Request (Flag) registers (PIR1, PIR2).
REGISTER 9-4: PIR1: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 1
Note 1: Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the Global
Interrupt Enable bit, GIE (INTCON<7>).
2: User software should ensure the appropriate
interrupt flag bits are cleared prior to
enabling an interrupt and after servicing
that interrupt.
U-0 R/W-0 R-0 R-0 U-0 R/W-0 R/W-0 R/W-0
— ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 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 5 RCIF: EUSART Receive Interrupt Flag bit
1 = The EUSART receive buffer, RCREG, is full (cleared when RCREG is read)
0 = The EUSART receive buffer is empty
bit 4 TXIF: EUSART Transmit Interrupt Flag bit
1 = The EUSART transmit buffer, TXREG, is empty (cleared when TXREG is written)
0 = The EUSART transmit buffer is full
bit 3 Unimplemented: Read as ‘0’
bit 2 CCP1IF: CCP1 Interrupt Flag bit
Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
PWM mode:
Unused in this mode.
bit 1 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 0 TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed (must be cleared in software)
0 = TMR1 register did not overflow
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 79
PIC18F1220/1320
REGISTER 9-5: PIR2: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 2
R/W-0 U-0 U-0 R/W-0 U-0 R/W-0 R/W-0 U-0
OSCFIF — — EEIF — LVDIF TMR3IF —
bit 7 bit 0
bit 7 OSCFIF: Oscillator Fail Interrupt Flag bit
1 = System oscillator failed, clock input has changed to INTOSC (must be cleared in software)
0 = System clock operating
bit 6-5 Unimplemented: Read as ‘0’
bit 4 EEIF: Data EEPROM/Flash Write Operation Interrupt Flag bit
1 = The write operation is complete (must be cleared in software)
0 = The write operation is not complete or has not been started
bit 3 Unimplemented: Read as ‘0’
bit 2 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
bit 1 TMR3IF: TMR3 Overflow Interrupt Flag bit
1 = TMR3 register overflowed (must be cleared in software)
0 = TMR3 register did not overflow
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 80 © 2007 Microchip Technology Inc.
9.3 PIE Registers
The PIE registers contain the individual enable bits for
the peripheral interrupts. Due to the number of
peripheral interrupt sources, there are two Peripheral
Interrupt Enable registers (PIE1, PIE2). When
IPEN = 0, the PEIE bit must be set to enable any of
these peripheral interrupts.
REGISTER 9-6: PIE1: PERIPHERAL INTERRUPT ENABLE REGISTER 1
U-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0
— ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 ADIE: A/D Converter Interrupt Enable bit
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
bit 5 RCIE: EUSART Receive Interrupt Enable bit
1 = Enables the EUSART receive interrupt
0 = Disables the EUSART receive interrupt
bit 4 TXIE: EUSART Transmit Interrupt Enable bit
1 = Enables the EUSART transmit interrupt
0 = Disables the EUSART transmit interrupt
bit 3 Unimplemented: Read as ‘0’
bit 2 CCP1IE: CCP1 Interrupt Enable bit
1 = Enables the CCP1 interrupt
0 = Disables the CCP1 interrupt
bit 1 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 0 TMR1IE: TMR1 Overflow Interrupt Enable bit
1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 81
PIC18F1220/1320
REGISTER 9-7: PIE2: PERIPHERAL INTERRUPT ENABLE REGISTER 2
R/W-0 U-0 U-0 R/W-0 U-0 R/W-0 R/W-0 U-0
OSCFIE — — EEIE — LVDIE TMR3IE —
bit 7 bit 0
bit 7 OSCFIE: Oscillator Fail Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 6-5 Unimplemented: Read as ‘0’
bit 4 EEIE: Data EEPROM/Flash Write Operation Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 3 Unimplemented: Read as ‘0’
bit 2 LVDIE: Low-Voltage Detect Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 1 TMR3IE: TMR3 Overflow Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 82 © 2007 Microchip Technology Inc.
9.4 IPR Registers
The IPR registers contain the individual priority bits for
the peripheral interrupts. Due to the number of
peripheral interrupt sources, there are two Peripheral
Interrupt Priority registers (IPR1, IPR2). Using the
priority bits requires that the Interrupt Priority Enable
(IPEN) bit be set.
REGISTER 9-8: IPR1: PERIPHERAL INTERRUPT PRIORITY REGISTER 1
U-0 R/W-1 R/W-1 R/W-1 U-0 R/W-1 R/W-1 R/W-1
— ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 ADIP: A/D Converter Interrupt Priority bit
1 = High priority
0 = Low priority
bit 5 RCIP: EUSART Receive Interrupt Priority bit
1 = High priority
0 = Low priority
bit 4 TXIP: EUSART Transmit Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 Unimplemented: Read as ‘0’
bit 2 CCP1IP: CCP1 Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR2IP: TMR2 to PR2 Match Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 TMR1IP: TMR1 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 83
PIC18F1220/1320
REGISTER 9-9: IPR2: PERIPHERAL INTERRUPT PRIORITY REGISTER 2
R/W-1 U-0 U-0 R/W-1 U-0 R/W-1 R/W-1 U-0
OSCFIP — — EEIP — LVDIP TMR3IP —
bit 7 bit 0
bit 7 OSCFIP: Oscillator Fail Interrupt Priority bit
1 = High priority
0 = Low priority
bit 6-5 Unimplemented: Read as ‘0’
bit 4 EEIP: Data EEPROM/Flash Write Operation Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 Unimplemented: Read as ‘0’
bit 2 LVDIP: Low-Voltage Detect Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR3IP: TMR3 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 84 © 2007 Microchip Technology Inc.
9.5 RCON Register
The RCON register contains bits used to determine the
cause of the last Reset or wake-up from a low-power
mode. RCON also contains the bit that enables
interrupt priorities (IPEN).
REGISTER 9-10: RCON REGISTER
R/W-0 U-0 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN — — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6-5 Unimplemented: Read as ‘0’
bit 4 RI: RESET Instruction Flag bit
For details of bit operation, see Register 5-3.
bit 3 TO: Watchdog Time-out Flag bit
For details of bit operation, see Register 5-3.
bit 2 PD: Power-down Detection Flag bit
For details of bit operation, see Register 5-3.
bit 1 POR: Power-on Reset Status bit
For details of bit operation, see Register 5-3.
bit 0 BOR: Brown-out Reset Status bit
For details of bit operation, see Register 5-3.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 85
PIC18F1220/1320
9.6 INTn Pin Interrupts
External interrupts on the RB0/INT0, RB1/INT1 and
RB2/INT2 pins are edge-triggered: either rising if the
corresponding INTEDGx bit is set in the INTCON2 register,
or falling if the INTEDGx bit is clear. When a valid
edge appears on the RBx/INTx pin, the corresponding
flag bit, INTxF, is set. This interrupt can be disabled by
clearing the corresponding enable bit, INTxE. Flag bit,
INTxF, must be cleared in software in the Interrupt
Service Routine before re-enabling the interrupt. All
external interrupts (INT0, INT1 and INT2) can wake-up
the processor from low-power modes if bit INTxE was
set prior to going into low-power modes. If the Global
Interrupt Enable bit, GIE, is set, the processor will
branch to the interrupt vector following wake-up.
Interrupt priority for INT1 and INT2 is determined by the
value contained in the interrupt priority bits, INT1IP
(INTCON3<6>) and INT2IP (INTCON3<7>). There is
no priority bit associated with INT0. It is always a high
priority interrupt source.
9.7 TMR0 Interrupt
In 8-bit mode (which is the default), an overflow
(FFh → 00h) in the TMR0 register will set flag bit,
TMR0IF. In 16-bit mode, an overflow (FFFFh → 0000h)
in the TMR0H:TMR0L registers will set flag bit,
TMR0IF. The interrupt can be enabled/disabled by
setting/clearing enable bit, TMR0IE (INTCON<5>).
Interrupt priority for Timer0 is determined by the value
contained in the interrupt priority bit, TMR0IP
(INTCON2<2>). See Section 11.0 “Timer0 Module”
for further details on the Timer0 module.
9.8 PORTB Interrupt-on-Change
An input change on PORTB<7:4> sets flag bit, RBIF
(INTCON<0>). The interrupt can be enabled/disabled
by setting/clearing enable bit, RBIE (INTCON<3>).
Interrupt priority for PORTB interrupt-on-change is
determined by the value contained in the interrupt
priority bit, RBIP (INTCON2<0>).
9.9 Context Saving During Interrupts
During interrupts, the return PC address is saved on the
stack. Additionally, the WREG, Status and BSR registers
are saved on the fast return stack. If a fast return from
interrupt is not used (see Section 5.3 “Fast Register
Stack”), the user may need to save the WREG, Status
and BSR registers on entry to the Interrupt Service
Routine. Depending on the user’s application, other
registers may also need to be saved. Example 9-1
saves and restores the WREG, Status and BSR
registers during an Interrupt Service Routine.
EXAMPLE 9-1: SAVING STATUS, WREG AND BSR REGISTERS IN RAM
MOVWF W_TEMP ; W_TEMP is in virtual bank
MOVFF STATUS, STATUS_TEMP ; STATUS_TEMP located anywhere
MOVFF BSR, BSR_TEMP ; BSR_TMEP located anywhere
;
; USER ISR CODE
;
MOVFF BSR_TEMP, BSR ; Restore BSR
MOVF W_TEMP, W ; Restore WREG
MOVFF STATUS_TEMP, STATUS ; Restore STATUSPIC18F1220/1320
DS39605F-page 86 © 2007 Microchip Technology Inc.
NOTES: © 2007 Microchip Technology Inc. DS39605F-page 87
PIC18F1220/1320
10.0 I/O PORTS
Depending on the device selected and features
enabled, there are up to five ports available. Some pins
of the I/O ports are multiplexed with an alternate
function from the peripheral features on the device. In
general, when a peripheral is enabled, that pin may not
be used as a general purpose I/O pin.
Each port has three registers for its operation. These
registers are:
• TRIS register (data direction register)
• PORT register (reads the levels on the pins of the
device)
• LAT register (output latch)
The Data Latch (LATA) register is useful for readmodify-write
operations on the value that the I/O pins
are driving.
A simplified model of a generic I/O port without the
interfaces to other peripherals is shown in Figure 10-1.
FIGURE 10-1: GENERIC I/O PORT
OPERATION
10.1 PORTA, TRISA and LATA
Registers
PORTA is an 8-bit wide, bidirectional port. The corresponding
data direction register is TRISA. Setting a
TRISA bit (= 1) will make the corresponding PORTA pin
an input (i.e., put the corresponding output driver in a
high-impedance mode). Clearing a TRISA bit (= 0) will
make the corresponding PORTA pin an output (i.e., put
the contents of the output latch on the selected pin).
Reading the PORTA register reads the status of the
pins, whereas writing to it will write to the port latch.
The Data Latch register (LATA) is also memory
mapped. Read-modify-write operations on the LATA
register read and write the latched output value for
PORTA.
The RA4 pin is multiplexed with the Timer0 module
clock input to become the RA4/T0CKI pin.
The sixth pin of PORTA (MCLR/VPP/RA5) is an input
only pin. Its operation is controlled by the MCLRE
configuration bit in Configuration Register 3H
(CONFIG3H<7>). When selected as a port pin
(MCLRE = 0), it functions as a digital input only pin; as
such, it does not have TRIS or LAT bits associated with
its operation. Otherwise, it functions as the device’s
Master Clear input. In either configuration, RA5 also
functions as the programming voltage input during
programming.
Pins RA6 and RA7 are multiplexed with the main oscillator
pins; they are enabled as oscillator or I/O pins by
the selection of the main oscillator in Configuration
Register 1H (see Section 19.1 “Configuration Bits”
for details). When they are not used as port pins, RA6
and RA7 and their associated TRIS and LAT bits are
read as ‘0’.
The other PORTA pins are multiplexed with analog
inputs, the analog VREF+ and VREF- inputs and the LVD
input. The operation of pins RA3:RA0 as A/D converter
inputs is selected by clearing/setting the control bits in
the ADCON1 register (A/D Control Register 1).
The RA4/T0CKI pin is a Schmitt Trigger input and an
open-drain output. All other PORTA pins have TTL
input levels and full CMOS output drivers.
The TRISA register controls the direction of the RA
pins, even when they are being used as analog inputs.
The user must ensure the bits in the TRISA register are
maintained set when using them as analog inputs.
EXAMPLE 10-1: INITIALIZING PORTA
Data
Bus
WR LAT
WR TRIS
RD Port
Data Latch
TRIS Latch
RD TRIS
Input
Buffer
I/O pin(1)
D Q
CK
D Q
CK
EN
Q D
EN
RD LAT
or Port
Note 1: I/O pins have diode protection to VDD and VSS.
Note: On a Power-on Reset, RA5 is enabled as a
digital input only if Master Clear functionality
is disabled.
Note: On a Power-on Reset, RA3:RA0 are
configured as analog inputs and read as
‘0’. RA4 is always a digital pin.
CLRF PORTA ; Initialize PORTA by
; clearing output
; data latches
CLRF LATA ; Alternate method
; to clear output
; data latches
MOVLW 0x7F ; Configure A/D
MOVWF ADCON1 ; for digital inputs
MOVLW 0xD0 ; Value used to
; initialize data
; direction
MOVWF TRISA ; Set RA<3:0> as outputs
; RA<7:4> as inputsPIC18F1220/1320
DS39605F-page 88 © 2007 Microchip Technology Inc.
FIGURE 10-2: BLOCK DIAGRAM OF
RA3:RA0 PINS
FIGURE 10-3: BLOCK DIAGRAM OF
OSC2/CLKO/RA6 PIN
FIGURE 10-4: BLOCK DIAGRAM OF
RA4/T0CKI PIN
FIGURE 10-5: BLOCK DIAGRAM OF
OSC1/CLKI/RA7 PIN
Data
Bus
Q D
EN
P
N
WR LATA
WR TRISA
Data Latch
TRIS Latch
RD TRISA
RD PORTA
VSS
VDD
I/O pin(1)
Note 1: I/O pins have protection diodes to VDD and VSS.
Analog
Input
Mode
To A/D Converter and LVD Modules
RD LATA
or
PORTA
D Q
CK Q
D Q
CK Q
Schmitt
Trigger
Input
Buffer
Data
Bus
D Q
CK Q
Q D
EN
P
N
WR LATA
WR
Data Latch
TRIS Latch
RD
RD PORTA
VSS
VDD
I/O pin(1)
Note 1: I/O pins have protection diodes to VDD and VSS.
or
PORTA
RD LATA
RA6 Enable
ECIO or
Enable
RCIO
TRISA
D Q
CK Q
TRISA
Schmitt
Trigger
Input
Buffer
Data
Bus
WR TRISA
RD PORTA
Data Latch
TRIS Latch
Schmitt
Trigger
Input
Buffer
N
VSS
I/O pin(1)
TMR0 Clock Input
D Q
CK Q
D Q
CK Q
EN
Q D
EN
RD LATA
WR LATA
or
PORTA
Note 1: I/O pins have protection diodes to VDD and VSS.
RD TRISA
Data
Bus
D Q
CK Q
Q D
EN
P
N
WR LATA
WR
Data Latch
TRIS Latch
RD
RD PORTA
VSS
VDD
I/O pin(1)
Note 1: I/O pins have protection diodes to VDD and VSS.
or
PORTA
RD LATA
Enable
RA7
TRISA
D Q
CK Q
TRISA
RA7 Enable
To Oscillator
Schmitt
Trigger
Input
Buffer© 2007 Microchip Technology Inc. DS39605F-page 89
PIC18F1220/1320
FIGURE 10-6: MCLR/VPP/RA5 PIN BLOCK DIAGRAM
TABLE 10-1: PORTA FUNCTIONS
TABLE 10-2: SUMMARY OF REGISTERS ASSOCIATED WITH PORTA
MCLR/VPP/RA5 Data Bus
RD PORTA
RD LATA
Schmitt
Trigger
MCLRE
RD TRISA
Q D
EN
Latch
Filter
Low-Level
MCLR Detect
High-Voltage Detect
Internal MCLR
HV
Name Bit# Buffer Function
RA0/AN0 bit 0 ST Input/output port pin or analog input.
RA1/AN1/LVDIN bit 1 ST Input/output port pin, analog input or Low-Voltage Detect input.
RA2/AN2/VREF- bit 2 ST Input/output port pin, analog input or VREF-.
RA3/AN3/VREF+ bit 3 ST Input/output port pin, analog input or VREF+.
RA4/T0CKI bit 4 ST Input/output port pin or external clock input for Timer0.
Output is open-drain type.
MCLR/VPP/RA5 bit 5 ST Master Clear input or programming voltage input (if MCLR is enabled); input
only port pin or programming voltage input (if MCLR is disabled).
OSC2/CLKO/RA6 bit 6 ST OSC2, clock output or I/O pin.
OSC1/CLKI/RA7 bit 7 ST OSC1, clock input or I/O pin.
Legend: TTL = TTL input, ST = Schmitt Trigger input
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
PORTA RA7(1) RA6(1) RA5(2) RA4 RA3 RA2 RA1 RA0 xx0x 0000 uu0u 0000
LATA LATA7(1) LATA6(1) — LATA Data Output Register xx-x xxxx uu-u uuuu
TRISA TRISA7(1) TRISA6(1) — PORTA Data Direction Register 11-1 1111 11-1 1111
ADCON1 — PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0 -000 0000 -000 0000
Legend: x = unknown, u = unchanged, – = unimplemented locations read as ‘0’. Shaded cells are not used by PORTA.
Note 1: RA7:RA6 and their associated latch and data direction bits are enabled as I/O pins based on oscillator
configuration; otherwise, they are read as ‘0’.
2: RA5 is an input only if MCLR is disabled.PIC18F1220/1320
DS39605F-page 90 © 2007 Microchip Technology Inc.
10.2 PORTB, TRISB and LATB
Registers
PORTB is an 8-bit wide, bidirectional port. The corresponding
data direction register is TRISB. Setting a
TRISB bit (= 1) will make the corresponding PORTB
pin an input (i.e., put the corresponding output driver in
a high-impedance mode). Clearing a TRISB bit (= 0)
will make the corresponding PORTB pin an output (i.e.,
put the contents of the output latch on the selected pin).
The Data Latch register (LATB) is also memory
mapped. Read-modify-write operations on the LATB
register read and write the latched output value for
PORTB.
EXAMPLE 10-2: INITIALIZING PORTB
Pins RB0-RB2 are multiplexed with INT0-INT2; pins
RB0, RB1 and RB4 are multiplexed with A/D inputs;
pins RB1 and RB4 are multiplexed with EUSART; and
pins RB2, RB3, RB6 and RB7 are multiplexed with
ECCP.
Each of the PORTB pins has a weak internal pull-up. A
single control bit can turn on all the pull-ups. This is
performed by clearing bit, RBPU (INTCON2<7>). The
weak pull-up is automatically turned off when the port
pin is configured as an output. The pull-ups are
disabled on a Power-on Reset.
Four of the PORTB pins (RB7:RB4) have an interrupton-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 interrupton-change
comparison). The input pins (of RB7:RB4)
are compared with the old value latched on the last
read of PORTB. The “mismatch” outputs of RB7:RB4
are OR’ed together to generate the RB Port Change
Interrupt with Flag bit, RBIF (INTCON<0>).
This interrupt can wake the device from Sleep. The
user, in the Interrupt Service Routine, can clear the
interrupt in the following manner:
a) Any read or write of PORTB (except with the
MOVFF instruction). This will end the mismatch
condition.
b) Clear flag bit, RBIF.
A mismatch condition will continue to set flag bit, RBIF.
Reading PORTB will end the mismatch condition and
allow flag bit, RBIF, to be cleared.
The interrupt-on-change feature is recommended for
wake-up on key depression operation and operations
where PORTB is only used for the interrupt-on-change
feature. Polling of PORTB is not recommended while
using the interrupt-on-change feature.
FIGURE 10-7: BLOCK DIAGRAM OF
RB0/AN4/INT0 PIN
Note: On a Power-on Reset, RB4:RB0 are
configured as analog inputs by default and
read as ‘0’; RB7:RB5 are configured as
digital inputs.
CLRF PORTB ; Initialize PORTB by
; clearing output
; data latches
CLRF LATB ; Alternate method
; to clear output
; data latches
MOVLW 0x70 ; Set RB0, RB1, RB4 as
MOVWF ADCON1 ; digital I/O pins
MOVLW 0xCF ; Value used to
; initialize data
; direction
MOVWF TRISB ; Set RB<3:0> as inputs
; RB<5:4> as outputs
; RB<7:6> as inputs
Data Latch
RBPU(2)
P
VDD
Data Bus
WR LATB
WR TRISB
RD TRISB
RD PORTB
Weak
Pull-up
INTx
I/O
pin(1)
Schmitt Trigger
Buffer
TRIS Latch
RD LATB
or PORTB
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS
bit(s) and clear the RBPU bit (INTCON2<7>).
To A/D Converter
Analog Input Mode
TTL
Input
Buffer
D Q
CK
D Q
CK
EN
Q D
EN© 2007 Microchip Technology Inc. DS39605F-page 91
PIC18F1220/1320
FIGURE 10-8: BLOCK DIAGRAM OF RB1/AN5/TX/CK/INT1 PIN
Data Latch
RBPU(2)
P
VDD
D Q
CK
D Q
CK
Q D
EN
Data Bus
WR LATB
WR TRISB
RD TRISB
RD PORTB
Weak
Pull-up
RD PORTB
RB1 pin(1)
TRIS Latch
RD LATB
or
PORTB
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
To A/D Converter
INT1/CK Input
Analog Input
Mode
1
0
TX/CK Data
EUSART Enable
Schmitt
Trigger
Input
Buffer
TX/CK TRIS
Analog Input Mode
TTL
Input
BufferPIC18F1220/1320
DS39605F-page 92 © 2007 Microchip Technology Inc.
FIGURE 10-9: BLOCK DIAGRAM OF RB2/P1B/INT2 PIN
Data Latch
RBPU(2)
P
VDD
D Q
CK
D Q
CK
Q D
EN
Data Bus
WR LATB or
WR TRISB
RD TRISB
RD PORTB
Weak
Pull-up
RD PORTB
RB2 pin(1)
TTL
Input
Buffer
TRIS Latch
RD LATB
PORTB
P1B Data
1
0
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
P1B Enable
INT2 Input
Schmitt
Trigger
P1B/D Tri-State
Auto-Shutdown© 2007 Microchip Technology Inc. DS39605F-page 93
PIC18F1220/1320
FIGURE 10-10: BLOCK DIAGRAM OF RB3/CCP1/P1A PIN
Data Bus
WR LATB or
WR TRISB
Data Latch
TRIS Latch
RD TRISB
D Q
CK Q
Q D
EN
ECCP1/P1A Data Out
1
0
D Q
CK Q
P
N
VDD
VSS
RD PORTB
ECCP1 Input
RB3 pin PORTB
RD LATB
Schmitt
Trigger
VDD
Weak
Pull-up P
RBPU(2)
TTL Input
Buffer
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
3: ECCP1 pin output enable active for any PWM mode and Compare mode, where CCP1M<3:0> = 1000 or 1001.
4: ECCP1 pin input enable active for Capture mode only.
ECCP1(3) pin Output Enable
P1A/C Tri-State Auto-Shutdown
ECCP1(4) pin Input EnablePIC18F1220/1320
DS39605F-page 94 © 2007 Microchip Technology Inc.
FIGURE 10-11: BLOCK DIAGRAM OF RB4/AN6/RX/DT/KBI0 PIN
Data Bus
WR LATB or
WR TRISB
Data Latch
TRIS Latch
RD TRISB
D Q
CK Q
Q D
EN
DT Data
1
0
D Q
CK Q
RD PORTB
RB4 pin PORTB
RD LATB
RBPU(2)
P Weak
Pull-up
Q1
From other Q D
EN
Set RBIF
RB7:RB4 pins RD PORTB
Q3
To A/D Converter
EUSART Enabled
TTL
Input
Buffer
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
DT TRIS
Analog Input Mode
RX/DT Input
Analog Input
Mode
Schmitt
Trigger
VDD© 2007 Microchip Technology Inc. DS39605F-page 95
PIC18F1220/1320
FIGURE 10-12: BLOCK DIAGRAM OF RB5/PGM/KBI1 PIN
Data Latch
From other
RBPU(2)
P
VDD
I/O pin(1)
D Q
CK
D Q
CK
Q D
EN
Q D
EN
Data Bus
WR LATB
WR TRISB
Set RBIF
TRIS Latch
RD TRISB
RD PORTB
RB7:RB5 and
Weak
Pull-up
RD PORTB
Latch
TTL
Input
Buffer ST
Buffer
RB7:RB5 in Serial Programming Mode
Q3
Q1
RD LATB
or PORTB
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit
(INTCON2<7>).
RB4 pinsPIC18F1220/1320
DS39605F-page 96 © 2007 Microchip Technology Inc.
FIGURE 10-13: BLOCK DIAGRAM OF RB6/PGC/T1OSO/T13CKI/P1C/KBI2 PIN
Data Bus
WR LATB or
WR TRISB
Data Latch
TRIS Latch
RD TRISB
D Q
CK Q
Q D
EN
P1C Data
1
0
D Q
CK Q
RD PORTB
RB6 pin PORTB
RD LATB
Schmitt
Trigger
RBPU(2)
P Weak
Pull-up
Q1
From other Q D
EN
Set RBIF
RB7:RB4 pins RD PORTB
Q3
PGC
From RB7 pin
Timer1
Oscillator
T1OSCEN
T13CKI
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
TTL
Buffer
ECCP1 P1C/D Enable
P1B/D Tri-State Auto-Shutdown
VDD© 2007 Microchip Technology Inc. DS39605F-page 97
PIC18F1220/1320
FIGURE 10-14: BLOCK DIAGRAM OF RB7/PGD/T1OSI/P1D/KBI3 PIN
Data Bus
WR LATB or
WR TRISB
Data Latch
TRIS Latch
RD TRISB
D Q
CK Q
Q D
EN
P1D Data
1
0
D Q
CK Q
RD PORTB
RB7 pin PORTB
RD LATB
Schmitt
Trigger
To RB6 pin
RBPU(2)
P Weak
Pull-up
Q1
From other Q D
EN
Set RBIF
RB7:RB4 pins RD PORTB
Q3
PGD
ECCP1 P1C/D Enable
TTL
Input
Buffer
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (INTCON2<7>).
P1B/D Tri-State Auto-Shutdown
T1OSCEN
VDDPIC18F1220/1320
DS39605F-page 98 © 2007 Microchip Technology Inc.
TABLE 10-3: PORTB FUNCTIONS
TABLE 10-4: SUMMARY OF REGISTERS ASSOCIATED WITH PORTB
Name Bit# Buffer Function
RB0/AN4/INT0 bit 0 TTL(1)/ST(2) Input/output port pin, analog input or external interrupt
input 0.
RB1/AN5/TX/CK/INT1 bit 1 TTL(1)/ST(2) Input/output port pin, analog input, Enhanced USART
Asynchronous Transmit, Addressable USART
Synchronous Clock or external interrupt input 1.
RB2/P1B/INT2 bit 2 TTL(1)/ST(2) Input/output port pin or external interrupt input 2.
Internal software programmable weak pull-up.
RB3/CCP1/P1A bit 3 TTL(1)/ST(3) Input/output port pin or Capture1 input/Compare1 output/
PWM output. Internal software programmable weak pull-up.
RB4/AN6/RX/DT/KBI0 bit 4 TTL(1)/ST(4) Input/output port pin (with interrupt-on-change), analog input,
Enhanced USART Asynchronous Receive or Addressable
USART Synchronous Data.
RB5/PGM/KBI1 bit 5 TTL(1)/ST(5) Input/output port pin (with interrupt-on-change).
Internal software programmable weak pull-up.
Low-Voltage ICSP enable pin.
RB6/PGC/T1OSO/T13CKI/
P1C/KBI2
bit 6 TTL(1)/ST(5,6) Input/output port pin (with interrupt-on-change), Timer1/
Timer3 clock input or Timer1oscillator output.
Internal software programmable weak pull-up.
Serial programming clock.
RB7/PGD/T1OSI/P1D/KBI3 bit 7 TTL(1)/ST(5) Input/output port pin (with interrupt-on-change) or Timer1
oscillator input. Internal software programmable weak pull-up.
Serial programming data.
Legend: TTL = TTL input, ST = Schmitt Trigger input
Note 1: This buffer is a TTL input when configured as a port input pin.
2: This buffer is a Schmitt Trigger input when configured as the external interrupt.
3: This buffer is a Schmitt Trigger input when configured as the CCP1 input.
4: This buffer is a Schmitt Trigger input when used as EUSART receive input.
5: This buffer is a Schmitt Trigger input when used in Serial Programming mode.
6: This buffer is a TTL input when used as the T13CKI input.
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
PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 xxxq qqqq uuuu uuuu
LATB LATB Data Output Register xxxx xxxx uuuu uuuu
TRISB PORTB Data Direction Register 1111 1111 1111 1111
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 1111 -1-1
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 11-0 0-00
ADCON1 — PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0 -000 0000 -000 0000
Legend: x = unknown, u = unchanged, q = value depends on condition. Shaded cells are not used by PORTB.© 2007 Microchip Technology Inc. DS39605F-page 99
PIC18F1220/1320
11.0 TIMER0 MODULE
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 in 8-bit
mode and FFFFh to 0000h in 16-bit mode
• Edge select for external clock
Figure 11-1 shows a simplified block diagram of the
Timer0 module in 8-bit mode and Figure 11-2 shows a
simplified block diagram of the Timer0 module in 16-bit
mode.
The T0CON register (Register 11-1) is a readable and
writable register that controls all the aspects of Timer0,
including the prescale selection.
REGISTER 11-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
bit 7 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
0 = Internal instruction cycle clock (CLKO)
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
111 = 1:256 Prescale value
110 = 1:128 Prescale value
101 = 1:64 Prescale value
100 = 1:32 Prescale value
011 = 1:16 Prescale value
010 = 1:8 Prescale value
001 = 1:4 Prescale value
000 = 1:2 Prescale value
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 100 © 2007 Microchip Technology Inc.
FIGURE 11-1: TIMER0 BLOCK DIAGRAM IN 8-BIT MODE
FIGURE 11-2: TIMER0 BLOCK DIAGRAM IN 16-BIT MODE
Note: Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI maximum prescale.
RA4/T0CKI
T0SE
0
1
1
0
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
Clocks
TMR0
(2 TCY Delay)
Data Bus
8
PSA
T0PS2, T0PS1, T0PS0
Set Interrupt
Flag bit TMR0IF
on Overflow
3
pin
Note: Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI maximum prescale.
T0SE
0
1
1
0
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
Clocks TMR0L
(2 TCY Delay)
Data Bus<7:0>
8
PSA
T0PS2, T0PS1, T0PS0
Set Interrupt
Flag bit TMR0IF
on Overflow
3
TMR0
TMR0H
High Byte
8
8
8
Read TMR0L
Write TMR0L
RA4/T0CKI
pin© 2007 Microchip Technology Inc. DS39605F-page 101
PIC18F1220/1320
11.1 Timer0 Operation
Timer0 can operate as a timer or as a counter.
Timer mode is selected by clearing the T0CS bit. 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. In
Counter mode, Timer0 will increment either on every
rising or falling edge of pin RA4/T0CKI. The incrementing
edge is determined by the Timer0 Source Edge
Select bit (T0SE). Clearing the T0SE bit selects the
rising edge.
When an external clock input is used for Timer0, it must
meet certain requirements. The requirements ensure
the external clock can be synchronized with the internal
phase clock (TOSC). Also, there is a delay in the actual
incrementing of Timer0 after synchronization.
11.2 Prescaler
An 8-bit counter is available as a prescaler for the Timer0
module. The prescaler is not readable or writable.
The PSA and T0PS2:T0PS0 bits determine the
prescaler assignment and prescale ratio.
Clearing bit PSA will assign the prescaler to the Timer0
module. When the prescaler is assigned to the Timer0
module, prescale values of 1:2, 1:4, ..., 1:256 are
selectable.
When assigned to the Timer0 module, all instructions
writing to the TMR0 register (e.g., CLRF TMR0, MOVWF
TMR0, BSF TMR0, x, ..., etc.) will clear the prescaler
count.
11.2.1 SWITCHING PRESCALER
ASSIGNMENT
The prescaler assignment is fully under software
control (i.e., it can be changed “on-the-fly” during
program execution).
11.3 Timer0 Interrupt
The TMR0 interrupt is generated when the TMR0 register
overflows from FFh to 00h in 8-bit mode, or FFFFh
to 0000h in 16-bit mode. This overflow sets the TMR0IF
bit. The interrupt can be masked by clearing the
TMR0IE bit. The TMR0IF bit must be cleared in software
by the Timer0 module Interrupt Service Routine
before re-enabling this interrupt. The TMR0 interrupt
cannot awaken the processor from Low-Power Sleep
mode, since the timer requires clock cycles even when
T0CS is set.
11.4 16-Bit Mode Timer Reads
and Writes
TMR0H is not the high byte of the timer/counter in
16-bit mode, but is actually a buffered version of the
high byte of Timer0 (refer to Figure 11-2). The high byte
of the Timer0 counter/timer is not directly readable nor
writable. TMR0H is updated with the contents of the
high byte of Timer0 during a read of TMR0L. This provides
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.
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 all 16 bits of Timer0 to be
updated at once.
TABLE 11-1: REGISTERS ASSOCIATED WITH TIMER0
Note: Writing to TMR0 when the prescaler is
assigned to Timer0 will clear the prescaler
count, but will not change the prescaler
assignment.
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
TMR0L Timer0 Module Low Byte Register xxxx xxxx uuuu uuuu
TMR0H Timer0 Module High Byte Register 0000 0000 0000 0000
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 1111 1111
TRISA RA7(1) RA6(1) — PORTA Data Direction Register 11-1 1111 11-1 1111
Legend: x = unknown, u = unchanged, – = unimplemented locations read as ‘0’. Shaded cells are not used by Timer0.
Note 1: RA6 and RA7 are enabled as I/O pins, depending on the oscillator mode selected in Configuration Word 1H.PIC18F1220/1320
DS39605F-page 102 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 103
PIC18F1220/1320
12.0 TIMER1 MODULE
The Timer1 module timer/counter has the following
features:
• 16-bit timer/counter
(two 8-bit registers: TMR1H and TMR1L)
• Readable and writable (both registers)
• Internal or external clock select
• Interrupt-on-overflow from FFFFh to 0000h
• Reset from CCP module special event trigger
• Status of system clock operation
Figure 12-1 is a simplified block diagram of the Timer1
module.
Register 12-1 details the Timer1 Control register. This
register controls the operating mode of the Timer1
module and contains the Timer1 Oscillator Enable bit
(T1OSCEN). Timer1 can be enabled or disabled by
setting or clearing control bit, TMR1ON (T1CON<0>).
The Timer1 oscillator can be used as a secondary clock
source in power managed modes. When the T1RUN bit
is set, the Timer1 oscillator is providing the system
clock. If the Fail-Safe Clock Monitor is enabled and the
Timer1 oscillator fails while providing the system clock,
polling the T1RUN bit will indicate whether the clock is
being provided by the Timer1 oscillator or another
source.
Timer1 can also be used to provide Real-Time Clock
(RTC) functionality to applications, with only a minimal
addition of external components and code overhead.
REGISTER 12-1: T1CON: TIMER1 CONTROL REGISTER
R/W-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
bit 7 bit 0
bit 7 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 T1RUN: Timer1 System Clock Status bit
1 = System clock is derived from Timer1 oscillator
0 = System clock is derived from another source
bit 5-4 T1CKPS1:T1CKPS0: Timer1 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 3 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 RB6/PGC/T1OSO/T13CKI/P1C/KBI2 (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 W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 104 © 2007 Microchip Technology Inc.
12.1 Timer1 Operation
Timer1 can operate in one of these modes:
• As a timer
• As a synchronous counter
• As an asynchronous counter
The operating mode is determined by the clock select
bit, TMR1CS (T1CON<1>).
When TMR1CS = 0, Timer1 increments every instruction
cycle. When TMR1CS = 1, Timer1 increments on
every rising edge of the external clock input, or the
Timer1 oscillator, if enabled.
When the Timer1 oscillator is enabled (T1OSCEN is
set), the RB7/PGD/T1OSI/P1D/KBI3 and RB6/T1OSO/
T13CKI/P1C/KBI2 pins become inputs. That is, the
TRISB7:TRISB6 values are ignored and the pins read
as ‘0’.
Timer1 also has an internal “Reset input”. This Reset
can be generated by the CCP module (see
Section 15.4.4 “Special Event Trigger”).
FIGURE 12-1: TIMER1 BLOCK DIAGRAM
FIGURE 12-2: TIMER1 BLOCK DIAGRAM: 16-BIT READ/WRITE MODE
TMR1H TMR1L
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
Peripheral Clocks
FOSC/4
Internal
Clock
TMR1ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
TMR1IF
Overflow
TMR1
CLR
CCP Special Event Trigger
T1OSCEN
Enable
Oscillator(1)
T1OSC
Interrupt
Flag bit
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off. This eliminates
power drain.
T1OSI
T13CKI/T1OSO
Timer 1
TMR1L
T1OSC T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
Peripheral Clocks
T1OSCEN
Enable
Oscillator(1)
TMR1IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR1ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T13CKI/T1OSO
T1OSI
TMR1
Flag bit
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
High Byte
Data Bus<7:0>
8
TMR1H
8 8
8
Read TMR1L
Write TMR1L
CLR
CCP Special Event Trigger© 2007 Microchip Technology Inc. DS39605F-page 105
PIC18F1220/1320
12.2 Timer1 Oscillator
A crystal oscillator circuit is built-in between pins T1OSI
(input) and T1OSO (amplifier output). It is enabled by
setting control bit, T1OSCEN (T1CON<3>). The oscillator
is a low-power oscillator rated for 32 kHz crystals.
It will continue to run during all power managed modes.
The circuit for a typical LP oscillator is shown in
Figure 12-3. Table 12-1 shows the capacitor selection
for the Timer1 oscillator.
The user must provide a software time delay to ensure
proper start-up of the Timer1 oscillator.
FIGURE 12-3: EXTERNAL
COMPONENTS FOR THE
TIMER1 LP OSCILLATOR
TABLE 12-1: CAPACITOR SELECTION FOR
THE TIMER OSCILLATOR
Note: The Timer1 oscillator shares the T1OSI
and T1OSO pins with the PGD and PGC
pins used for programming and
debugging.
When using the Timer1 oscillator, In-Circuit
Serial Programming (ICSP) may not
function correctly (high voltage or low
voltage), or the In-Circuit Debugger (ICD)
may not communicate with the controller.
As a result of using either ICSP or ICD, the
Timer1 crystal may be damaged.
If ICSP or ICD operations are required, the
crystal should be disconnected from the
circuit (disconnect either lead), or installed
after programming. The oscillator loading
capacitors may remain in-circuit during
ICSP or ICD operation.
Osc Type Freq C1 C2
LP 32 kHz 22 pF(1) 22 pF(1)
Note 1: Microchip suggests this value as a starting
point in validating the oscillator circuit.
Oscillator operation should then be tested
to ensure expected performance under
all expected conditions (VDD and
temperature).
2: Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time.
3: Since each resonator/crystal has its own
characteristics, the user should consult
the resonator/crystal manufacturer for
appropriate values of external
components.
4: Capacitor values are for design guidance
only.
Note: See the Notes with Table 12-1 for additional
information about capacitor selection.
C1
C2
XTAL
PIC18FXXXX
PGD/T1OSI
PGC/T1OSO
32.768 kHz
22 pF
22 pF
PGD
PGC PIC18F1220/1320
DS39605F-page 106 © 2007 Microchip Technology Inc.
12.3 Timer1 Oscillator Layout
Considerations
The Timer1 oscillator circuit draws very little power
during operation. Due to the low-power nature of the
oscillator, it may also be sensitive to rapidly changing
signals in close proximity.
The oscillator circuit, shown in Figure 12-3, should be
located as close as possible to the microcontroller.
There should be no circuits passing within the oscillator
circuit boundaries other than VSS or VDD.
If a high-speed circuit must be located near the oscillator
(such as the CCP1 pin in output compare or PWM
mode, or the primary oscillator using the OSC2 pin), a
grounded guard ring around the oscillator circuit, as
shown in Figure 12-4, may be helpful when used on a
single sided PCB, or in addition to a ground plane.
FIGURE 12-4: OSCILLATOR CIRCUIT
WITH GROUNDED
GUARD RING
12.4 Timer1 Interrupt
The TMR1 register pair (TMR1H:TMR1L) increments
from 0000h to FFFFh and rolls over to 0000h. The
Timer1 interrupt, if enabled, is generated on overflow,
which is latched in interrupt flag bit, TMR1IF
(PIR1<0>). This interrupt can be enabled/disabled by
setting/clearing Timer1 Interrupt Enable bit, TMR1IE
(PIE1<0>).
12.5 Resetting Timer1 Using a CCP
Trigger Output
If the CCP module is configured in Compare mode
to generate a “special event trigger”
(CCP1M3:CCP1M0 = 1011), this signal will reset
Timer1 and start an A/D conversion, if the A/D module
is enabled (see Section 15.4.4 “Special Event
Trigger” for more information).
Timer1 must be configured for either Timer or Synchronized
Counter mode to take advantage of this feature.
If Timer1 is running in Asynchronous Counter mode,
this Reset operation may not work.
In the event that a write to Timer1 coincides with a
special event trigger from CCP1, the write will take
precedence.
In this mode of operation, the CCPR1H:CCPR1L register
pair effectively becomes the period register for
Timer1.
12.6 Timer1 16-Bit Read/Write Mode
Timer1 can be configured for 16-bit reads and writes
(see Figure 12-2). When the RD16 control bit
(T1CON<7>) 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.
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.
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.
RA1
RA4
RB0
MCLR
VSS
RA2
RA3
Note: Not drawn to scale.
RB2
OSC1
RB5
OSC2
VDD
RB7
RB6
C2
X1
C3
C4
X2
C5
C1
Note: The special event triggers from the CCP1
module will not set interrupt flag bit,
TMR1IF (PIR1<0>). © 2007 Microchip Technology Inc. DS39605F-page 107
PIC18F1220/1320
12.7 Using Timer1 as a
Real-Time Clock
Adding an external LP oscillator to Timer1 (such as the
one described in Section 12.2 “Timer1 Oscillator”,
above), gives users the option to include RTC functionality
to their applications. This is accomplished with an
inexpensive watch crystal to provide an accurate time
base and several lines of application code to calculate
the time. When operating in Sleep mode and using a
battery or supercapacitor as a power source, it can
completely eliminate the need for a separate RTC
device and battery backup.
The application code routine, RTCisr, shown in
Example 12-1, demonstrates a simple method to
increment a counter at one-second intervals using an
Interrupt Service Routine. Incrementing the TMR1 register
pair to overflow, triggers the interrupt and calls the
routine, which increments the seconds counter by one;
additional counters for minutes and hours are
incremented as the previous counter overflow.
Since the register pair is 16 bits wide, counting up to
overflow the register directly from a 32.768 kHz clock
would take 2 seconds. To force the overflow at the
required one-second intervals, it is necessary to preload
it; the simplest method is to set the MSb of TMR1H
with a BSF instruction. Note that the TMR1L register is
never preloaded or altered; doing so may introduce
cumulative error over many cycles.
For this method to be accurate, Timer1 must operate in
Asynchronous mode and the Timer1 overflow interrupt
must be enabled (PIE1<0> = 1), as shown in the
routine, RTCinit. The Timer1 oscillator must also be
enabled and running at all times.
EXAMPLE 12-1: IMPLEMENTING A REAL-TIME CLOCK USING A TIMER1 INTERRUPT SERVICE
RTCinit
MOVLW 0x80 ; Preload TMR1 register pair
MOVWF TMR1H ; for 1 second overflow
CLRF TMR1L
MOVLW b’00001111’ ; Configure for external clock,
MOVWF T1OSC ; Asynchronous operation, external oscillator
CLRF secs ; Initialize timekeeping registers
CLRF mins ;
MOVLW .12
MOVWF hours
BSF PIE1, TMR1IE ; Enable Timer1 interrupt
RETURN
RTCisr
BSF TMR1H, 7 ; Preload for 1 sec overflow
BCF PIR1, TMR1IF ; Clear interrupt flag
INCF secs, F ; Increment seconds
MOVLW .59 ; 60 seconds elapsed?
CPFSGT secs
RETURN ; No, done
CLRF secs ; Clear seconds
INCF mins, F ; Increment minutes
MOVLW .59 ; 60 minutes elapsed?
CPFSGT mins
RETURN ; No, done
CLRF mins ; clear minutes
INCF hours, F ; Increment hours
MOVLW .23 ; 24 hours elapsed?
CPFSGT hours
RETURN ; No, done
MOVLW .01 ; Reset hours to 1
MOVWF hours
RETURN ; DonePIC18F1220/1320
DS39605F-page 108 © 2007 Microchip Technology Inc.
TABLE 12-2: REGISTERS ASSOCIATED WITH TIMER1 AS A TIMER/COUNTER
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
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 TMR1 Register xxxx xxxx uuuu uuuu
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0000 0000 u0uu uuuu
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’. Shaded cells are not used by the Timer1 module.© 2007 Microchip Technology Inc. DS39605F-page 109
PIC18F1220/1320
13.0 TIMER2 MODULE
The Timer2 module timer has the following features:
• 8-bit timer (TMR2 register)
• 8-bit period register (PR2)
• Readable and writable (both registers)
• Software programmable prescaler (1:1, 1:4, 1:16)
• Software programmable postscaler (1:1 to 1:16)
• Interrupt on TMR2 match with PR2
Timer2 has a control register shown in Register 13-1.
TMR2 can be shut off by clearing control bit, TMR2ON
(T2CON<2>), to minimize power consumption.
Figure 13-1 is a simplified block diagram of the Timer2
module. Register 13-1 shows the Timer2 Control
register. The prescaler and postscaler selection of
Timer2 are controlled by this register.
13.1 Timer2 Operation
Timer2 can be used as the PWM time base for the
PWM mode of the CCP module. The TMR2 register is
readable and writable and is cleared on any device
Reset. The input clock (FOSC/4) has a prescale option
of 1:1, 1:4 or 1:16, selected by control bits,
T2CKPS1:T2CKPS0 (T2CON<1:0>). The match output
of TMR2 goes through a 4-bit postscaler (which
gives a 1:1 to 1:16 scaling inclusive) to generate a
TMR2 interrupt (latched in flag bit, TMR2IF (PIR1<1>)).
The prescaler and postscaler counters are cleared
when any of the following occurs:
• A write to the TMR2 register
• A write to the T2CON register
• Any device Reset (Power-on Reset, MCLR Reset,
Watchdog Timer Reset or Brown-out Reset)
TMR2 is not cleared when T2CON is written.
REGISTER 13-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 W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 110 © 2007 Microchip Technology Inc.
13.2 Timer2 Interrupt
The Timer2 module has an 8-bit period register, PR2.
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 PR2 register is
initialized to FFh upon Reset.
13.3 Output of TMR2
The output of TMR2 (before the postscaler) is fed to the
Synchronous Serial Port module, which optionally uses
it to generate the shift clock.
FIGURE 13-1: TIMER2 BLOCK DIAGRAM
TABLE 13-1: REGISTERS ASSOCIATED WITH TIMER2 AS A TIMER/COUNTER
Comparator
TMR2 Sets Flag
TMR2
Output(1)
Reset
Postscaler
Prescaler
PR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
EQ
4
bit TMR2IF
TOUTPS3:TOUTPS0
T2CKPS1:T2CKPS0
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
TMR2 Timer2 Module Register 0000 0000 0000 0000
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
PR2 Timer2 Period Register 1111 1111 1111 1111
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’. Shaded cells are not used by the Timer2 module.© 2007 Microchip Technology Inc. DS39605F-page 111
PIC18F1220/1320
14.0 TIMER3 MODULE
The Timer3 module timer/counter has the following
features:
• 16-bit timer/counter
(two 8-bit registers; TMR3H and TMR3L)
• Readable and writable (both registers)
• Internal or external clock select
• Interrupt-on-overflow from FFFFh to 0000h
• Reset from CCP module trigger
Figure 14-1 is a simplified block diagram of the Timer3
module.
Register 14-1 shows the Timer3 Control register. This
register controls the operating mode of the Timer3
module and sets the CCP clock source.
Register 12-1 shows the Timer1 Control register. This
register controls the operating mode of the Timer1
module, as well as contains the Timer1 Oscillator
Enable bit (T1OSCEN), which can be a clock source for
Timer3.
REGISTER 14-1: T3CON: TIMER3 CONTROL REGISTER
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 — T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
bit 7 bit 0
bit 7 RD16: 16-bit Read/Write Mode Enable bit
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 Unimplemented: Read as ‘0’
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 3 T3CCP1: Timer3 and Timer1 to CCP1 Enable bits
1 = Timer3 is the clock source for compare/capture CCP module
0 = Timer1 is the clock source for compare/capture CCP module
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 Timer1 oscillator or T13CKI
(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 W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 112 © 2007 Microchip Technology Inc.
14.1 Timer3 Operation
Timer3 can operate in one of these modes:
• As a timer
• As a synchronous counter
• As an asynchronous counter
The operating mode is determined by the clock select
bit, TMR3CS (T3CON<1>).
When TMR3CS = 0, Timer3 increments every instruction
cycle. When TMR3CS = 1, Timer3 increments on
every rising edge of the Timer1 external clock input or
the Timer1 oscillator, if enabled.
When the Timer1 oscillator is enabled (T1OSCEN is
set), the RB7/PGD/T1OSI/P1D/KBI3 and RB6/PGC/
T1OSO/T13CKI/P1C/KBI2 pins become inputs. That
is, the TRISB7:TRISB6 value is ignored and the pins
are read as ‘0’.
Timer3 also has an internal “Reset input”. This Reset
can be generated by the CCP module (see
Section 15.4.4 “Special Event Trigger”).
FIGURE 14-1: TIMER3 BLOCK DIAGRAM
FIGURE 14-2: TIMER3 BLOCK DIAGRAM CONFIGURED IN 16-BIT READ/WRITE MODE
TMR3H TMR3L
T1OSC
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0
Peripheral Clocks
T1OSCEN
Enable
Oscillator(1)
TMR3IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR3ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T1OSO/
T1OSI
Flag bit
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
T13CKI
CLR
CCP Special Event Trigger
T3CCPx
Timer3
TMR3L
T1OSC
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0
Peripheral
T1OSCEN
Enable
Oscillator(1)
FOSC/4
Internal
Clock
TMR3ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T1OSO/
T1OSI
TMR3
T13CKI
CLR
CCP Special Event Trigger
T3CCPx
To Timer1 Clock Input
Note 1: When the T1OSCEN bit is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
High Byte
Data Bus<7:0>
8
TMR3H
8 8
8
Read TMR3L
Write TMR3L
Set TMR3IF Flag bit
on Overflow
Clocks© 2007 Microchip Technology Inc. DS39605F-page 113
PIC18F1220/1320
14.2 Timer1 Oscillator
The Timer1 oscillator may be used as the clock source
for Timer3. The Timer1 oscillator is enabled by setting
the T1OSCEN (T1CON<3>) bit. The oscillator is a lowpower
oscillator rated for 32 kHz crystals. See
Section 12.2 “Timer1 Oscillator” for further details.
14.3 Timer3 Interrupt
The TMR3 register pair (TMR3H:TMR3L) increments
from 0000h to FFFFh and rolls over to 0000h. The
TMR3 interrupt, if enabled, is generated on overflow,
which is latched in interrupt flag bit, TMR3IF
(PIR2<1>). This interrupt can be enabled/disabled by
setting/clearing TMR3 Interrupt Enable bit, TMR3IE
(PIE2<1>).
14.4 Resetting Timer3 Using a CCP
Trigger Output
If the CCP module is configured in Compare mode
to generate a “special event trigger”
(CCP1M3:CCP1M0 = 1011), this signal will reset
Timer3. See Section 15.4.4 “Special Event Trigger”
for more information.
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 CCP1, the write will take precedence. In this mode
of operation, the CCPR1H:CCPR1L register pair
effectively becomes the period register for Timer3.
TABLE 14-1: REGISTERS ASSOCIATED WITH TIMER3 AS A TIMER/COUNTER
Note: The special event triggers from the CCP
module will not set interrupt flag bit,
TMR3IF (PIR1<0>).
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
PIR2 OSCFIF — — EEIF — LVDIF TMR3IF — 0--0 -00- 0--0 -00-
PIE2 OSCFIE — — EEIE — LVDIE TMR3IE — 0--0 -00- 0--0 -00-
IPR2 OSCFIP — — EEIP — LVDIP TMR3IP — 1--1 -11- 1--1 -11-
TMR3L Holding Register for the Least Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
TMR3H Holding Register for the Most Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0000 0000 u0uu uuuu
T3CON RD16 — T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0-00 0000 u-uu uuuu
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’. Shaded cells are not used by the Timer3 module.PIC18F1220/1320
DS39605F-page 114 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 115
PIC18F1220/1320
15.0 ENHANCED CAPTURE/
COMPARE/PWM (ECCP)
MODULE
The Enhanced CCP module is implemented as a
standard CCP module with Enhanced PWM
capabilities. These capabilities allow for 2 or 4 output
channels, user-selectable polarity, dead-band control
and automatic shutdown and restart and are discussed
in detail in Section 15.5 “Enhanced PWM Mode”.
The control register for CCP1 is shown in Register 15-1.
In addition to the expanded functions of the CCP1CON
register, the ECCP module has two additional
registers associated with Enhanced PWM operation
and auto-shutdown features:
• PWM1CON
• ECCPAS
REGISTER 15-1: CCP1CON REGISTER FOR ENHANCED CCP OPERATION
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0
bit 7 bit 0
bit 7-6 P1M1:P1M0: PWM Output Configuration bits
If CCP1M<3:2> = 00, 01, 10:
xx = P1A assigned as Capture/Compare input; P1B, P1C, P1D assigned as port pins
If CCP1M<3:2> = 11:
00 = Single output; P1A modulated; P1B, P1C, P1D assigned as port pins
01 = Full-bridge output forward; P1D modulated; P1A active; P1B, P1C inactive
10 = Half-bridge output; P1A, P1B modulated with dead-band control; P1C, P1D assigned as
port pins
11 = Full-bridge output reverse; P1B modulated; P1C active; P1A, P1D inactive
bit 5-4 DC1B1:DC1B0: PWM Duty Cycle Least Significant bits
Capture mode:
Unused.
Compare mode:
Unused.
PWM mode:
These bits are the two LSbs of the PWM duty cycle. The eight MSbs are found in CCPR1L.
bit 3-0 CCP1M3:CCP1M0: ECCP1 Mode Select bits
0000 = Capture/Compare/PWM off (resets ECCP module)
0001 = Unused (reserved)
0010 = Compare mode, toggle output on match (ECCP1IF bit is set)
0011 = Unused (reserved)
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode, set output on match (ECCP1IF bit is set)
1001 = Compare mode, clear output on match (ECCP1IF bit is set)
1010 = Compare mode, generate software interrupt on match (ECCP1IF bit is set,
ECCP1 pin returns to port pin operation)
1011 = Compare mode, trigger special event (ECCP1IF bit is set; ECCP resets TMR1 or
TMR3 and starts an A/D conversion if the A/D module is enabled)
1100 = PWM mode; P1A, P1C active-high; P1B, P1D active-high
1101 = PWM mode; P1A, P1C active-high; P1B, P1D active-low
1110 = PWM mode; P1A, P1C active-low; P1B, P1D active-high
1111 = PWM mode; P1A, P1C active-low; P1B, P1D active-low
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 116 © 2007 Microchip Technology Inc.
15.1 ECCP Outputs
The Enhanced CCP module may have up to four
outputs, depending on the selected operating mode.
These outputs, designated P1A through P1D, are
multiplexed with I/O pins on PORTB. The pin
assignments are summarized in Table 15-1.
To configure I/O pins as PWM outputs, the proper PWM
mode must be selected by setting the P1Mn and
CCP1Mn bits (CCP1CON<7:6> and <3:0>,
respectively). The appropriate TRISB direction bits for
the port pins must also be set as outputs.
TABLE 15-1: PIN ASSIGNMENTS FOR VARIOUS ECCP MODES
15.2 CCP Module
Capture/Compare/PWM Register 1 (CCPR1) is comprised
of two 8-bit registers: CCPR1L (low byte) and
CCPR1H (high byte). The CCP1CON register controls
the operation of CCP1. All are readable and writable.
TABLE 15-2: CCP MODE – TIMER
RESOURCE
15.3 Capture Mode
In Capture mode, CCPR1H:CCPR1L captures the 16-bit
value of the TMR1 or TMR3 registers when an event
occurs on pin RB3/CCP1/P1A. An event is defined as
one of the following:
• every falling edge
• every rising edge
• every 4th rising edge
• every 16th rising edge
The event is selected by control bits, CCP1M3:CCP1M0
(CCP1CON<3:0>). When a capture is made, the interrupt
request flag bit, CCP1IF (PIR1<2>), is set; it must
be cleared in software. If another capture occurs before
the value in register CCPR1 is read, the old captured
value is overwritten by the new captured value.
15.3.1 CCP PIN CONFIGURATION
In Capture mode, the RB3/CCP1/P1A pin should be
configured as an input by setting the TRISB<3> bit.
15.3.2 TIMER1/TIMER3 MODE SELECTION
The timers that are to be used with the capture feature
(either Timer1 and/or Timer3) must be running in Timer
mode or Synchronized Counter mode. In Asynchronous
Counter mode, the capture operation may not
work. The timer to be used with the CCP module is
selected in the T3CON register.
15.3.3 SOFTWARE INTERRUPT
When the Capture mode is changed, a false capture
interrupt may be generated. The user should keep bit,
CCP1IE (PIE1<2>), clear while changing capture
modes to avoid false interrupts and should clear the
flag bit, CCP1IF, following any such change in
operating mode.
ECCP Mode CCP1CON
Configuration RB3 RB2 RB6 RB7
Compatible CCP 00xx 11xx CCP1 RB2/INT2 RB6/PGC/T1OSO/T13CKI/KBI2 RB7/PGD/T1OSI/KBI3
Dual PWM 10xx 11xx P1A P1B RB6/PGC/T1OSO/T13CKI/KBI2 RB7/PGD/T1OSI/KBI3
Quad PWM x1xx 11xx P1A P1B P1C P1D
Legend: x = Don’t care. Shaded cells indicate pin assignments not used by ECCP in a given mode.
Note 1: TRIS register values must be configured appropriately.
CCP Mode Timer Resource
Capture
Compare
PWM
Timer1 or Timer3
Timer1 or Timer3
Timer2
Note: If the RB3/CCP1/P1A is configured as an
output, a write to the port can cause a
capture condition. © 2007 Microchip Technology Inc. DS39605F-page 117
PIC18F1220/1320
15.3.4 CCP PRESCALER
There are four prescaler settings, specified by bits
CCP1M3:CCP1M0. Whenever the CCP module is
turned off or the CCP module is not in Capture mode,
the prescaler counter is cleared. This means that any
Reset will clear the prescaler counter.
Switching from one capture prescaler to another may
generate an interrupt. Also, the prescaler counter will
not be cleared; therefore, the first capture may be from
a non-zero prescaler. Example 15-1 shows the
recommended method for switching between capture
prescalers. This example also clears the prescaler
counter and will not generate the “false” interrupt.
EXAMPLE 15-1: CHANGING BETWEEN
CAPTURE PRESCALERS
FIGURE 15-1: CAPTURE MODE OPERATION BLOCK DIAGRAM
15.4 Compare Mode
In Compare mode, the 16-bit CCPR1 register value is
constantly compared against either the TMR1 register
pair value, or the TMR3 register pair value. When a
match occurs, the RB3/CCP1/P1A pin:
• Is driven high
• Is driven low
• Toggles output (high-to-low or low-to-high)
• Remains unchanged (interrupt only)
The action on the pin is based on the value of control
bits, CCP1M3:CCP1M0. At the same time, interrupt
flag bit, CCP1IF, is set.
15.4.1 CCP PIN CONFIGURATION
The user must configure the RB3/CCP1/P1A pin as an
output by clearing the TRISB<3> bit.
15.4.2 TIMER1/TIMER3 MODE SELECTION
Timer1 and/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.
15.4.3 SOFTWARE INTERRUPT MODE
When generate software interrupt is chosen, the RB3/
CCP1/P1A pin is not affected. CCP1IF is set and an
interrupt is generated (if enabled).
15.4.4 SPECIAL EVENT TRIGGER
In this mode, an internal hardware trigger is generated,
which may be used to initiate an action.
The special event trigger output of CCP1 resets the
TMR1 register pair. This allows the CCPR1 register to
effectively be a 16-bit programmable period register for
Timer1.
The special event trigger also sets the GO/DONE bit
(ADCON0<1>). This starts a conversion of the
currently selected A/D channel if the A/D is on.
CLRF CCP1CON ; Turn CCP module off
MOVLW NEW_CAPT_PS ; Load WREG with the
; new prescaler mode
; value and CCP ON
MOVWF CCP1CON ; Load CCP1CON with
; this value
CCPR1H CCPR1L
TMR1H TMR1L
Set Flag bit CCP1IF
TMR3
Enable
Q’s
CCP1CON<3:0>
CCP1 pin
Prescaler
÷ 1, 4, 16
and
Edge Detect
TMR3H TMR3L
TMR1
Enable
T3CCP1
T3CCP1
Note: Clearing the CCP1CON register will force
the RB3/CCP1/P1A compare output latch
to the default low level. This is not the
PORTB I/O data latch.PIC18F1220/1320
DS39605F-page 118 © 2007 Microchip Technology Inc.
FIGURE 15-2: COMPARE MODE OPERATION BLOCK DIAGRAM
TABLE 15-3: REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, TIMER1 AND TIMER3
CCPR1H CCPR1L
TMR1H TMR1L
Comparator
Q S
R
Output
Logic
Special Event Trigger
Set Flag bit CCP1IF
RB3/CCP1/P1A pin Match
TRISB<3>
CCP1CON<3:0>
Mode Select
Output Enable
Special Event Trigger will:
Reset Timer1 or Timer3, but does not set Timer1 or Timer3 interrupt flag bit
and set bit GO/DONE (ADCON0<2>), which starts an A/D conversion.
TMR3H TMR3L
T3CCP1 0 1
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
TRISB PORTB 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 TMR1 Register xxxx xxxx uuuu uuuu
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0000 0000 uuuu uuuu
CCPR1L Capture/Compare/PWM Register 1 (LSB) xxxx xxxx uuuu uuuu
CCPR1H Capture/Compare/PWM Register 1 (MSB) xxxx xxxx uuuu uuuu
CCP1CON P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 0000 0000 0000 0000
TMR3L Holding Register for the Least Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
TMR3H Holding Register for the Most Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
T3CON RD16 — T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0-00 0000 u-uu uuuu
ADCON0 VCFG1 VCFG0 — CHS2 CHS1 CHS0 GO/DONE ADON 00-0 0000 00-0 0000
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’. Shaded cells are not used by Capture and Timer1.© 2007 Microchip Technology Inc. DS39605F-page 119
PIC18F1220/1320
15.5 Enhanced PWM Mode
The Enhanced PWM Mode provides additional PWM
output options for a broader range of control applications.
The module is an upwardly compatible version of
the standard CCP module and offers up to four outputs,
designated P1A through P1D. Users are also able to
select the polarity of the signal (either active-high or
active-low). The module’s output mode and polarity are
configured by setting the P1M1:P1M0 and
CCP1M3CCP1M0 bits of the CCP1CON register
(CCP1CON<7:6> and CCP1CON<3:0>, respectively).
Figure 15-3 shows a simplified block diagram of PWM
operation. All control registers are double-buffered and
are loaded at the beginning of a new PWM cycle (the
period boundary when Timer2 resets) in order to prevent
glitches on any of the outputs. The exception is the PWM
Delay register, ECCP1DEL, which is loaded at either the
duty cycle boundary or the boundary period (whichever
comes first). Because of the buffering, the module waits
until the assigned timer resets instead of starting immediately.
This means that Enhanced PWM waveforms do
not exactly match the standard PWM waveforms, but
are instead offset by one full instruction cycle (4 TOSC).
As before, the user must manually configure the
appropriate TRIS bits for output.
15.5.1 PWM PERIOD
The PWM period is specified by writing to the PR2
register. The PWM period can be calculated using the
equation:
EQUATION 15-1: PWM PERIOD
PWM frequency is defined as 1/[PWM period]. When
TMR2 is equal to PR2, the following three events occur
on the next increment cycle:
• TMR2 is cleared
• The CCP1 pin is set (if PWM duty cycle = 0%, the
CCP1 pin will not be set)
• The PWM duty cycle is copied from CCPR1L into
CCPR1H
15.5.2 PWM DUTY CYCLE
The PWM duty cycle is specified by writing to the
CCPR1L register and to the CCP1CON<5:4> bits. Up
to 10-bit resolution is available. The CCPR1L contains
the eight MSbs and the CCP1CON<5:4> contains the
two LSbs. This 10-bit value is represented by
CCPR1L:CCP1CON<5:4>. The PWM duty cycle is
calculated by the equation:
EQUATION 15-2: PWM DUTY CYCLE
CCPR1L and CCP1CON<5:4> can be written to at any
time, but the duty cycle value is not copied into
CCPR1H until a match between PR2 and TMR2 occurs
(i.e., the period is complete). In PWM mode, CCPR1H
is a read-only register.
The CCPR1H register and a 2-bit internal latch are
used to double-buffer the PWM duty cycle. This
double-buffering is essential for glitchless PWM
operation. When the CCPR1H and 2-bit latch match
TMR2, concatenated with an internal 2-bit Q clock or
two bits of the TMR2 prescaler, the CCP1 pin is
cleared. The maximum PWM resolution (bits) for a
given PWM frequency is given by the equation:
EQUATION 15-3: PWM RESOLUTION
15.5.3 PWM OUTPUT CONFIGURATIONS
The P1M1:P1M0 bits in the CCP1CON register allow
one of four configurations:
• Single Output
• Half-Bridge Output
• Full-Bridge Output, Forward mode
• Full-Bridge Output, Reverse mode
The Single Output mode is the Standard PWM mode
discussed in Section 15.5 “Enhanced PWM Mode”.
The Half-Bridge and Full-Bridge Output modes are
covered in detail in the sections that follow.
The general relationship of the outputs in all
configurations is summarized in Figure 15-4.
TABLE 15-4: EXAMPLE PWM FREQUENCIES AND RESOLUTIONS AT 40 MHz
Note: The Timer2 postscaler (see Section 13.0
“Timer2 Module”) is not used in the
determination of the PWM frequency. The
postscaler could be used to have a servo
update rate at a different frequency than
the PWM output.
PWM Period = [(PR2) + 1] • 4 • TOSC •
(TMR2 Prescale Value)
Note: If the PWM duty cycle value is longer than
the PWM period, the CCP1 pin will not be
cleared.
PWM Duty Cycle = (CCPR1L:CCP1CON<5:4>) •
TOSC • (TMR2 Prescale Value)
( ) PWM Resolution (max) =
FOSC
FPWM
log
log(2)
bits
PWM Frequency 2.44 kHz 9.77 kHz 39.06 kHz 156.25 kHz 312.50 kHz 416.67 kHz
Timer Prescaler (1, 4, 16) 16 4 1 1 1 1
PR2 Value FFh FFh FFh 3Fh 1Fh 17h
Maximum Resolution (bits) 10 10 10 8 7 6.58PIC18F1220/1320
DS39605F-page 120 © 2007 Microchip Technology Inc.
FIGURE 15-3: SIMPLIFIED BLOCK DIAGRAM OF THE ENHANCED PWM MODULE
FIGURE 15-4: PWM OUTPUT RELATIONSHIPS (ACTIVE-HIGH STATE)
CCPR1L
CCPR1H (Slave)
Comparator
TMR2
Comparator
PR2
(Note 1)
R Q
S
Duty Cycle Registers
CCP1CON<5:4>
Clear Timer,
set CCP1 pin and
latch D.C.
Note: The 8-bit TMR2 register is concatenated with the 2-bit internal Q clock, or 2 bits of the prescaler to create the
10-bit time base.
TRISB<3>
RB3/CCP1/P1A
TRISB<2>
RB2/P1B/INT2
TRISB<6>
RB6/PGC/T1OSO/T13CKI/
TRISB<7>
RB7/PGD/T1OSI/P1D/KBI3
Output
Controller
P1M1<1:0>
2
CCP1M<3:0>
4
CCP1DEL
CCP1/P1A
P1B
P1C
P1D
P1C/KBI2
0
Period
00
10
01
11
SIGNAL
PR2+1
CCP1CON<7:6>
P1A Modulated
P1A Modulated
P1B Modulated
P1A Active
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
P1B Modulated
P1C Active
P1D Inactive
Duty
Cycle
(Single Output)
(Half-Bridge)
(Full-Bridge,
Forward)
(Full-Bridge,
Reverse)
Delay(1) Delay(1)© 2007 Microchip Technology Inc. DS39605F-page 121
PIC18F1220/1320
FIGURE 15-5: PWM OUTPUT RELATIONSHIPS (ACTIVE-LOW STATE)
0
Period
00
10
01
11
SIGNAL
PR2+1
CCP1CON<7:6>
P1A Modulated
P1A Modulated
P1B Modulated
P1A Active
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
P1B Modulated
P1C Active
P1D Inactive
Duty
Cycle
(Single Output)
(Half-Bridge)
(Full-Bridge,
Forward)
(Full-Bridge,
Reverse)
Delay(1) Delay(1)
Relationships:
• Period = 4 * TOSC * (PR2 + 1) * (TMR2 Prescale Value)
• Duty Cycle = TOSC * (CCPR1L<7:0>:CCP1CON<5:4>) * (TMR2 Prescale Value)
• Delay = 4 * TOSC * (PWM1CON<6:0>)
Note 1: Dead-band delay is programmed using the PWM1CON register (Section 15.5.6 “Programmable Dead-Band
Delay”).PIC18F1220/1320
DS39605F-page 122 © 2007 Microchip Technology Inc.
15.5.4 HALF-BRIDGE MODE
In the Half-Bridge Output mode, two pins are used as
outputs to drive push-pull loads. The PWM output
signal is output on the RB3/CCP1/P1A pin, while the
complementary PWM output signal is output on the
RB2/P1B/INT2 pin (Figure 15-6). This mode can be
used for half-bridge applications, as shown in
Figure 15-7, or for full-bridge applications, where four
power switches are being modulated with two PWM
signals.
In Half-Bridge Output mode, the programmable deadband
delay can be used to prevent shoot-through
current in half-bridge power devices. The value of bits,
PDC6:PDC0 (PWM1CON<6:0>), sets the number of
instruction cycles before the output is driven active. If the
value is greater than the duty cycle, the corresponding
output remains inactive during the entire cycle. See
Section 15.5.6 “Programmable Dead-Band Delay”
for more details of the dead-band delay operations.
The TRISB<3> and TRISB<2> bits must be cleared to
configure P1A and P1B as outputs.
FIGURE 15-6: HALF-BRIDGE PWM
OUTPUT (ACTIVE-HIGH)
FIGURE 15-7: EXAMPLES OF HALF-BRIDGE OUTPUT MODE APPLICATIONS
Period
Duty Cycle
td
td
(1)
P1A
P1B
td = Dead-Band Delay
Period
(1) (1)
Note 1: At this time, the TMR2 register is equal to the
PR2 register.
PIC18F1220/1320
P1A
P1B
FET
Driver
FET
Driver
Load
+
V
-
+
V
-
FET
Driver
FET
Driver
V+
V-
Load
FET
Driver
FET
Driver
PIC18F1220/1320
P1A
P1B
Standard Half-Bridge Circuit (“Push-Pull”)
Half-Bridge Output Driving a Full-Bridge Circuit© 2007 Microchip Technology Inc. DS39605F-page 123
PIC18F1220/1320
15.5.5 FULL-BRIDGE MODE
In Full-Bridge Output mode, four pins are used as
outputs; however, only two outputs are active at a time.
In the Forward mode, pin RB3/CCP1/P1A is continuously
active and pin RB7/PGD/T1OSI/P1D/KBI3 is
modulated. In the Reverse mode, pin RB6/PGC/
T1OSO/T13CKI/P1C/KBI2 is continuously active and
pin RB2/P1B/INT2 is modulated. These are illustrated
in Figure 15-8.
The TRISB<3:2> and TRISB<7:6> bits must be cleared
to make the P1A, P1B, P1C and P1D pins output.
FIGURE 15-8: FULL-BRIDGE PWM OUTPUT (ACTIVE-HIGH)
Period
Duty Cycle
P1A
P1B
P1C
P1D
Forward Mode
(1)
Period
Duty Cycle
P1A
P1C
P1D
P1B
Reverse Mode
(1)
(1) (1)
Note 1: At this time, the TMR2 register is equal to the PR2 register.PIC18F1220/1320
DS39605F-page 124 © 2007 Microchip Technology Inc.
FIGURE 15-9: EXAMPLE OF FULL-BRIDGE APPLICATION
15.5.5.1 Direction Change in Full-Bridge Mode
In the Full-Bridge Output mode, the P1M1 bit in the
CCP1CON register allows the user to control the
Forward/Reverse direction. When the application
firmware changes this direction control bit, the module
will assume the new direction on the next PWM cycle.
Just before the end of the current PWM period, the
modulated outputs (P1B and P1D) are placed in their
inactive state, while the unmodulated outputs (P1A and
P1C) are switched to drive in the opposite direction.
This occurs in a time interval of (4 TOSC * (Timer2
Prescale Value) before the next PWM period begins.
The Timer2 prescaler will be either 1,4 or 16, depending
on the value of the T2CKPS bit (T2CON<1:0>).
During the interval from the switch of the unmodulated
outputs to the beginning of the next period, the
modulated outputs (P1B and P1D) remain inactive.
This relationship is shown in Figure 15-10.
Note that in the Full-Bridge Output mode, the ECCP
module does not provide any dead-band delay. In
general, since only one output is modulated at all times,
dead-band delay is not required. However, there is a
situation where a dead-band delay might be required.
This situation occurs when both of the following
conditions are true:
1. The direction of the PWM output changes when
the duty cycle of the output is at or near 100%.
2. The turn-off time of the power switch, including
the power device and driver circuit, is greater
than the turn-on time.
Figure 15-11 shows an example where the PWM direction
changes from forward to reverse, at a near 100%
duty cycle. At time t1, the output P1A and P1D become
inactive, while output P1C becomes active. In this
example, since the turn-off time of the power devices is
longer than the turn-on time, a shoot-through current
may flow through power devices QC and QD (see
Figure 15-9) for the duration of ‘t’. The same phenomenon
will occur to power devices QA and QB for PWM
direction change from reverse to forward.
If changing PWM direction at high duty cycle is required
for an application, one of the following requirements
must be met:
1. Reduce PWM for a PWM period before
changing directions.
2. Use switch drivers that can drive the switches off
faster than they can drive them on.
Other options to prevent shoot-through current may
exist.
PIC18F1220/1320
P1A
P1C
FET
Driver
FET
Driver
V+
V-
Load
FET
Driver
FET
Driver
P1B
P1D
QA
QB QD
QC© 2007 Microchip Technology Inc. DS39605F-page 125
PIC18F1220/1320
FIGURE 15-10: PWM DIRECTION CHANGE (ACTIVE-HIGH)
FIGURE 15-11: PWM DIRECTION CHANGE AT NEAR 100% DUTY CYCLE (ACTIVE-HIGH)
DC
PWM Period(1)
SIGNAL
Note 1: The direction bit in the CCP1 Control register (CCP1CON<7>) is written any time during the PWM cycle.
2: When changing directions, the P1A and P1C toggle one Timer2 count before the end of the current PWM cycle.
The modulated P1B and P1D signals are inactive at this time.
PWM Period
One Timer2 Count(2)
P1A
P1B
P1C
P1D
DC
Forward Period Reverse Period
P1A
tON
tOFF
t = tOFF – tON
P1B
P1C
P1D
External Switch D
Potential
Shoot-Through
Current
Note 1: tON is the turn-on delay of power switch QC and its driver.
2: tOFF is the turn-off delay of power switch QD and its driver.
External Switch C
t1
DC
DCPIC18F1220/1320
DS39605F-page 126 © 2007 Microchip Technology Inc.
15.5.6 PROGRAMMABLE DEAD-BAND
DELAY
In half-bridge applications where all power switches are
modulated at the PWM frequency at all times, the
power switches normally require more time to turn off
than to turn on. If both the upper and lower power
switches are switched at the same time (one turned on
and the other turned off), both switches may be on for
a short period of time until one switch completely turns
off. During this brief interval, a very high current (shootthrough
current) may flow through both power
switches, shorting the bridge supply. To avoid this
potentially destructive shoot-through current from flowing
during switching, turning on either of the power
switches is normally delayed to allow the other switch
to completely turn off.
In the Half-Bridge Output mode, a digitally programmable
dead-band delay is available to avoid shoot-through
current from destroying the bridge power switches. The
delay occurs at the signal transition from the non-active
state to the active state. See Figure 15-6 for an illustration.
The lower seven bits of the PWM1CON register
(Register 15-2) sets the delay period in terms of
microcontroller instruction cycles (TCY or 4 TOSC).
15.5.7 ENHANCED PWM
AUTO-SHUTDOWN
When the ECCP is programmed for any of the
Enhanced PWM modes, the active output pins may be
configured for auto-shutdown. Auto-shutdown immediately
places the Enhanced PWM output pins into a
defined shutdown state when a shutdown event
occurs.
A shutdown event can be caused by the INT0, INT1 or
INT2 pins (or any combination of these three sources).
The auto-shutdown feature can be disabled by not
selecting any auto-shutdown sources. The autoshutdown
sources to be used are selected using the
ECCPAS2:ECCPAS0 bits (bits <6:4> of the ECCPAS
register).
When a shutdown occurs, the output pins are
asynchronously placed in their shutdown states, specified
by the PSSAC1:PSSAC0 and PSSBD1:PSSBD0
bits (ECCPAS<3:0>). Each pin pair (P1A/P1C and
P1B/P1D) may be set to drive high, drive low or be tristated
(not driving). The ECCPASE bit (ECCPAS<7>)
is also set to hold the Enhanced PWM outputs in their
shutdown states.
The ECCPASE bit is set by hardware when a shutdown
event occurs. If automatic restarts are not enabled, the
ECCPASE bit is cleared by firmware when the cause of
the shutdown clears. If automatic restarts are enabled,
the ECCPASE bit is automatically cleared when the
cause of the auto-shutdown has cleared.
If the ECCPASE bit is set when a PWM period begins,
the PWM outputs remain in their shutdown state for that
entire PWM period. When the ECCPASE bit is cleared,
the PWM outputs will return to normal operation at the
beginning of the next PWM period.
REGISTER 15-2: PWM1CON: PWM CONFIGURATION REGISTER
Note: Writing to the ECCPASE bit is disabled
while a shutdown condition is active.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PRSEN PDC6 PDC5 PDC4 PDC3 PDC2 PDC1 PDC0
bit 7 bit 0
bit 7 PRSEN: PWM Restart Enable bit
1 = Upon auto-shutdown, the ECCPASE bit clears automatically once the shutdown event
goes away; the PWM restarts automatically
0 = Upon auto-shutdown, ECCPASE must be cleared in software to restart the PWM
bit 6-0 PDC<6:0>: PWM Delay Count bits
Number of FOSC/4 (4 * TOSC) cycles between the scheduled time when a PWM signal should
transition active and the actual time it transitions active.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 127
PIC18F1220/1320
REGISTER 15-3: ECCPAS: ENHANCED CAPTURE/COMPARE/PWM/AUTO-SHUTDOWN
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
ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1 PSSBD0
bit 7 bit 0
bit 7 ECCPASE: ECCP Auto-Shutdown Event Status bit
0 = ECCP outputs are operating
1 = A shutdown event has occurred; ECCP outputs are in shutdown state
bit 6 ECCPAS2: ECCP Auto-Shutdown bit 2
0 = INT0 pin has no effect
1 = INT0 pin low causes shutdown
bit 5 ECCPAS1: ECCP Auto-Shutdown bit 1
0 = INT2 pin has no effect
1 = INT2 pin low causes shutdown
bit 4 ECCPAS0: ECCP Auto-Shutdown bit 0
0 = INT1 pin has no effect
1 = INT1 pin low causes shutdown
bit 3-2 PSSACn: Pins A and C Shutdown State Control bits
00 = Drive Pins A and C to ‘0’
01 = Drive Pins A and C to ‘1’
1x = Pins A and C tri-state
bit 1-0 PSSBDn: Pins B and D Shutdown State Control bits
00 = Drive Pins B and D to ‘0’
01 = Drive Pins B and D to ‘1’
1x = Pins B and D tri-state
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 128 © 2007 Microchip Technology Inc.
15.5.7.1 Auto-Shutdown and
Automatic Restart
The auto-shutdown feature can be configured to allow
automatic restarts of the module, following a shutdown
event. This is enabled by setting the PRSEN bit of the
PWM1CON register (PWM1CON<7>).
In Shutdown mode with PRSEN = 1 (Figure 15-12), the
ECCPASE bit will remain set for as long as the cause
of the shutdown continues. When the shutdown
condition clears, the ECCPASE bit is automatically
cleared. If PRSEN = 0 (Figure 15-13), once a shutdown
condition occurs, the ECCPASE bit will remain set until
it is cleared by firmware. Once ECCPASE is cleared,
the Enhanced PWM will resume at the beginning of the
next PWM period.
Independent of the PRSEN bit setting, the ECCPASE
bit cannot be cleared as long as the cause of the
shutdown persists.
The Auto-Shutdown mode can be forced by writing a ‘1’
to the ECCPASE bit.
15.5.8 START-UP CONSIDERATIONS
When the ECCP module is used in the PWM mode, the
application hardware must use the proper external pullup
and/or pull-down resistors on the PWM output pins.
When the microcontroller is released from Reset, all of
the I/O pins are in the high-impedance state. The
external circuits must keep the power switch devices in
the off state, until the microcontroller drives the I/O pins
with the proper signal levels, or activates the PWM
output(s).
The CCP1M1:CCP1M0 bits (CCP1CON<1:0>) allow
the user to choose whether the PWM output signals are
active-high or active-low for each pair of PWM output
pins (P1A/P1C and P1B/P1D). The PWM output
polarities must be selected before the PWM pins are
configured as outputs. Changing the polarity configuration
while the PWM pins are configured as outputs is
not recommended, since it may result in damage to the
application circuits.
The P1A, P1B, P1C and P1D output latches may not be
in the proper states when the PWM module is initialized.
Enabling the PWM pins for output at the same time as
the ECCP module may cause damage to the application
circuit. The ECCP module must be enabled in the proper
output mode and complete a full PWM cycle, before configuring
the PWM pins as outputs. The completion of a
full PWM cycle is indicated by the TMR2IF bit being set
as the second PWM period begins.
FIGURE 15-12: PWM AUTO-SHUTDOWN (PRSEN = 1, AUTO-RESTART ENABLED)
FIGURE 15-13: PWM AUTO-SHUTDOWN (PRSEN = 0, AUTO-RESTART DISABLED)
Note: Writing to the ECCPASE bit is disabled
while a shutdown condition is active.
Shutdown
PWM
ECCPASE bit
Activity
Event
PWM Period PWM Period PWM Period
Duty Cycle
Dead Time
Duty Cycle Duty Cycle
Dead Time Dead Time
Shutdown
PWM
ECCPASE bit
Activity
Event
PWM Period PWM Period PWM Period
ECCPASE
Cleared by Firmware
Duty Cycle
Dead Time
Duty Cycle Duty Cycle
Dead Time Dead Time© 2007 Microchip Technology Inc. DS39605F-page 129
PIC18F1220/1320
15.5.9 SETUP FOR PWM OPERATION
The following steps should be taken when configuring
the ECCP1 module for PWM operation:
1. Configure the PWM pins P1A and P1B (and
P1C and P1D, if used) as inputs by setting the
corresponding TRISB bits.
2. Set the PWM period by loading the PR2 register.
3. Configure the ECCP module for the desired
PWM mode and configuration by loading the
CCP1CON register with the appropriate values:
• Select one of the available output
configurations and direction with the
P1M1:P1M0 bits.
• Select the polarities of the PWM output
signals with the CCP1M3:CCP1M0 bits.
4. Set the PWM duty cycle by loading the CCPR1L
register and CCP1CON<5:4> bits.
5. For Half-Bridge Output mode, set the deadband
delay by loading PWM1CON<6:0> with
the appropriate value.
6. If auto-shutdown operation is required, load the
ECCPAS register:
• Select the auto-shutdown sources using the
ECCPAS<2:0> bits.
• Select the shutdown states of the PWM
output pins using PSSAC1:PSSAC0 and
PSSBD1:PSSBD0 bits.
• Set the ECCPASE bit (ECCPAS<7>).
7. If auto-restart operation is required, set the
PRSEN bit (PWM1CON<7>).
8. Configure and start TMR2:
• Clear the TMR2 interrupt flag bit by clearing
the TMR2IF bit (PIR1<1>).
• Set the TMR2 prescale value by loading the
T2CKPS bits (T2CON<1:0>).
• Enable Timer2 by setting the TMR2ON bit
(T2CON<2>).
9. Enable PWM outputs after a new PWM cycle
has started:
• Wait until TMR2 overflows (TMR2IF bit is set).
• Enable the CCP1/P1A, P1B, P1C and/or P1D
pin outputs by clearing the respective TRISB
bits.
• Clear the ECCPASE bit (ECCPAS<7>).
15.5.10 OPERATION IN LOW-POWER
MODES
In the Low-Power Sleep mode, all clock sources are
disabled. Timer2 will not increment and the state of the
module will not change. If the ECCP pin is driving a
value, it will continue to drive that value. When the
device wakes up, it will continue from this state. If TwoSpeed
Start-ups are enabled, the initial start-up
frequency may not be stable if the INTOSC is being
used.
In PRI_IDLE mode, the primary clock will continue to
clock the ECCP module without change.
In all other low-power modes, the selected low-power
mode clock will clock Timer2. Other low-power mode
clocks will most likely be different than the primary
clock frequency.
15.5.10.1 Operation with Fail-Safe
Clock Monitor
If the Fail-Safe Clock Monitor is enabled
(CONFIG1H<6> is programmed), a clock failure will
force the device into the Low-Power RC_RUN mode
and the OSCFIF bit (PIR2<7>) will be set. The ECCP
will then be clocked from the INTRC clock source,
which may have a different clock frequency than the
primary clock. By loading the IRCF2:IRCF0 bits on
Resets, the user can enable the INTOSC at a high
clock speed in the event of a clock failure.
See the previous section for additional details.
15.5.11 EFFECTS OF A RESET
Both power-on and subsequent Resets will force all
ports to input mode and the CCP registers to their
Reset states.
This forces the Enhanced CCP module to reset to a
state compatible with the standard CCP module.PIC18F1220/1320
DS39605F-page 130 © 2007 Microchip Technology Inc.
TABLE 15-5: REGISTERS ASSOCIATED WITH ENHANCED PWM AND TIMER2
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
RCON IPEN — — RI TO PD POR BOR 0--1 11qq 0--q qquu
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
TMR2 Timer2 Module Register 0000 0000 0000 0000
PR2 Timer2 Module Period Register 1111 1111 1111 1111
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
TRISB PORTB Data Direction Register 1111 1111 1111 1111
CCPR1H Enhanced Capture/Compare/PWM Register 1 High Byte xxxx xxxx uuuu uuuu
CCPR1L Enhanced Capture/Compare/PWM Register 1 Low Byte xxxx xxxx uuuu uuuu
CCP1CON P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 0000 0000 0000 0000
ECCPAS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1 PSSBD0 0000 0000 0000 0000
PWM1CON PRSEN PDC6 PDC5 PDC4 PDC3 PDC2 PDC1 PDC0 0000 0000 uuuu uuuu
OSCCON IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 0000 qq00 0000 qq00
Legend: x = unknown, u = unchanged, – = unimplemented, read as ‘0’.
Shaded cells are not used by the ECCP module in Enhanced PWM mode.© 2007 Microchip Technology Inc. DS39605F-page 131
PIC18F1220/1320
16.0 ENHANCED ADDRESSABLE
UNIVERSAL SYNCHRONOUS
ASYNCHRONOUS RECEIVER
TRANSMITTER (EUSART)
The Enhanced Addressable Universal Synchronous
Asynchronous Receiver Transmitter (EUSART) module
can be configured as a full-duplex asynchronous
system that can communicate with peripheral devices,
such as CRT terminals and personal computers. It can
also 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 Enhanced Addressable USART module
implements additional features, including automatic
baud rate detection and calibration, automatic wake-up
on Sync Break reception and 12-bit Break character
transmit. These features make it ideally suited for use
in Local Interconnect Network (LIN) bus systems.
The EUSART can be configured in the following
modes:
• Asynchronous (full duplex) with:
- Auto-wake-up on character reception
- Auto-baud calibration
- 12-bit Break character transmission
• Synchronous – Master (half duplex) with
selectable clock polarity
• Synchronous – Slave (half duplex) with selectable
clock polarity
The RB1/AN5/TX/CK/INT1 and RB4/AN6/RX/DT/KBI0
pins must be configured as follows for use with the
Universal Synchronous Asynchronous Receiver
Transmitter:
• SPEN (RCSTA<7>) bit must be set ( = 1),
• PCFG6:PCFG5 (ADCON1<5:6>) must be set ( = 1),
• TRISB<4> bit must be set ( = 1) and
• TRISB<1> bit must be set ( = 1).
The operation of the Enhanced USART module is
controlled through three registers:
• Transmit Status and Control (TXSTA)
• Receive Status and Control (RCSTA)
• Baud Rate Control (BAUDCTL)
These are detailed in on the following pages in
Register 16-1, Register 16-2 and Register 16-3,
respectively.
16.1 Asynchronous Operation in Power
Managed Modes
The EUSART may operate in Asynchronous mode
while the peripheral clocks are being provided by the
internal oscillator block. This makes it possible to
remove the crystal or resonator that is commonly
connected as the primary clock on the OSC1 and
OSC2 pins.
The factory calibrates the internal oscillator block output
(INTOSC) for 8 MHz (see Table 22-6). However,
this frequency may drift as VDD or temperature
changes and this directly affects the asynchronous
baud rate. Two methods may be used to adjust the
baud rate clock, but both require a reference clock
source of some kind.
The first (preferred) method uses the OSCTUNE
register to adjust the INTOSC output back to 8 MHz.
Adjusting the value in the OSCTUNE register allows for
fine resolution changes to the system clock source (see
Section 3.6 “INTOSC Frequency Drift” for more
information).
The other method adjusts the value in the Baud Rate
Generator (BRG). There may not be fine enough
resolution when adjusting the Baud Rate Generator to
compensate for a gradual change in the peripheral
clock frequency.
Note: The EUSART control will automatically
reconfigure the pin from input to output as
needed.PIC18F1220/1320
DS39605F-page 132 © 2007 Microchip Technology Inc.
REGISTER 16-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 R/W-0
CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D
bit 7 bit 0
bit 7 CSRC: Clock Source Select bit
Asynchronous mode:
Don’t care.
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: SREN/CREN overrides TXEN in Sync mode.
bit 4 SYNC: EUSART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
bit 3 SENDB: Send Break Character bit
Asynchronous mode:
1 = Send Sync Break on next transmission (cleared by hardware upon completion)
0 = Sync Break transmission completed
Synchronous mode:
Don’t care.
bit 2 BRGH: High Baud Rate Select bit
Asynchronous mode:
1 = High speed
0 = Low speed
Synchronous mode:
Unused in this mode.
bit 1 TRMT: Transmit Shift Register Status bit
1 = TSR Idle
0 = TSR busy
bit 0 TX9D: 9th bit of Transmit Data
Can be address/data bit or a parity bit.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 133
PIC18F1220/1320
REGISTER 16-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 (held in Reset)
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
Asynchronous mode:
Don’t care.
Synchronous mode – Master:
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception is complete.
Synchronous mode – Slave:
Don’t care.
bit 4 CREN: Continuous Receive Enable bit
Asynchronous mode:
1 = Enables receiver
0 = Disables receiver
Synchronous mode:
1 = Enables continuous receive until enable bit, CREN, is cleared (CREN overrides SREN)
0 = Disables continuous receive
bit 3 ADDEN: Address Detect Enable bit
Asynchronous mode 9-bit (RX9 = 1):
1 = Enables address detection, generates RCIF interrupt and loads RCREG when RX9D is set
0 = Disables address detection, all bytes are received and ninth bit can be used as parity bit
Asynchronous mode 8-bit (RX9 = 0):
Don’t care.
bit 2 FERR: Framing Error bit
1 = Framing error (can be updated by reading RCREG register and receiving 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
This can be address/data bit or a parity bit and must be calculated by user firmware.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 134 © 2007 Microchip Technology Inc.
REGISTER 16-3: BAUDCTL: BAUD RATE CONTROL REGISTER
U-0 R-1 U-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0
— RCIDL — SCKP BRG16 — WUE ABDEN
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 RCIDL: Receive Operation Idle Status bit
1 = Receiver is Idle
0 = Receiver is busy
bit 5 Unimplemented: Read as ‘0’
bit 4 SCKP: Synchronous Clock Polarity Select bit
Asynchronous mode:
Unused in this mode.
Synchronous mode:
1 = Idle state for clock (CK) is a high level
0 = Idle state for clock (CK) is a low level
bit 3 BRG16: 16-bit Baud Rate Register Enable bit
1 = 16-bit Baud Rate Generator – SPBRGH and SPBRG
0 = 8-bit Baud Rate Generator – SPBRG only (Compatible mode), SPBRGH value ignored
bit 2 Unimplemented: Read as ‘0’
bit 1 WUE: Wake-up Enable bit
Asynchronous mode:
1 = EUSART will continue to sample the RX pin – interrupt generated on falling edge; bit
cleared in hardware on following rising edge
0 = RX pin not monitored or rising edge detected
Synchronous mode:
Unused in this mode.
bit 0 ABDEN: Auto-Baud Detect Enable bit
Asynchronous mode:
1 = Enable baud rate measurement on the next character – requires reception of a Sync byte
(55h); cleared in hardware upon completion
0 = Baud rate measurement disabled or completed
Synchronous mode:
Unused in this mode.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 135
PIC18F1220/1320
16.2 EUSART Baud Rate Generator
(BRG)
The BRG is a dedicated 8-bit or 16-bit generator, that
supports both the Asynchronous and Synchronous
modes of the EUSART. By default, the BRG operates
in 8-bit mode; setting the BRG16 bit (BAUDCTL<3>)
selects 16-bit mode.
The SPBRGH:SPBRG register pair controls the period
of a free running timer. In Asynchronous mode, bits
BRGH (TXSTA<2>) and BRG16 also control the baud
rate. In Synchronous mode, bit BRGH is ignored.
Table 16-1 shows the formula for computation of the
baud rate for different EUSART modes which only
apply in Master mode (internally generated clock).
Given the desired baud rate and FOSC, the nearest
integer value for the SPBRGH:SPBRG registers can be
calculated using the formulas in Table 16-1. From this,
the error in baud rate can be determined. An example
calculation is shown in Example 16-1. Typical baud
rates and error values for the various asynchronous
modes are shown in Table 16-2. It may be
advantageous to use the high baud rate (BRGH = 1),
or the 16-bit BRG to reduce the baud rate error, or
achieve a slow baud rate for a fast oscillator frequency.
Writing a new value to the SPBRGH:SPBRG registers
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.
16.2.1 POWER MANAGED MODE
OPERATION
The system clock is used to generate the desired baud
rate; however, when a power managed mode is
entered, the clock source may be operating at a different
frequency than in PRI_RUN mode. In Sleep mode,
no clocks are present and in PRI_IDLE mode, the
primary clock source continues to provide clocks to the
Baud Rate Generator; however, in other power
managed modes, the clock frequency will probably
change. This may require the value in SPBRG to be
adjusted.
If the system clock is changed during an active receive
operation, a receive error or data loss may result. To
avoid this problem, check the status of the RCIDL bit
and make sure that the receive operation is Idle before
changing the system clock.
16.2.2 SAMPLING
The data on the RB4/AN6/RX/DT/KBI0 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.
TABLE 16-1: BAUD RATE FORMULAS
EXAMPLE 16-1: CALCULATING BAUD RATE ERROR
Configuration Bits BRG/EUSART Mode Baud Rate Formula
SYNC BRG16 BRGH
000 8-bit/Asynchronous FOSC/[64 (n + 1)]
001 8-bit/Asynchronous FOSC/[16 (n + 1)] 010 16-bit/Asynchronous
011 16-bit/Asynchronous
10x 8-bit/Synchronous FOSC/[4 (n + 1)]
11x 16-bit/Synchronous
Legend: x = Don’t care, n = value of SPBRGH:SPBRG register pair
For a device with FOSC of 16 MHz, desired baud rate of 9600, Asynchronous mode, 8-bit BRG:
Desired Baud Rate = FOSC/(64 ([SPBRGH:SPBRG] + 1))
Solving for SPBRGH:SPBRG:
X = ((FOSC/Desired Baud Rate)/64) – 1
= ((16000000/9600)/64) – 1
= [25.042] = 25
Calculated Baud Rate= 16000000/(64 (25 + 1))
= 9615
Error = (Calculated Baud Rate – Desired Baud Rate)/Desired Baud Rate
= (9615 – 9600)/9600 = 0.16%PIC18F1220/1320
DS39605F-page 136 © 2007 Microchip Technology Inc.
TABLE 16-2: REGISTERS ASSOCIATED WITH BAUD RATE GENERATOR
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
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 -010 0000 -010
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented, read as ‘0’. Shaded cells are not used by the BRG.
TABLE 16-3: BAUD RATES FOR ASYNCHRONOUS MODES
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 0
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 — — — — — — — — — — — —
1.2 — — — 1.221 1.73 255 1.202 0.16 129 1201 -0.16 103
2.4 2.441 1.73 255 2.404 0.16 129 2.404 0.16 64 2403 -0.16 51
9.6 9.615 0.16 64 9.766 1.73 31 9.766 1.73 15 9615 -0.16 12
19.2 19.531 1.73 31 19.531 1.73 15 19.531 1.73 7 — — —
57.6 56.818 -1.36 10 62.500 8.51 4 52.083 -9.58 2 — — —
115.2 125.000 8.51 4 104.167 -9.58 2 78.125 -32.18 1 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 0
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 0.300 0.16 207 300 -0.16 103 300 -0.16 51
1.2 1.202 0.16 51 1201 -0.16 25 1201 -0.16 12
2.4 2.404 0.16 25 2403 -0.16 12 — — —
9.6 8.929 -6.99 6 — — — — — —
19.2 20.833 8.51 2 — — — — — —
57.6 62.500 8.51 0 — — — — — —
115.2 62.500 -45.75 0 — — — — — —© 2007 Microchip Technology Inc. DS39605F-page 137
PIC18F1220/1320
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 0
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
2.4 — — — — — — 2.441 1.73 255 2403 -0.16 207
9.6 9.766 1.73 255 9.615 0.16 129 9.615 0.16 64 9615 -0.16 51
19.2 19.231 0.16 129 19.231 0.16 64 19.531 1.73 31 19230 -0.16 25
57.6 58.140 0.94 42 56.818 -1.36 21 56.818 -1.36 10 55555 3.55 8
115.2 113.636 -1.36 21 113.636 -1.36 10 125.000 8.51 4 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 0
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 — — — — — — 300 -0.16 207
1.2 1.202 0.16 207 1201 -0.16 103 1201 -0.16 51
2.4 2.404 0.16 103 2403 -0.16 51 2403 -0.16 25
9.6 9.615 0.16 25 9615 -0.16 12 — — —
19.2 19.231 0.16 12 — — — — — —
57.6 62.500 8.51 3 — — — — — —
115.2 125.000 8.51 1 — — — — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 1
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 0.300 0.00 8332 0.300 0.02 4165 0.300 0.02 2082 300 -0.04 1665
1.2 1.200 0.02 2082 1.200 -0.03 1041 1.200 -0.03 520 1201 -0.16 415
2.4 2.402 0.06 1040 2.399 -0.03 520 2.404 0.16 259 2403 -0.16 207
9.6 9.615 0.16 259 9.615 0.16 129 9.615 0.16 64 9615 -0.16 51
19.2 19.231 0.16 129 19.231 0.16 64 19.531 1.73 31 19230 -0.16 25
57.6 58.140 0.94 42 56.818 -1.36 21 56.818 -1.36 10 55555 3.55 8
115.2 113.636 -1.36 21 113.636 -1.36 10 125.000 8.51 4 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 1
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 0.300 0.04 832 300 -0.16 415 300 -0.16 207
1.2 1.202 0.16 207 1201 -0.16 103 1201 -0.16 51
2.4 2.404 0.16 103 2403 -0.16 51 2403 -0.16 25
9.6 9.615 0.16 25 9615 -0.16 12 — — —
19.2 19.231 0.16 12 — — — — — —
57.6 62.500 8.51 3 — — — — — —
115.2 125.000 8.51 1 — — — — — —
TABLE 16-3: BAUD RATES FOR ASYNCHRONOUS MODES (CONTINUED)PIC18F1220/1320
DS39605F-page 138 © 2007 Microchip Technology Inc.
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 1 or SYNC = 1, BRG16 = 1
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 0.300 0.00 33332 0.300 0.00 16665 0.300 0.00 8332 300 -0.01 6665
1.2 1.200 0.00 8332 1.200 0.02 4165 1.200 0.02 2082 1200 -0.04 1665
2.4 2.400 0.02 4165 2.400 0.02 2082 2.402 0.06 1040 2400 -0.04 832
9.6 9.606 0.06 1040 9.596 -0.03 520 9.615 0.16 259 9615 -0.16 207
19.2 19.193 -0.03 520 19.231 0.16 259 19.231 0.16 129 19230 -0.16 103
57.6 57.803 0.35 172 57.471 -0.22 86 58.140 0.94 42 57142 0.79 34
115.2 114.943 -0.22 86 116.279 0.94 42 113.636 -1.36 21 117647 -2.12 16
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 1 or SYNC = 1, BRG16 = 1
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
value
(decimal)
0.3 0.300 0.01 3332 300 -0.04 1665 300 -0.04 832
1.2 1.200 0.04 832 1201 -0.16 415 1201 -0.16 207
2.4 2.404 0.16 415 2403 -0.16 207 2403 -0.16 103
9.6 9.615 0.16 103 9615 -0.16 51 9615 -0.16 25
19.2 19.231 0.16 51 19230 -0.16 25 19230 -0.16 12
57.6 58.824 2.12 16 55555 3.55 8 — — —
115.2 111.111 -3.55 8 — — — — — —
TABLE 16-3: BAUD RATES FOR ASYNCHRONOUS MODES (CONTINUED)© 2007 Microchip Technology Inc. DS39605F-page 139
PIC18F1220/1320
16.2.3 AUTO-BAUD RATE DETECT
The Enhanced USART module supports the automatic
detection and calibration of baud rate. This feature is
active only in Asynchronous mode and while the WUE
bit is clear.
The automatic baud rate measurement sequence
(Figure 16-1) begins whenever a Start bit is received and
the ABDEN bit is set. The calculation is self-averaging.
In the Auto-Baud Rate Detect (ABD) mode, the clock to
the BRG is reversed. Rather than the BRG clocking the
incoming RX signal, the RX signal is timing the BRG. In
ABD mode, the internal Baud Rate Generator is used
as a counter to time the bit period of the incoming serial
byte stream.
Once the ABDEN bit is set, the state machine will clear
the BRG and look for a Start bit. The Auto-Baud Detect
must receive a byte with the value 55h (ASCII “U”,
which is also the LIN bus Sync character), in order to
calculate the proper bit rate. The measurement is taken
over both a low and a high bit time in order to minimize
any effects caused by asymmetry of the incoming signal.
After a Start bit, the SPBRG begins counting up
using the preselected clock source on the first rising
edge of RX. After eight bits on the RX pin, or the fifth
rising edge, an accumulated value totalling the proper
BRG period is left in the SPBRGH:SPBRG registers.
Once the 5th edge is seen (should correspond to the
Stop bit), the ABDEN bit is automatically cleared.
While calibrating the baud rate period, the BRG
registers are clocked at 1/8th the preconfigured clock
rate. Note that the BRG clock will be configured by the
BRG16 and BRGH bits. Independent of the BRG16 bit
setting, both the SPBRG and SPBRGH will be used as
a 16-bit counter. This allows the user to verify that no
carry occurred for 8-bit modes, by checking for 00h in
the SPBRGH register. Refer to Table 16-4 for counter
clock rates to the BRG.
While the ABD sequence takes place, the EUSART
state machine is held in Idle. The RCIF interrupt is set
once the fifth rising edge on RX is detected. The value
in the RCREG needs to be read to clear the RCIF
interrupt. RCREG content should be discarded.
16.2.4 RECEIVING A SYNC (AUTO-BAUD
RATE DETECT)
To receive a Sync (Auto-Baud Rate Detect):
1. Configure the EUSART for asynchronous receive.
TXEN should remain clear. SPBRGH:SPBRG
may be left as is. The controller should operate in
either PRI_RUN or PRI_IDLE.
2. Enable RXIF interrupts. Set RCIE, PEIE, GIE.
3. Enable Auto-Baud Rate Detect. Set ABDEN.
4. When the next RCIF interrupt occurs, the
received baud rate has been measured. Read
RCREG to clear RCIF and discard. Check
SPBRGH:SPBRG for a valid value. The
EUSART is ready for normal communications.
Return from the interrupt. Allow the primary
clock to run (PRI_RUN or PRI_IDLE).
5. Process subsequent RCIF interrupts normally
as in asynchronous reception. Remain in
PRI_RUN or PRI_IDLE until communications
are complete.
TABLE 16-4: BRG COUNTER CLOCK
RATES
Note 1: It is up to the user to determine that the
incoming character baud rate is within the
range of the selected BRG clock source.
Some combinations of oscillator frequency
and EUSART baud rates are not possible
due to bit error rates. Overall system
timing and communication baud rates
must be taken into consideration when
using the Auto-Baud Rate Detection
feature.
BRG16 BRGH BRG Counter Clock
0 0 FOSC/512
0 1 FOSC/128
1 0 FOSC/128
1 1 FOSC/32
Note: During the ABD sequence, SPBRG and
SPBRGH are both used as a 16-bit counter,
independent of BRG16 setting.PIC18F1220/1320
DS39605F-page 140 © 2007 Microchip Technology Inc.
FIGURE 16-1: AUTOMATIC BAUD RATE CALCULATION
16.3 EUSART Asynchronous Mode
The Asynchronous mode of operation is selected by
clearing the SYNC bit (TXSTA<4>). In this mode, the
EUSART uses standard Non-Return-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/16-bit Baud Rate Generator can be
used to derive standard baud rate frequencies from the
oscillator.
The EUSART transmits and receives the LSb first. The
EUSART’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
and BRG16 bits (TXSTA<2> and BAUDCTL<3>). Parity
is not supported by the hardware, but can be
implemented in software and stored as the 9th data bit.
Asynchronous mode is available in all low-power
modes; it is available in Sleep mode only when autowake-up
on Sync Break is enabled. When in PRI_IDLE
mode, no changes to the Baud Rate Generator values
are required; however, other low-power mode clocks
may operate at another frequency than the primary
clock. Therefore, the Baud Rate Generator values may
need to be adjusted.
When operating in Asynchronous mode, the EUSART
module consists of the following important elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
• Auto-Wake-up on Sync Break Character
• 12-bit Break Character Transmit
• Auto-Baud Rate Detection
16.3.1 EUSART ASYNCHRONOUS
TRANSMITTER
The EUSART transmitter block diagram is shown in
Figure 16-2. The heart of the transmitter is the Transmit
(Serial) Shift Register (TSR). The shift register obtains
its data from the Read/Write Transmit Buffer register,
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the 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 flag bit, TXIF (PIR1<4>), is set. This interrupt
can be enabled/disabled by setting/clearing enable bit,
TXIE (PIE1<4>). Flag bit, TXIF, will be set, regardless of
the state of enable bit, TXIE, and cannot be cleared in
software. Flag bit, TXIF, is not cleared immediately upon
loading the Transmit Buffer register, TXREG. TXIF
becomes valid in the second instruction cycle following
the load instruction. Polling TXIF immediately following a
load of TXREG will return invalid results.
While flag bit, TXIF, indicates the status of the TXREG
register, another bit, TRMT (TXSTA<1>), shows the
status of the TSR register. Status bit, TRMT, is a readonly
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.
BRG Value
RX pin
ABDEN bit
RCIF bit
Bit 0 Bit 1
(Interrupt)
Read
RCREG
BRG Clock
Start
Set by User Auto-Cleared
XXXXh 0000h
Edge #1
Bit 2 Bit 3
Edge #2
Bit 4 Bit 5
Edge #3
Bit 6 Bit 7
Edge #4 Edge #5
001Ch
Note 1: The ABD sequence requires the EUSART module to be configured in Asynchronous mode and WUE = 0.
SPBRG XXXXh 1Ch
SPBRGH XXXXh 00h
Stop Bit
Note 1: The TSR register is not mapped in data
memory, so it is not available to the user.
2: Flag bit, TXIF, is set when enable bit,
TXEN, is set.© 2007 Microchip Technology Inc. DS39605F-page 141
PIC18F1220/1320
To set up an Asynchronous Transmission:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set transmit bit
TX9. Can be used as address/data bit.
5. Enable the transmission by setting bit TXEN,
which will also set bit TXIF.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Load data to the TXREG register (starts
transmission).
If using interrupts, ensure that the GIE and PEIE bits in
the INTCON register (INTCON<7:6>) are set.
FIGURE 16-2: EUSART TRANSMIT BLOCK DIAGRAM
FIGURE 16-3: ASYNCHRONOUS TRANSMISSION
TXIF
TXIE
Interrupt
TXEN Baud Rate CLK
SPBRG
Baud Rate Generator
TX9D
MSb LSb
Data Bus
TXREG Register
TSR Register
(8) 0
TX9
TRMT SPEN
RB1/AN5/TX/CK/INT1 pin
Pin Buffer
and Control
8
• • •
BRG16 SPBRGH
Word 1
Word 1
Transmit Shift Reg
Start bit bit 0 bit 1 bit 7/8
Write to TXREG
Word 1
BRG Output
(Shift Clock)
RB1/AN5/TX/
TXIF bit
(Transmit Buffer
Reg. Empty Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
1 TCY
CK/INT1 (pin) Stop bitPIC18F1220/1320
DS39605F-page 142 © 2007 Microchip Technology Inc.
FIGURE 16-4: ASYNCHRONOUS TRANSMISSION (BACK TO BACK)
TABLE 16-5: REGISTERS ASSOCIATED WITH ASYNCHRONOUS TRANSMISSION
Transmit Shift Reg.
Write to TXREG
BRG Output
(Shift Clock)
RB1/AN5/TX/
TXIF bit
(Interrupt Reg. Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
Word 1 Word 2
Word 1 Word 2
Stop bit Start bit
Transmit Shift Reg.
Word 1 Word 2
bit 0 bit 1 bit 7/8 bit 0
Note: This timing diagram shows two consecutive transmissions.
1 TCY
1 TCY
CK/INT1 (pin) Start bit
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG EUSART Transmit Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented locations read as ‘0’. Shaded cells are not used for asynchronous transmission.© 2007 Microchip Technology Inc. DS39605F-page 143
PIC18F1220/1320
16.3.2 EUSART ASYNCHRONOUS
RECEIVER
The receiver block diagram is shown in Figure 16-5.
The data is received on the RB4/AN6/RX/DT/KBI0 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.
To set up an Asynchronous Reception:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit RCIE.
4. If 9-bit reception is desired, set bit RX9.
5. Enable the reception by setting bit CREN.
6. Flag bit, RCIF, will be set when reception is
complete and an interrupt will be generated if
enable bit RCIE was set.
7. Read the RCSTA register to get the 9th 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
enable bit CREN.
10. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
16.3.3 SETTING UP 9-BIT MODE WITH
ADDRESS DETECT
This mode would typically be used in RS-485 systems.
To set up an Asynchronous Reception with Address
Detect Enable:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
the SYNC bit and setting the SPEN bit.
3. If interrupts are required, set the RCEN bit and
select the desired priority level with the RCIP bit.
4. Set the RX9 bit to enable 9-bit reception.
5. Set the ADDEN bit to enable address detect.
6. Enable reception by setting the CREN bit.
7. The RCIF bit will be set when reception is
complete. The interrupt will be Acknowledged if
the RCIE and GIE bits are set.
8. Read the RCSTA register to determine if any
error occurred during reception, as well as read
bit 9 of data (if applicable).
9. Read RCREG to determine if the device is being
addressed.
10. If any error occurred, clear the CREN bit.
11. If the device has been addressed, clear the
ADDEN bit to allow all received data into the
receive buffer and interrupt the CPU.
FIGURE 16-5: EUSART RECEIVE BLOCK DIAGRAM
x64 Baud Rate CLK
Baud Rate Generator
RB4/AN6/RX/DT/KBI0
Pin Buffer
and Control
SPEN
Data
Recovery
CREN OERR FERR
MSb RSR Register LSb
RX9D RCREG Register
FIFO
Interrupt RCIF
RCIE
Data Bus
8
÷ 64
÷ 16
or
Stop (8) 7 1 0 Start
RX9
• • •
BRG16 SPBRGH SPBRG
or
÷ 4PIC18F1220/1320
DS39605F-page 144 © 2007 Microchip Technology Inc.
To set up an Asynchronous Transmission:
1. Initialize the SPBRG register for the appropriate
baud rate. If a high-speed baud rate is desired,
set bit BRGH (see Section 16.2 “EUSART
Baud Rate Generator (BRG)”).
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set transmit bit
TX9. Can be used as address/data bit.
5. Enable the transmission by setting bit TXEN,
which will also set bit TXIF.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Load data to the TXREG register (starts
transmission).
If using interrupts, ensure that the GIE and PEIE bits in
the INTCON register (INTCON<7:6>) are set.
FIGURE 16-6: ASYNCHRONOUS RECEPTION
TABLE 16-6: REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION
Start
bit bit 0 bit 7/8 bit 1 Stop bit 0 bit 7/8
bit
Start
bit
Start
bit 7/8 Stop bit
bit
RX (pin)
Reg
Rcv Buffer Reg
Rcv Shift
Read Rcv
Buffer Reg
RCREG
RCIF
(Interrupt Flag)
OERR bit
CREN
Word 1
RCREG
Word 2
RCREG
Stop
bit
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.
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG EUSART Receive Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented locations read as ‘0’. Shaded cells are not used for asynchronous reception.© 2007 Microchip Technology Inc. DS39605F-page 145
PIC18F1220/1320
16.3.4 AUTO-WAKE-UP ON SYNC BREAK
CHARACTER
During Sleep mode, all clocks to the EUSART are
suspended. Because of this, the Baud Rate Generator
is inactive and a proper byte reception cannot be performed.
The auto-wake-up feature allows the controller
to wake-up due to activity on the RX/DT line while the
EUSART is operating in Asynchronous mode.
The auto-wake-up feature is enabled by setting the
WUE bit (BAUDCTL<1>). Once set, the typical receive
sequence on RX/DT is disabled and the EUSART
remains in an Idle state, monitoring for a wake-up event
independent of the CPU mode. A wake-up event consists
of a high-to-low transition on the RX/DT line. (This
coincides with the start of a Sync Break or a Wake-up
Signal character for the LIN protocol.)
Following a wake-up event, the module generates an
RCIF interrupt. The interrupt is generated synchronously
to the Q clocks in normal operating modes
(Figure 16-7) and asynchronously if the device is in
Sleep mode (Figure 16-8). The interrupt condition is
cleared by reading the RCREG register.
The WUE bit is automatically cleared once a low-to-high
transition is observed on the RX line, following the wakeup
event. At this point, the EUSART module is in Idle
mode and returns to normal operation. This signals to
the user that the Sync Break event is over.
16.3.4.1 Special Considerations Using
Auto-Wake-up
Since auto-wake-up functions by sensing rising edge
transitions on RX/DT, information with any state changes
before the Stop bit may signal a false end-of-character
and cause data or framing errors. To work properly,
therefore, the initial character in the transmission must
be all ‘0’s. This can be 00h (8 bytes) for standard RS-232
devices, or 000h (12 bits) for LIN bus.
Oscillator start-up time must also be considered,
especially in applications using oscillators with longer
start-up intervals (i.e., LP, XT or HS/PLL mode). The
Sync Break (or Wake-up Signal) character must be of
sufficient length and be followed by a sufficient period,
to allow enough time for the selected oscillator to start
and provide proper initialization of the EUSART.
16.3.4.2 Special Considerations Using
the WUE Bit
The timing of WUE and RCIF events may cause some
confusion when it comes to determining the validity of
received data. As noted, setting the WUE bit places the
EUSART in an Idle mode. The wake-up event causes
a receive interrupt by setting the RCIF bit. The WUE bit
is cleared after this when a rising edge is seen on RX/
DT. The interrupt condition is then cleared by reading
the RCREG register. Ordinarily, the data in RCREG will
be dummy data and should be discarded.
The fact that the WUE bit has been cleared (or is still
set) and the RCIF flag is set should not be used as an
indicator of the integrity of the data in RCREG. Users
should consider implementing a parallel method in
firmware to verify received data integrity.
To assure that no actual data is lost, check the RCIDL
bit to verify that a receive operation is not in process. If
a receive operation is not occurring, the WUE bit may
then be set just prior to entering the Sleep mode.
FIGURE 16-7: AUTO-WAKE-UP BIT (WUE) TIMINGS DURING NORMAL OPERATION
FIGURE 16-8: AUTO-WAKE-UP BIT (WUE) TIMINGS DURING SLEEP
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
WUE bit
RX/DT Line
RCIF
Cleared due to User Read of RCREG
Note 1: The EUSART remains in Idle while the WUE bit is set.
Bit Set by User Cleared by hardware
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
WUE bit
RX/DT Line
RCIF
Cleared due to User Read of RCREG
Note 1: If the wake-up event requires a long oscillator warm-up time, the WUE bit may be cleared while the primary clock is still starting.
2: The EUSART remains in Idle while the WUE bit is set.
Sleep Ends
Enters Sleep Bit Set by User Cleared by hardware
Note 1PIC18F1220/1320
DS39605F-page 146 © 2007 Microchip Technology Inc.
16.3.5 BREAK CHARACTER SEQUENCE
The Enhanced USART module has the capability of
sending the special Break character sequences that
are required by the LIN bus standard. The Break character
transmit consists of a Start bit, followed by twelve
‘0’ bits and a Stop bit. The Frame Break character is
sent whenever the SENDB and TXEN bits (TXSTA<3>
and TXSTA<5>) are set while the Transmit Shift
register is loaded with data. Note that the value of data
written to TXREG will be ignored and all ‘0’s will be
transmitted.
The SENDB bit is automatically reset by hardware after
the corresponding Stop bit is sent. This allows the user
to preload the transmit FIFO with the next transmit byte
following the Break character (typically, the Sync
character in the LIN specification).
Note that the data value written to the TXREG for the
Break character is ignored. The write simply serves the
purpose of initiating the proper sequence.
The TRMT bit indicates when the transmit operation is
active or Idle, just as it does during normal transmission.
See Figure 16-9 for the timing of the Break
character sequence.
16.3.5.1 Transmitting A Break Signal
The Enhanced USART module has the capability of
sending the Break signal that is required by the LIN bus
standard. The Break signal consists of a Start bit,
followed by twelve ‘0’ bits and a Stop bit. The Break signal
is sent whenever the SENDB (TXSTA<3>) and
TXEN (TXSTA<5>) bits are set and TXREG is loaded
with data. The data written to TXREG will be ignored
and all ‘0’s will be transmitted.
SENDB is automatically cleared by hardware when the
Break signal has been sent. This allows the user to
preload the transmit FIFO with the next transmit byte
following the Break character (typically, the Sync
character in the LIN specification).
The TRMT bit indicates when the transmit operation is
active or Idle, just as it does during normal
transmission.
To send a Break Signal:
1. Configure the EUSART for asynchronous transmissions
(steps 1-5). Initialize the SPBRG register
for the appropriate baud rate. If a high-speed baud
rate is desired, set bit BRGH (see Section 16.2
“EUSART Baud Rate Generator (BRG)”).
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set transmit bit
TX9. Can be used as address/data bit.
5. Enable the transmission by setting bit TXEN,
which will also set bit TXIF.
6. Set the SENDB bit.
7. Load a byte into TXREG. This triggers sending a
Break signal. The Break signal is complete
when TRMT is set. SENDB will also be cleared.
See Figure 16-9 for the timing of the Break signal
sequence.
16.3.6 RECEIVING A BREAK CHARACTER
The Enhanced USART module can receive a Break
character in two ways.
The first method forces configuration of the baud rate
at a frequency of 9/13 the typical speed. This allows for
the Stop bit transition to be at the correct sampling
location (12 bits for Break versus Start bit and 8 data
bits for typical data).
The second method uses the auto-wake-up feature
described in Section 16.3.4 “Auto-Wake-up on Sync
Break Character”. By enabling this feature, the
EUSART will sample the next two transitions on RX/DT,
cause an RCIF interrupt and receive the next data byte
followed by another interrupt.
Note that following a Break character, the user will
typically want to enable the Auto-Baud Rate Detect
feature. For both methods, the user can set the ABD bit
before placing the EUSART in its Sleep mode.
16.3.6.1 Transmitting a Break Sync
The following sequence will send a message frame
header made up of a Break, followed by an auto-baud
Sync byte. This sequence is typical of a LIN bus master.
1. Configure the EUSART for the desired mode.
2. Set the TXEN and SENDB bits to set up the
Break character.
3. Load the TXREG with a dummy character to
initiate transmission (the value is ignored).
4. Write ‘55h’ to TXREG to load the Sync character
into the transmit FIFO buffer.
5. After the Break has been sent, the SENDB bit is
reset by hardware. The Sync character now
transmits in the preconfigured mode. When the
TXREG becomes empty, as indicated by the
TXIF, the next data byte can be written to TXREG.© 2007 Microchip Technology Inc. DS39605F-page 147
PIC18F1220/1320
16.3.6.2 Receiving a Break Sync
To receive a Break Sync:
1. Configure the EUSART for asynchronous
transmit and receive. TXEN should remain
clear. SPBRGH:SPBRG may be left as is.
2. Enable auto-wake-up. Set WUE.
3. Enable RXIF interrupts. Set RCIE, PEIE, GIE.
4. The controller may be placed in any power
managed mode.
5. An RCIF will be generated at the beginning of
the Break signal. When the interrupt is received,
read RCREG to clear RCIF and discard. Allow
the controller to return to PRI_RUN mode.
6. Wait for the RX line to go high at the end of the
Break signal. Wait for any of the following: WUE
to clear automatically (poll), RB4/RX to go high
(poll) or for RBIF to be set (poll or interrupt). If
RBIF is used, check to be sure that RB4/RX is
high before continuing.
7. Enable Auto-Baud Rate Detect. Set ABDEN.
8. Return from the interrupt. Allow the primary
clock to start and stabilize (PRI_RUN or
PRI_IDLE).
9. When the next RCIF interrupt occurs, the
received baud rate has been measured. Read
RCREG to clear RCIF and discard. Check
SPBRGH:SPBRG for a valid value. The
EUSART is ready for normal communications.
Return from the interrupt. Allow the primary
clock to run (PRI_RUN or PRI_IDLE).
10. Process subsequent RCIF interrupts normally
as in asynchronous reception. TXEN should
now be set if transmissions are needed. TXIF
and TXIE may be set if transmit interrupts are
desired. Remain in PRI_RUN or PRI_IDLE until
communications are complete. Clear TXEN and
return to step 2.
FIGURE 16-9: SEND BREAK CHARACTER SEQUENCE
Write to TXREG
BRG Output
(Shift Clock)
Start Bit Bit 0 Bit 1 Bit 11 Stop Bit
Break
TXIF bit
TX (pin)
TRMT bit
SENDB
Dummy Write PIC18F1220/1320
DS39605F-page 148 © 2007 Microchip Technology Inc.
16.4 EUSART Synchronous Master
Mode
The Synchronous Master mode is entered by setting
the CSRC bit (TXSTA<7>). In this 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 bit,
SYNC (TXSTA<4>). In addition, enable bit, SPEN
(RCSTA<7>), is set in order to configure the RB1/AN5/
TX/CK/INT1 and RB4/AN6/RX/DT/KBI0 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. Clock polarity is
selected with the SCKP bit (BAUDCTL<5>); setting
SCKP sets the Idle state on CK as high, while clearing
the bit sets the Idle state as low. This option is provided
to support Microwire devices with this module.
16.4.1 EUSART SYNCHRONOUS MASTER
TRANSMISSION
The EUSART transmitter block diagram is shown in
Figure 16-2. The heart of the transmitter is the Transmit
(Serial) Shift Register (TSR). The shift register obtains
its data from the Read/Write Transmit Buffer register,
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the last
bit has been transmitted from the previous load. As
soon as the last bit is transmitted, the TSR is loaded
with new data from the TXREG (if available).
Once the TXREG register transfers the data to the TSR
register (occurs in one TCYCLE), the TXREG is empty
and interrupt bit, TXIF (PIR1<4>), is set. The interrupt
can be enabled/disabled by setting/clearing enable bit,
TXIE (PIE1<4>). Flag bit, TXIF, will be set, regardless
of the state of enable bit, TXIE and cannot be cleared
in software. It will reset only when new data is loaded
into the TXREG register.
While flag bit, TXIF, indicates the status of the TXREG
register, another bit, TRMT (TXSTA<1>), shows the
status of the TSR register. TRMT is a read-only bit,
which is set when the TSR is empty. No interrupt logic is
tied to this bit, so the user has to poll this bit in order to
determine if the TSR register is empty. The TSR is not
mapped in data memory, so it is not available to the user.
To set up a Synchronous Master Transmission:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the synchronous master serial port by
setting bits SYNC, SPEN and CSRC.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set bit TX9.
5. Enable the transmission by setting bit TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Start transmission by loading data to the TXREG
register.
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
FIGURE 16-10: SYNCHRONOUS TRANSMISSION
bit 0 bit 1 bit 7
Word 1
Q1 Q2 Q3Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3Q4 Q1Q2 Q3Q4 Q1 Q2Q3Q4 Q1 Q2Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
bit 2 bit 0 bit 1 bit 7 RB4/AN6/RX/
RB1/AN5/TX/
Write to
TXREG Reg
TXIF bit
(Interrupt Flag)
TXEN bit ‘1’ ‘1’
Word 2
TRMT bit
Write Word 1 Write Word 2
Note: Sync Master mode, SPBRG = 0, continuous transmission of two 8-bit words.
DT/KBI0 pin
CK/INT1 pin
RB1/AN5/TX/
CK/INT1 pin
(SCKP = 0)
(SCKP = 1)© 2007 Microchip Technology Inc. DS39605F-page 149
PIC18F1220/1320
FIGURE 16-11: SYNCHRONOUS TRANSMISSION (THROUGH TXEN)
TABLE 16-7: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER TRANSMISSION
RB4/AN6/RX/DT/KBI0 pin
RB1/AN5/TX/CK/INT1 pin
Write to
TXREG reg
TXIF bit
TRMT bit
bit 0 bit 1 bit 2 bit 6 bit 7
TXEN bit
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG EUSART Transmit Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented, read as ‘0’. Shaded cells are not used for synchronous master transmission.PIC18F1220/1320
DS39605F-page 150 © 2007 Microchip Technology Inc.
16.4.2 EUSART SYNCHRONOUS MASTER
RECEPTION
Once Synchronous mode is selected, reception is
enabled by setting either the Single Receive Enable bit,
SREN (RCSTA<5>), or the Continuous Receive
Enable bit, CREN (RCSTA<4>). Data is sampled on the
RB4/AN6/RX/DT/KBI0 pin on the falling edge of the
clock.
If enable bit, SREN, is set, only a single word is
received. If enable bit, CREN, is set, the reception is
continuous until CREN is cleared. If both bits are set,
then CREN takes precedence.
To set up a Synchronous Master Reception:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the synchronous master serial port by
setting bits SYNC, SPEN and CSRC.
3. Ensure bits CREN and SREN are clear.
4. If interrupts are desired, set enable bit RCIE.
5. If 9-bit reception is desired, set bit RX9.
6. If a single reception is required, set bit SREN.
For continuous reception, set bit CREN.
7. Interrupt flag bit, RCIF, will be set when reception
is complete and an interrupt will be generated if
the enable bit, RCIE, was set.
8. Read the RCSTA register to get the 9th 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
bit CREN.
11. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
FIGURE 16-12: SYNCHRONOUS RECEPTION (MASTER MODE, SREN)
CREN bit
RB4/AN6/RX/
RB1/AN5/TX/
Write to
bit SREN
SREN bit
RCIF bit
(Interrupt)
Read
RXREG
Q2 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
‘0’
bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7
‘0’
Q1 Q2 Q3 Q4
Note: Timing diagram demonstrates Sync Master mode with bit SREN = 1 and bit BRGH = 0.
RB1/AN5/TX/
CK/INT1 pin
CK/INT1 pin
DT/KBI0 pin
(SCKP = 0)
(SCKP = 1)© 2007 Microchip Technology Inc. DS39605F-page 151
PIC18F1220/1320
TABLE 16-8: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER 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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG EUSART Receive Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented, read as ‘0’. Shaded cells are not used for synchronous master reception.PIC18F1220/1320
DS39605F-page 152 © 2007 Microchip Technology Inc.
16.5 EUSART Synchronous
Slave Mode
Synchronous Slave mode is entered by clearing bit,
CSRC (TXSTA<7>). This mode differs from the
Synchronous Master mode in that the shift clock is
supplied externally at the RB1/AN5/TX/CK/INT1 pin
(instead of being supplied internally in Master mode).
This allows the device to transfer or receive data while
in any low-power mode.
16.5.1 EUSART 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 the TXREG
register.
c) Flag bit, TXIF, will not be set.
d) When the first word has been shifted out of TSR,
the TXREG register will transfer the second
word to the TSR and flag bit, TXIF, will now be
set.
e) If enable bit, TXIE, is set, the interrupt will wake
the chip from Sleep. If the global interrupt is
enabled, the program will branch to the interrupt
vector.
To set up a Synchronous Slave Transmission:
1. Enable the synchronous slave serial port by
setting bits SYNC and SPEN and clearing bit
CSRC.
2. Clear bits CREN and SREN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set bit TX9.
5. Enable the transmission by setting enable bit
TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Start transmission by loading data to the TXREG
register.
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 16-9: REGISTERS ASSOCIATED WITH SYNCHRONOUS SLAVE TRANSMISSION
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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
TXREG EUSART Transmit Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented, read as ‘0’. Shaded cells are not used for synchronous slave transmission.© 2007 Microchip Technology Inc. DS39605F-page 153
PIC18F1220/1320
16.5.2 EUSART SYNCHRONOUS SLAVE
RECEPTION
The operation of the Synchronous Master and Slave
modes is identical, except in the case of Sleep, or any
Idle mode and bit SREN, which is a “don’t care” in
Slave mode.
If receive is enabled by setting the CREN bit prior to
entering Sleep or any Idle mode, then a word may be
received while in this low-power mode. Once the word
is received, the RSR register will transfer the data to the
RCREG register; if the RCIE enable bit is set, the interrupt
generated will wake the chip from low-power
mode. If the global interrupt is enabled, the program will
branch to the interrupt vector.
To set up a Synchronous Slave Reception:
1. Enable the synchronous master serial port by
setting bits SYNC and SPEN and clearing bit
CSRC.
2. If interrupts are desired, set enable bit RCIE.
3. If 9-bit reception is desired, set bit RX9.
4. To enable reception, set enable bit CREN.
5. Flag bit, RCIF, will be set when reception is
complete. An interrupt will be generated if
enable bit, RCIE, was set.
6. Read the RCSTA register to get the 9th 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
bit CREN.
9. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 16-10: 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
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 0000 000x
RCREG EUSART Receive Register 0000 0000 0000 0000
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 0000 0010
BAUDCTL — RCIDL — SCKP BRG16 — WUE ABDEN -1-1 0-00 -1-1 0-00
SPBRGH Baud Rate Generator Register High Byte 0000 0000 0000 0000
SPBRG Baud Rate Generator Register Low Byte 0000 0000 0000 0000
Legend: x = unknown, – = unimplemented, read as ‘0’. Shaded cells are not used for synchronous slave reception.PIC18F1220/1320
DS39605F-page 154 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 155
PIC18F1220/1320
17.0 10-BIT ANALOG-TO-DIGITAL
CONVERTER (A/D) MODULE
The Analog-to-Digital (A/D) converter module has
seven inputs for the PIC18F1220/1320 devices. This
module allows conversion of an analog input signal to
a corresponding 10-bit digital number.
A new feature for the A/D converter is the addition of
programmable acquisition time. This feature allows the
user to select a new channel for conversion and to set
the GO/DONE bit immediately. When the GO/DONE bit
is set, the selected channel is sampled for the programmed
acquisition time before a conversion is actually
started. This removes the firmware overhead that
may have been required to allow for an acquisition
(sampling) period (see Register 17-3 and Section 17.3
“Selecting and Configuring Automatic Acquisition
Time”).
The module has five registers:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register 0 (ADCON0)
• A/D Control Register 1 (ADCON1)
• A/D Control Register 2 (ADCON2)
The ADCON0 register, shown in Register 17-1,
controls the operation of the A/D module. The
ADCON1 register, shown in Register 17-2, configures
the functions of the port pins. The ADCON2 register,
shown in Register 17-3, configures the A/D clock
source, programmed acquisition time and justification.
REGISTER 17-1: ADCON0: A/D CONTROL REGISTER 0
R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
VCFG1 VCFG0 — CHS2 CHS1 CHS0 GO/DONE ADON
bit 7 bit 0
bit 7-6 VCFG<1:0>: Voltage Reference Configuration bits
bit 5 Unimplemented: Read as ‘0’
bit 4-2 CHS2:CHS0: Analog Channel Select bits
000 = Channel 0 (AN0)
001 = Channel 1 (AN1)
010 = Channel 2 (AN2)
011 = Channel 3 (AN3)
100 = Channel 4 (AN4)
101 = Channel 5 (AN5)
110 = Channel 6 (AN6)
111 = Unimplemented(1)
bit 1 GO/DONE: A/D Conversion Status bit
When ADON = 1:
1 = A/D conversion in progress
0 = A/D Idle
bit 0 ADON: A/D On bit
1 = A/D converter module is enabled
0 = A/D converter module is disabled
Note 1: Performing a conversion on unimplemented channels returns full-scale results.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
A/D VREF+ A/D VREF-
00 AVDD AVSS
01 External VREF+ AVSS
10 AVDD External VREF-
11 External VREF+ External VREF-PIC18F1220/1320
DS39605F-page 156 © 2007 Microchip Technology Inc.
REGISTER 17-2: ADCON1: A/D CONTROL REGISTER 1
U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 PCFG6: A/D Port Configuration bit – AN6
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 5 PCFG5: A/D Port Configuration bit – AN5
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 4 PCFG4: A/D Port Configuration bit – AN4
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 3 PCFG3: A/D Port Configuration bit – AN3
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 2 PCFG2: A/D Port Configuration bit – AN2
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 1 PCFG1: A/D Port Configuration bit – AN1
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
bit 0 PCFG0: A/D Port Configuration bit – AN0
1 = Pin configured as a digital port
0 = Pin configured as an analog channel – digital input disabled and reads ‘0’
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown© 2007 Microchip Technology Inc. DS39605F-page 157
PIC18F1220/1320
REGISTER 17-3: ADCON2: A/D CONTROL REGISTER 2
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0
bit 7 bit 0
bit 7 ADFM: A/D Result Format Select bit
1 = Right justified
0 = Left justified
bit 6 Unimplemented: Read as ‘0’
bit 5-3 ACQT2:ACQT0: A/D Acquisition Time Select bits
000 = 0 TAD(1)
001 = 2 TAD
010 = 4 TAD
011 = 6 TAD
100 = 8 TAD
101 = 12 TAD
110 = 16 TAD
111 = 20 TAD
bit 2-0 ADCS2:ADCS0: A/D Conversion Clock Select bits
000 = FOSC/2
001 = FOSC/8
010 = FOSC/32
011 = FRC (clock derived from A/D RC oscillator)(1)
100 = FOSC/4
101 = FOSC/16
110 = FOSC/64
111 = FRC (clock derived from A/D RC oscillator)(1)
Note: If the A/D FRC clock source is selected, a delay of one TCY (instruction cycle) is
added before the A/D clock starts. This allows the SLEEP instruction to be executed
before starting a conversion.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 158 © 2007 Microchip Technology Inc.
The analog reference voltage is software selectable to
either the device’s positive and negative supply voltage
(AVDD and AVSS), or the voltage level on the
RA3/AN3/VREF+ and RA2/AN2/VREF- pins.
The A/D converter has a unique feature of being able
to operate while the device is in Sleep mode. To operate
in Sleep, the A/D conversion clock must be derived
from the A/D’s internal RC oscillator.
The output of the sample and hold is the input into the
converter, which generates the result via successive
approximation.
A device Reset forces all registers to their Reset state.
This forces the A/D module to be turned off and any
conversion in progress is aborted.
Each port pin associated with the A/D converter can be
configured as an analog input, or as a digital I/O. The
ADRESH and ADRESL registers contain the result of
the A/D conversion. When the A/D conversion is complete,
the result is loaded into the ADRESH/ADRESL
registers, 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 17-1.
FIGURE 17-1: A/D BLOCK DIAGRAM
(Input Voltage)
VAIN
VREFH
Reference
Voltage
AVDD
VCFG1:VCFG0
CHS2:CHS0
AN6(1)
AN5
AN4
AN3/VREF+
AN2/VREFAN1
AN0
111
110
101
100
011
010
001
000
10-bit
Converter
VREFL
AVSS
A/D
Note 1: I/O pins have diode protection to VDD and VSS.
0x
1x
x1
x0
AVDD© 2007 Microchip Technology Inc. DS39605F-page 159
PIC18F1220/1320
The value in the ADRESH/ADRESL registers is not
modified for a Power-on Reset. The ADRESH/ADRESL
registers will contain unknown data after a Power-on
Reset.
After the A/D module has been configured as desired,
the selected channel must be acquired before the conversion
is started. The analog input channels must
have their corresponding TRIS bits selected as an
input. To determine acquisition time, see Section 17.1
“A/D Acquisition Requirements”. After this acquisition
time has elapsed, the A/D conversion can be
started. An acquisition time can be programmed to
occur between setting the GO/DONE bit and the actual
start of the conversion.
To do 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 acquisition time (ADCON2)
• Select A/D conversion clock (ADCON2)
• Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired):
• Clear ADIF bit
• Set ADIE bit
• Set GIE bit
3. Wait the required acquisition time (if required).
4. Start conversion:
• Set GO/DONE bit (ADCON0 register)
5. Wait for A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared
OR
• Waiting for the A/D interrupt
6. Read A/D Result registers (ADRESH:ADRESL);
clear bit, ADIF, if required.
7. For the next conversion, go to step 1 or step 2,
as required. The A/D conversion time per bit is
defined as TAD. A minimum wait of 2 TAD is
required before the next acquisition starts.
FIGURE 17-2: ANALOG INPUT MODEL
VAIN CPIN
Rs ANx
5 pF
VDD
VT = 0.6V
VT = 0.6V ILEAKAGE
RIC ≤ 1k
Sampling
Switch
SS RSS
CHOLD = 120 pF
VSS
6V
Sampling Switch
5V
4V
3V
2V
5 6 7 8 9 10 11
(kΩ)
VDD
± 500 nA
Legend: CPIN = input capacitance
VT = threshold voltage
ILEAKAGE = leakage current at the pin due to
various junctions
RIC = interconnect resistance
SS = sampling switch
CHOLD = sample/hold capacitance (from DAC)
RSS = sampling switch resistancePIC18F1220/1320
DS39605F-page 160 © 2007 Microchip Technology Inc.
17.1 A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy,
the charge holding capacitor (CHOLD) must be allowed
to fully charge to the input channel voltage level. The
analog input model is shown in Figure 17-2. The
source impedance (RS) and the internal sampling
switch (RSS) impedance directly affect the time
required to charge the capacitor CHOLD. The sampling
switch (RSS) impedance varies over the device voltage
(VDD). 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Ω. After the analog input channel is
selected (changed), the channel must be sampled for
at least the minimum acquisition time before starting a
conversion.
To calculate the minimum acquisition time,
Equation 17-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.
Example 17-1 shows the calculation of the minimum
required acquisition time, TACQ. This calculation is
based on the following application system
assumptions:
CHOLD = 120 pF
Rs = 2.5 kΩ
Conversion Error ≤ 1/2 LSb
VDD = 5V → RSS = 7 kΩ
Temperature = 50°C (system max.)
VHOLD = 0V @ time = 0
17.2 A/D VREF+ and VREF- References
If external voltage references are used instead of the
internal AVDD and AVSS sources, the source impedance
of the VREF+ and VREF- voltage sources must be
considered. During acquisition, currents supplied by
these sources are insignificant. However, during
conversion, the A/D module sinks and sources current
through the reference sources.
In order to maintain the A/D accuracy, the voltage
reference source impedances should be kept low to
reduce voltage changes. These voltage changes occur
as reference currents flow through the reference
source impedance. The maximum recommended
impedance of the VREF+ and VREF- external
reference voltage sources is 250Ω.
EQUATION 17-1: ACQUISITION TIME
EQUATION 17-2: A/D MINIMUM CHARGING TIME
EXAMPLE 17-1: CALCULATING THE MINIMUM REQUIRED ACQUISITION TIME
Note: When the conversion is started, the
holding capacitor is disconnected from the
input pin.
TACQ = Amplifier Settling Time + Holding Capacitor Charging Time + Temperature Coefficient
= TAMP + TC + TCOFF
VHOLD = (ΔVREF – (ΔVREF/2048)) • (1 – e(-TC/CHOLD(RIC + RSS + RS)))
or
TC = -(CHOLD)(RIC + RSS + RS) ln(1/2048)
TACQ =TAMP + TC + TCOFF
TAMP = 5 μs
TCOFF = (Temp – 25ºC)(0.05 μs/ºC)
(50ºC – 25ºC)(0.05 μs/ºC)
1.25 μs
Temperature coefficient is only required for temperatures > 25ºC. Below 25ºC, TCOFF = 0 μs.
TC = -(CHOLD)(RIC + RSS + RS) ln(1/2047) μs
-(120 pF) (1 kΩ + 7 kΩ + 2.5 kΩ) ln(0.0004883) μs
9.61 μs
TACQ = 5 μs + 1.25 μs + 9.61 μs
12.86 μs© 2007 Microchip Technology Inc. DS39605F-page 161
PIC18F1220/1320
17.3 Selecting and Configuring
Automatic Acquisition Time
The ADCON2 register allows the user to select an
acquisition time that occurs each time the GO/DONE
bit is set.
When the GO/DONE bit is set, sampling is stopped and
a conversion begins. The user is responsible for ensuring
the required acquisition time has passed between
selecting the desired input channel and setting the
GO/DONE bit. This occurs when the ACQT2:ACQT0
bits (ADCON2<5:3>) remain in their Reset state (‘000’)
and is compatible with devices that do not offer
programmable acquisition times.
If desired, the ACQT bits can be set to select a
programmable acquisition time for the A/D module.
When the GO/DONE bit is set, the A/D module continues
to sample the input for the selected acquisition
time, then automatically begins a conversion. Since the
acquisition time is programmed, there may be no need
to wait for an acquisition time between selecting a
channel and setting the GO/DONE bit.
In either case, when the conversion is completed, the
GO/DONE bit is cleared, the ADIF flag is set and the
A/D begins sampling the currently selected channel
again. If an acquisition time is programmed, there is
nothing to indicate if the acquisition time has ended or
if the conversion has begun.
17.4 Selecting the A/D Conversion
Clock
The A/D conversion time per bit is defined as TAD. The
A/D conversion requires 11 TAD per 10-bit conversion.
The source of the A/D conversion clock is software
selectable. There are seven possible options for TAD:
• 2 TOSC
• 4 TOSC
• 8 TOSC
• 16 TOSC
• 32 TOSC
• 64 TOSC
• Internal RC oscillator
For correct A/D conversions, the A/D conversion clock
(TAD) must be as short as possible, but greater than the
minimum TAD (approximately 2 μs, see parameter 130
for more information).
Table 17-1 shows the resultant TAD times derived from
the device operating frequencies and the A/D clock
source selected.
TABLE 17-1: TAD vs. DEVICE OPERATING FREQUENCIES
AD Clock Source (TAD) Maximum Device Frequency
Operation ADCS2:ADCS0 PIC18F1220/1320 PIC18LF1220/1320(4)
2 TOSC 000 1.25 MHz 666 kHz
4 TOSC 100 2.50 MHz 1.33 MHz
8 TOSC 001 5.00 MHz 2.66 MHz
16 TOSC 101 10.0 MHz 5.33 MHz
32 TOSC 010 20.0 MHz 10.65 MHz
64 TOSC 110 40.0 MHz 21.33 MHz
RC(3) x11 1.00 MHz(1) 1.00 MHz(2)
Note 1: The RC source has a typical TAD time of 4 μs.
2: The RC source has a typical TAD time of 6 μs.
3: 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.
4: Low-power devices only.PIC18F1220/1320
DS39605F-page 162 © 2007 Microchip Technology Inc.
17.5 Operation in Low-Power Modes
The selection of the automatic acquisition time and the
A/D conversion clock is determined, in part, by the lowpower
mode clock source and frequency while in a
low-power mode.
If the A/D is expected to operate while the device is
in a low-power mode, the ACQT2:ACQT0 and
ADCS2:ADCS0 bits in ADCON2 should be updated in
accordance with the low-power mode clock that will be
used. After the low-power mode is entered (either of
the Run modes), an A/D acquisition or conversion may
be started. Once an acquisition or conversion is
started, the device should continue to be clocked by the
same low-power mode clock source until the conversion
has been completed. If desired, the device may be
placed into the corresponding low-power (ANY)_IDLE
mode during the conversion.
If the low-power mode clock frequency is less than
1 MHz, the A/D RC clock source should be selected.
Operation in the Low-Power Sleep mode requires the
A/D RC clock to be selected. If bits, ACQT2:ACQT0, are
set to ‘000’ and a conversion is started, the conversion
will be delayed one instruction cycle to allow execution
of the SLEEP instruction and entry to Low-Power Sleep
mode. The IDLEN and SCS bits in the OSCCON register
must have already been cleared prior to starting the
conversion.
17.6 Configuring Analog Port Pins
The ADCON1, TRISA and TRISB registers all configure
the A/D port pins. The port pins needed 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.
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, all pins
configured as analog input channels 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 be accurately
converted.
2: Analog levels on any pin defined as a
digital input may cause the digital input
buffer to consume current out of the
device’s specification limits.© 2007 Microchip Technology Inc. DS39605F-page 163
PIC18F1220/1320
17.7 A/D Conversions
Figure 17-3 shows the operation of the A/D converter
after the GO bit has been set and the ACQT2:ACQT0
bits are cleared. A conversion is started after the following
instruction to allow entry into Low-Power Sleep
mode before the conversion begins.
Figure 17-4 shows the operation of the A/D converter
after the GO bit has been set and the ACQT2:ACQT0
bits are set to ‘010’ and selecting a 4 TAD acquisition
time before the conversion starts.
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. This means 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 completed or aborted, a
2 TAD wait is required before the next acquisition can
be started. After this wait, acquisition on the selected
channel is automatically started.
FIGURE 17-3: A/D CONVERSION TAD CYCLES (ACQT<2:0> = 000, TACQ = 0)
FIGURE 17-4: A/D CONVERSION TAD CYCLES (ACQT<2:0> = 010, TACQ = 4 TAD)
Note: The GO/DONE bit should NOT be set in
the same instruction that turns on the A/D.
TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD11
Set GO bit
Holding capacitor is disconnected from analog input (typically 100 ns)
TCY – TAD TAD9 TAD10
Next Q4: ADRESH/ADRESL is loaded, GO bit is cleared,
ADIF bit is set, holding capacitor is connected to analog input.
Conversion Starts
b9 b8 b7 b6 b5 b4 b3 b2 b1 b0
1 2 3 4 5 6 7 8 11
Set GO bit
(Holding capacitor is disconnected)
9 10
Next Q4: ADRESH:ADRESL is loaded, GO bit is cleared,
ADIF bit is set, holding capacitor is reconnected to analog input.
Conversion Starts
1 2 3 4
(Holding capacitor continues
acquiring input)
TACQT Cycles TAD Cycles
Automatic
Acquisition
Time
b9 b8 b7 b6 b5 b4 b3 b2 b1 b0PIC18F1220/1320
DS39605F-page 164 © 2007 Microchip Technology Inc.
17.8 Use of the CCP1 Trigger
An A/D conversion can be started by the “special event
trigger” of the CCP1 module. This requires that the
CCP1M3:CCP1M0 bits (CCP1CON<3:0>) be programmed
as ‘1011’ and that the A/D module is enabled
(ADON bit is set). When the trigger occurs, the
GO/DONE bit will be set, starting the A/D acquisition
and conversion and the Timer1 (or Timer3) counter will
be reset to zero. Timer1 (or Timer3) is reset to automatically
repeat the A/D acquisition period with minimal
software overhead (moving ADRESH/ADRESL to the
desired location). The appropriate analog input
channel must be selected and the minimum acquisition
period is either timed by the user, or an appropriate
TACQ time selected before the “special event trigger”
sets the GO/DONE bit (starts a conversion).
If the A/D module is not enabled (ADON is cleared), the
“special event trigger” will be ignored by the A/D
module, but will still reset the Timer1 (or Timer3)
counter.
TABLE 17-2: SUMMARY OF A/D REGISTERS
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 0000 0000 0000
PIR1 — ADIF RCIF TXIF — CCP1IF TMR2IF TMR1IF -000 -000 -000 -000
PIE1 — ADIE RCIE TXIE — CCP1IE TMR2IE TMR1IE -000 -000 -000 -000
IPR1 — ADIP RCIP TXIP — CCP1IP TMR2IP TMR1IP -111 -111 -111 -111
PIR2 OSCFIF — — EEIF — LVDIF TMR3IF — 0--0 -00- 0--0 -00-
PIE2 OSCFIE — — EEIE — LVDIE TMR3IE — 0--0 -00- 0--0 -00-
IPR2 OSCFIP — — EEIP — LVDIP TMR3IP — 1--1 -11- 1--1 -11-
ADRESH A/D Result Register High Byte xxxx xxxx uuuu uuuu
ADRESL A/D Result Register Low Byte xxxx xxxx uuuu uuuu
ADCON0 VCFG1 VCFG0 — CHS2 CHS1 CHS0 GO/DONE ADON 00-0 0000 00-0 0000
ADCON1 — PCFG6 PCFG5 PCFG4 PCFG3 PCFG2 PCFG1 PCFG0 -000 0000 -000 0000
ADCON2 ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 0-00 0000 0-00 0000
PORTA RA7(3) RA6(2) RA5(1) RA4 RA3 RA2 RA1 RA0 qq0x 0000 uu0u 0000
TRISA TRISA7(3) TRISA6(2) — PORTA Data Direction Register qq-1 1111 11-1 1111
PORTB Read PORTB pins, Write LATB Latch xxxx xxxx uuuu uuuu
TRISB PORTB Data Direction Register 1111 1111 1111 1111
LATB PORTB Output Data Latch xxxx xxxx uuuu uuuu
Legend: x = unknown, u = unchanged, q = depends on CONFIG1H<3:0>, – = unimplemented, read as ‘0’.
Shaded cells are not used for A/D conversion.
Note 1: RA5 port bit is available only as an input pin when the MCLRE bit in the configuration register is ‘0’.
2: RA6 and TRISA6 are available only when the primary oscillator mode selection offers RA6 as a port pin; otherwise, RA6
always reads ‘0’, TRISA6 always reads ‘1’ and writes to both are ignored (see CONFIG1H<3:0>).
3: RA7 and TRISA7 are available only when the internal RC oscillator is configured as the primary oscillator in
CONFIG1H<3:0>; otherwise, RA7 always reads ‘0’, TRISA7 always reads ‘1’ and writes to both are ignored.© 2007 Microchip Technology Inc. DS39605F-page 165
PIC18F1220/1320
18.0 LOW-VOLTAGE DETECT
In many applications, the ability to determine if the
device voltage (VDD) 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 a software programmable circuitry,
where a device voltage trip point can be specified.
When the voltage of the device becomes lower then 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 18-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 the time,
until the device voltage is no longer in valid operating
range, to shut down the system. Voltage point VB is the
minimum valid operating voltage specification. This
occurs at time TB. The difference, TB – TA, is the total
time for shutdown.
The block diagram for the LVD module is shown in
Figure 18-2 (following page). 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 than), the LVDIF bit is set.
Each node in the resistor 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 1.2V
internal reference voltage generated by the 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 18-2). The trip point is selected by
programming the LVDL3:LVDL0 bits (LVDCON<3:0>).
FIGURE 18-1: TYPICAL LOW-VOLTAGE DETECT APPLICATION
Time
Voltage
VA
VB
TA TB
Legend: VA = LVD trip point
VB = Minimum valid device
operating voltagePIC18F1220/1320
DS39605F-page 166 © 2007 Microchip Technology Inc.
FIGURE 18-2: LOW-VOLTAGE DETECT (LVD) BLOCK DIAGRAM
The LVD module has an additional feature that allows
the user to supply the trip voltage to the module from
an external source. This mode is enabled when bits,
LVDL3:LVDL0, are set to ‘1111’. In this state, the comparator
input is multiplexed from the external input pin,
LVDIN (Figure 18-3). This gives users flexibility,
because it allows them to configure the Low-Voltage
Detect interrupt to occur at any voltage in the valid
operating range.
FIGURE 18-3: LOW-VOLTAGE DETECT (LVD) WITH EXTERNAL INPUT BLOCK DIAGRAM
LVDIF
VDD
16-to-1 MUX
LVDEN
LVD Control
Register
Internally Generated
Reference Voltage
LVDIN
1.2V
LVD
EN
LVD Control
16-to-1 MUX
BGAP
BODEN
LVDEN
VxEN
LVDIN
Register
VDD
VDD
Externally Generated
Trip Point© 2007 Microchip Technology Inc. DS39605F-page 167
PIC18F1220/1320
18.1 Control Register
The Low-Voltage Detect Control register controls the
operation of the Low-Voltage Detect circuitry.
REGISTER 18-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 the 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
1111 = External analog input is used (input comes from the LVDIN pin)
1110 = 4.04V-5.15V
1101 = 3.76V-4.79V
1100 = 3.58V-4.56V
1011 = 3.41V-4.34V
1010 = 3.23V-4.11V
1001 = 3.14V-4.00V
1000 = 2.96V-3.77V
0111 = 2.70V-3.43V
0110 = 2.53V-3.21V
0101 = 2.43V-3.10V
0100 = 2.25V-2.86V
0011 = 2.16V-2.75V
0010 = 1.99V-2.53V
0001 = Reserved
0000 = Reserved
Note: LVDL3:LVDL0 modes, which result in a trip point below the valid operating voltage
of the device, are not tested.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknownPIC18F1220/1320
DS39605F-page 168 © 2007 Microchip Technology Inc.
18.2 Operation
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.
The following steps are needed to set up 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, until the LVD module has
stabilized (clear the LVDIF bit).
6. Enable the LVD interrupt (set the LVDIE and the
GIE bits).
Figure 18-4 shows typical waveforms that the LVD
module may be used to detect.
FIGURE 18-4: LOW-VOLTAGE DETECT WAVEFORMS
VLVD
VDD
LVDIF
VLVD
VDD
Enable LVD
Internally Generated TIVRST
LVDIF may not be set.
Enable LVD
LVDIF
LVDIF cleared in software
LVDIF cleared in software
LVDIF cleared in software,
CASE 1:
CASE 2:
LVDIF remains set since LVD condition still exists
Reference Stable
Internally Generated
Reference Stable
TIVRST© 2007 Microchip Technology Inc. DS39605F-page 169
PIC18F1220/1320
18.2.1 REFERENCE VOLTAGE SET POINT
The internal reference voltage of the LVD module may
be used by other internal circuitry (the programmable
Brown-out Reset). If these circuits are disabled (lower
current consumption), the reference voltage circuit
requires a time to become stable before a low-voltage
condition can be reliably detected. This time is invariant
of system clock speed. This start-up 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 waveform in Figure 18-4.
18.2.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.
18.3 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 wakeup
from Sleep. Device execution will continue from the
interrupt vector address if interrupts have been globally
enabled.
18.4 Effects of a Reset
A device Reset forces all registers to their Reset state.
This forces the LVD module to be turned off. PIC18F1220/1320
DS39605F-page 170 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 171
PIC18F1220/1320
19.0 SPECIAL FEATURES OF
THE CPU
PIC18F1220/1320 devices include several features
intended to maximize system reliability, minimize cost
through elimination of external components and offer
code protection. These are:
• Oscillator Selection
• Resets:
- Power-on Reset (POR)
- Power-up Timer (PWRT)
- Oscillator Start-up Timer (OST)
- Brown-out Reset (BOR)
• Interrupts
• Watchdog Timer (WDT)
• Fail-Safe Clock Monitor
• Two-Speed Start-up
• Code Protection
• ID Locations
• In-Circuit Serial Programming
Several oscillator options are available to allow the part
to fit the application. The RC oscillator option saves
system cost, while the LP crystal option saves power.
These are discussed in detail in Section 2.0 “Oscillator
Configurations”.
A complete discussion of device Resets and interrupts
is available in previous sections of this data sheet.
In addition to their Power-up and Oscillator Start-up
Timers provided for Resets, PIC18F1220/1320 devices
have a Watchdog Timer, which is either permanently
enabled via the configuration bits, or software
controlled (if configured as disabled).
The inclusion of an internal RC oscillator also provides
the additional benefits of a Fail-Safe Clock Monitor
(FSCM) and Two-Speed Start-up. FSCM provides for
background monitoring of the peripheral clock and
automatic switchover in the event of its failure. TwoSpeed
Start-up enables code to be executed almost
immediately on start-up, while the primary clock source
completes its start-up delays.
All of these features are enabled and configured by
setting the appropriate configuration register bits.
19.1 Configuration Bits
The configuration bits can be programmed (read as
‘0’), or left unprogrammed (read as ‘1’), to select various
device configurations. These bits are mapped
starting at program memory location 300000h.
The user will note that address 300000h is beyond the
user program memory space. In fact, it belongs to the
configuration memory space (300000h-3FFFFFh),
which can only be accessed using table reads and
table writes.
Programming the configuration registers is done in a
manner similar to programming the Flash memory. The
EECON1 register WR bit starts a self-timed write to the
configuration register. In normal operation mode, a
TBLWT instruction, with the TBLPTR pointing to the
configuration register, sets up the address and the data
for the configuration register write. Setting the WR bit
starts a long write to the configuration register. The configuration
registers are written a byte at a time. To write
or erase a configuration cell, a TBLWT instruction can
write a ‘1’ or a ‘0’ into the cell. For additional details on
Flash programming, refer to Section 6.5 “Writing to
Flash Program Memory”.
TABLE 19-1: CONFIGURATION BITS AND DEVICE IDS
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Default/
Unprogrammed
Value
300001h CONFIG1H IESO FSCM — — FOSC3 FOSC2 FOSC1 FOSC0 11-- 1111
300002h CONFIG2L — — — — BORV1 BORV0 BOR PWRTEN ---- 1111
300003h CONFIG2H — — — WDTPS3 WDTPS2 WDTPS1 WDTPS0 WDT ---1 1111
300005h CONFIG3H MCLRE — — — — — — — 1--- ----
300006h CONFIG4L DEBUG — — — — LVP — STVR 1--- -1-1
300008h CONFIG5L — — — — — — CP1 CP0 ---- --11
300009h CONFIG5H CPD CPB — — — — — — 11-- ----
30000Ah CONFIG6L — — — — — — WRT1 WRT0 ---- --11
30000Bh CONFIG6H WRTD WRTB WRTC — — — — — 111- ----
30000Ch CONFIG7L — — — — — — EBTR1 EBTR0 ---- --11
30000Dh CONFIG7H — EBTRB — — — — — — -1-- ----
3FFFFEh DEVID1(1) DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0 xxxx xxxx(1)
3FFFFFh DEVID2(1) DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3 0000 0111
Legend: x = unknown, u = unchanged, – = unimplemented. Shaded cells are unimplemented, read as ‘0’.
Note 1: See Register 19-14 for DEVID1 values. DEVID registers are read-only and cannot be programmed by the user.PIC18F1220/1320
DS39605F-page 172 © 2007 Microchip Technology Inc.
REGISTER 19-1: CONFIG1H: CONFIGURATION REGISTER 1 HIGH (BYTE ADDRESS 300001h)
R/P-1 R/P-1 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1
IESO FSCM — — FOSC3 FOSC2 FOSC1 FOSC0
bit 7 bit 0
bit 7 IESO: Internal External Switchover bit
1 = Internal External Switchover mode enabled
0 = Internal External Switchover mode disabled
bit 6 FSCM: Fail-Safe Clock Monitor Enable bit
1 = Fail-Safe Clock Monitor enabled
0 = Fail-Safe Clock Monitor disabled
bit 5-4 Unimplemented: Read as ‘0’
bit 3-0 FOSC<3:0>: Oscillator Selection bits
11xx = External RC oscillator, CLKO function on RA6
1001 = Internal RC oscillator, CLKO function on RA6 and port function on RA7
1000 = Internal RC oscillator, port function on RA6 and port function on RA7
0111 = External RC oscillator, port function on RA6
0110 = HS oscillator, PLL enabled (clock frequency = 4 x FOSC1)
0101 = EC oscillator, port function on RA6
0100 = EC oscillator, CLKO function on RA6
0010 = HS oscillator
0001 = XT oscillator
0000 = LP oscillator
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state© 2007 Microchip Technology Inc. DS39605F-page 173
PIC18F1220/1320
REGISTER 19-2: CONFIG2L: CONFIGURATION REGISTER 2 LOW (BYTE ADDRESS 300002h)
U-0 U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1
— — — — BORV1 BORV0 BOR PWRTEN
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3-2 BORV1:BORV0: Brown-out Reset Voltage bits
11 = Reserved
10 = VBOR set to 2.7V
01 = VBOR set to 4.2V
00 = VBOR set to 4.5V
bit 1 BOR: Brown-out Reset Enable bit(1)
1 = Brown-out Reset enabled
0 = Brown-out Reset disabled
bit 0 PWRTEN: Power-up Timer Enable bit(1)
1 = PWRT disabled
0 = PWRT enabled
Note 1: The Power-up Timer is decoupled from Brown-out Reset, allowing these features to
be independently controlled.
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed statePIC18F1220/1320
DS39605F-page 174 © 2007 Microchip Technology Inc.
REGISTER 19-3: CONFIG2H: CONFIGURATION REGISTER 2 HIGH (BYTE ADDRESS 300003h)
U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1 R/P-1
— — — WDTPS3 WDTPS2 WDTPS1 WDTPS0 WDTEN
bit 7 bit 0
bit 7-5 Unimplemented: Read as ‘0’
bit 4-1 WDTPS<3:0>: Watchdog Timer Postscale Select bits
1111 = 1:32,768
1110 = 1:16,384
1101 = 1:8,192
1100 = 1:4,096
1011 = 1:2,048
1010 = 1:1,024
1001 = 1:512
1000 = 1:256
0111 = 1:128
0110 = 1:64
0101 = 1:32
0100 = 1:16
0011 = 1:8
0010 = 1:4
0001 = 1:2
0000 = 1:1
bit 0 WDT: Watchdog Timer Enable bit
1 = WDT enabled
0 = WDT disabled (control is placed on the SWDTEN bit)
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state© 2007 Microchip Technology Inc. DS39605F-page 175
PIC18F1220/1320
REGISTER 19-4: CONFIG3H: CONFIGURATION REGISTER 3 HIGH (BYTE ADDRESS 300005h)
REGISTER 19-5: CONFIG4L: CONFIGURATION REGISTER 4 LOW (BYTE ADDRESS 300006h)
R/P-1 U-0 U-0 U-0 U-0 U-0 U-0 U-0
MCLRE — — — — — — —
bit 7 bit 0
bit 7 MCLRE: MCLR Pin Enable bit
1 = MCLR pin enabled, RA5 input pin disabled
0 = RA5 input pin enabled, MCLR disabled
bit 6-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
R/P-1 U-0 U-0 U-0 U-0 R/P-1 U-0 R/P-1
DEBUG — — — — LVP — STVR
bit 7 bit 0
bit 7 DEBUG: Background Debugger Enable bit (see note)
1 = Background debugger disabled, RB6 and RB7 configured as general purpose I/O pins
0 = Background debugger enabled, RB6 and RB7 are dedicated to In-Circuit Debug
bit 6-3 Unimplemented: Read as ‘0’
bit 2 LVP: Low-Voltage ICSP Enable bit
1 = Low-Voltage ICSP enabled
0 = Low-Voltage ICSP disabled
bit 1 Unimplemented: Read as ‘0’
bit 0 STVR: Stack Full/Underflow Reset Enable bit
1 = Stack full/underflow will cause Reset
0 = Stack full/underflow will not cause Reset
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
Note: The Timer1 oscillator shares the T1OSI and T1OSO pins with the PGD and PGC
pins used for programming and debugging.
When using the Timer1 oscillator, In-Circuit Serial Programming (ICSP) may not
function correctly (high voltage or low voltage), or the In-Circuit Debugger (ICD) may
not communicate with the controller. As a result of using either ICSP or ICD, the
Timer1 crystal may be damaged.
If ICSP or ICD operations are required, the crystal should be disconnected from the
circuit (disconnect either lead) or installed after programming. The oscillator loading
capacitors may remain in-circuit during ICSP or ICD operation. PIC18F1220/1320
DS39605F-page 176 © 2007 Microchip Technology Inc.
REGISTER 19-6: CONFIG5L: CONFIGURATION REGISTER 5 LOW (BYTE ADDRESS 300008h)
REGISTER 19-7: CONFIG5H: CONFIGURATION REGISTER 5 HIGH (BYTE ADDRESS 300009h)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — — — CP1 CP0
bit 7 bit 0
bit 7-2 Unimplemented: Read as ‘0’
bit 1 CP1: Code Protection bit (PIC18F1320)
1 = Block 1 (001000-001FFFh) not code-protected
0 = Block 1 (001000-001FFFh) code-protected
bit 0 CP0: Code Protection bit (PIC18F1320)
1 = Block 0 (00200-000FFFh) not code-protected
0 = Block 0 (00200-000FFFh) code-protected
bit 1 CP1: Code Protection bit (PIC18F1220)
1 = Block 1 (000800-000FFFh) not code-protected
0 = Block 1 (000800-000FFFh) code-protected
bit 0 CP0: Code Protection bit (PIC18F1220)
1 = Block 0 (000200-0007FFh) not code-protected
0 = Block 0 (000200-0007FFh) code-protected
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
R/C-1 R/C-1 U-0 U-0 U-0 U-0 U-0 U-0
CPD CPB — — — — — —
bit 7 bit 0
bit 7 CPD: Data EEPROM Code Protection bit
1 = Data EEPROM not code-protected
0 = Data EEPROM code-protected
bit 6 CPB: Boot Block Code Protection bit
1 = Boot Block (000000-0001FFh) not code-protected
0 = Boot Block (000000-0001FFh) code-protected
bit 5-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state© 2007 Microchip Technology Inc. DS39605F-page 177
PIC18F1220/1320
REGISTER 19-8: CONFIG6L: CONFIGURATION REGISTER 6 LOW (BYTE ADDRESS 30000Ah)
REGISTER 19-9: CONFIG6H: CONFIGURATION REGISTER 6 HIGH (BYTE ADDRESS 30000Bh)
U-0 U-0 U-0 U-0 U-0 U-0 R/P-1 R/P-1
— — — — — — WRT1 WRT0
bit 7 bit 0
bit 7-2 Unimplemented: Read as ‘0’
bit 1 WRT1: Write Protection bit (PIC18F1320)
1 = Block 1 (001000-001FFFh) not write-protected
0 = Block 1 (001000-001FFFh) write-protected
bit 0 WRT0: Write Protection bit (PIC18F1320)
1 = Block 0 (00200-000FFFh) not write-protected
0 = Block 0 (00200-000FFFh) write-protected
bit 1 WRT1: Write Protection bit (PIC18F1220)
1 = Block 1 (000800-000FFFh) not write-protected
0 = Block 1 (000800-000FFFh) write-protected
bit 0 WRT0: Write Protection bit (PIC18F1220)
1 = Block 0 (000200-0007FFh) not write-protected
0 = Block 0 (000200-0007FFh) write-protected
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
R/P-1 R/P-1 R-1 U-0 U-0 U-0 U-0 U-0
WRTD WRTB WRTC — — — — —
bit 7 bit 0
bit 7 WRTD: Data EEPROM Write Protection bit
1 = Data EEPROM not write-protected
0 = Data EEPROM write-protected
bit 6 WRTB: Boot Block Write Protection bit
1 = Boot Block (000000-0001FFh) not write-protected
0 = Boot Block (000000-0001FFh) write-protected
bit 5 WRTC: Configuration Register Write Protection bit
1 = Configuration registers (300000-3000FFh) not write-protected
0 = Configuration registers (300000-3000FFh) write-protected
Note: This bit is read-only in normal execution mode; it can be written only in Program mode.
bit 4-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed statePIC18F1220/1320
DS39605F-page 178 © 2007 Microchip Technology Inc.
REGISTER 19-10: CONFIG7L: CONFIGURATION REGISTER 7 LOW (BYTE ADDRESS 30000Ch)
REGISTER 19-11: CONFIG7H: CONFIGURATION REGISTER 7 HIGH (BYTE ADDRESS 30000Dh)
U-0 U-0 U-0 U-0 U-0 U-0 R/P-1 R/P-1
— — — — — — EBTR1 EBTR0
bit 7 bit 0
bit 7-2 Unimplemented: Read as ‘0’
bit 1 EBTR1: Table Read Protection bit (PIC18F1320)
1 = Block 1 (001000-001FFFh) not protected from table reads executed in other blocks
0 = Block 1 (001000-001FFFh) protected from table reads executed in other blocks
bit 0 EBTR0: Table Read Protection bit (PIC18F1320)
1 = Block 0 (00200-000FFFh) not protected from table reads executed in other blocks
0 = Block 0 (00200-000FFFh) protected from table reads executed in other blocks
bit 1 EBTR1: Table Read Protection bit (PIC18F1220)
1 = Block 1 (000800-000FFFh) not protected from table reads executed in other blocks
0 = Block 1 (000800-000FFFh) protected from table reads executed in other blocks
bit 0 EBTR0: Table Read Protection bit (PIC18F1220)
1 = Block 0 (000200-0007FFh) not protected from table reads executed in other blocks
0 = Block 0 (000200-0007FFh) protected from table reads executed in other blocks
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
U-0 R/P-1 U-0 U-0 U-0 U-0 U-0 U-0
— EBTRB — — — — — —
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 EBTRB: Boot Block Table Read Protection bit
1 = Boot Block (000000-0001FFh) not protected from table reads executed in other blocks
0 = Boot Block (000000-0001FFh) protected from table reads executed in other blocks
bit 5-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state© 2007 Microchip Technology Inc. DS39605F-page 179
PIC18F1220/1320
REGISTER 19-12: DEVID1: DEVICE ID REGISTER 1 FOR PIC18F1220/1320 DEVICES
REGISTER 19-13: DEVID2: DEVICE ID REGISTER 2 FOR PIC18F1220/1320 DEVICES
RRRRRRRR
DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0
bit 7 bit 0
bit 7-5 DEV2:DEV0: Device ID bits
111 = PIC18F1220
110 = PIC18F1320
bit 4-0 REV4:REV0: Revision ID bits
These bits are used to indicate the device revision.
Legend:
R = Read-only bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
RRRRRRRR
DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3
bit 7 bit 0
bit 7-0 DEV10:DEV3: Device ID bits
These bits are used with the DEV2:DEV0 bits in the Device ID Register 1 to identify the
part number.
0000 0111 = PIC18F1220/1320 devices
Note: These values for DEV10:DEV3 may be shared with other devices. The specific
device is always identified by using the entire DEV10:DEV0 bit sequence.
Legend:
R = Read-only bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed statePIC18F1220/1320
DS39605F-page 180 © 2007 Microchip Technology Inc.
19.2 Watchdog Timer (WDT)
For PIC18F1220/1320 devices, the WDT is driven by the
INTRC source. When the WDT is enabled, the clock
source is also enabled. The nominal WDT period is 4 ms
and has the same stability as the INTRC oscillator.
The 4 ms period of the WDT is multiplied by a 16-bit
postscaler. Any output of the WDT postscaler is selected
by a multiplexer, controlled by bits in Configuration
Register 2H. Available periods range from 4 ms to
131.072 seconds (2.18 minutes). The WDT and
postscaler are cleared when any of the following events
occur: execute a SLEEP or CLRWDT instruction, the IRCF
bits (OSCCON<6:4>) are changed or a clock failure has
occurred.
Adjustments to the internal oscillator clock period using
the OSCTUNE register also affect the period of the
WDT by the same factor. For example, if the INTRC
period is increased by 3%, then the WDT period is
increased by 3%.
19.2.1 CONTROL REGISTER
Register 19-14 shows the WDTCON register. This is a
readable and writable register, which contains a control
bit that allows software to override the WDT enable
configuration bit, only if the configuration bit has
disabled the WDT.
FIGURE 19-1: WDT BLOCK DIAGRAM
REGISTER 19-14: WDTCON REGISTER
Note 1: The CLRWDT and SLEEP instructions
clear the WDT and postscaler counts
when executed.
2: Changing the setting of the IRCF bits
(OSCCON<6:4>) clears the WDT and
postscaler counts.
3: When a CLRWDT instruction is executed
the postscaler count will be cleared.
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-0
— — — — — — — SWDTEN
bit 7 bit 0
bit 7-1 Unimplemented: Read as ‘0’
bit 0 SWDTEN: Software Controlled Watchdog Timer Enable bit
1 = Watchdog Timer is on
0 = Watchdog Timer is off
Note: This bit has no effect if the configuration bit, WDTEN (CONFIG2H<0>), is enabled.
Legend:
R = Readable bit W = Writable bit -n = Value at POR
U = Unimplemented bit, read as ‘0’
INTRC Oscillator
WDT
Wake-up
Reset
WDT
WDT Counter
(31 kHz)
Programmable Postscaler
1:1 to 1:32,768
Enable WDT
WDTPS<3:0>
SWDTEN
WDTEN
CLRWDT
4
from Sleep
Reset All Device
Sleep
INTRC Control
Resets
÷125© 2007 Microchip Technology Inc. DS39605F-page 181
PIC18F1220/1320
TABLE 19-2: SUMMARY OF WATCHDOG TIMER REGISTERS
19.3 Two-Speed Start-up
The Two-Speed Start-up feature helps to minimize the
latency period from oscillator start-up to code execution
by allowing the microcontroller to use the INTRC oscillator
as a clock source until the primary clock source is
available. It is enabled by setting the IESO bit in
Configuration Register 1H (CONFIG1H<7>).
Two-Speed Start-up is available only if the primary oscillator
mode is LP, XT, HS or HSPLL (crystal-based
modes). Other sources do not require an OST start-up
delay; for these, Two-Speed Start-up is disabled.
When enabled, Resets and wake-ups from Sleep mode
cause the device to configure itself to run from the
internal oscillator block as the clock source, following
the time-out of the Power-up Timer after a Power-on
Reset is enabled. This allows almost immediate code
execution while the primary oscillator starts and the
OST is running. Once the OST times out, the device
automatically switches to PRI_RUN mode.
Because the OSCCON register is cleared on Reset
events, the INTOSC (or postscaler) clock source is not
initially available after a Reset event; the INTRC clock
is used directly at its base frequency. To use a higher
clock speed on wake-up, the INTOSC or postscaler
clock sources can be selected to provide a higher clock
speed by setting bits, IFRC2:IFRC0, immediately after
Reset. For wake-ups from Sleep, the INTOSC or
postscaler clock sources can be selected by setting
IFRC2:IFRC0 prior to entering Sleep mode.
In all other power managed modes, Two-Speed Start-up
is not used. The device will be clocked by the currently
selected clock source until the primary clock source
becomes available. The setting of the IESO bit is
ignored.
19.3.1 SPECIAL CONSIDERATIONS FOR
USING TWO-SPEED START-UP
While using the INTRC oscillator in Two-Speed Startup,
the device still obeys the normal command
sequences for entering power managed modes, including
serial SLEEP instructions (refer to Section 3.1.3
“Multiple Sleep Commands”). In practice, this means
that user code can change the SCS1:SCS0 bit settings
and issue SLEEP commands before the OST times out.
This would allow an application to briefly wake-up, perform
routine “housekeeping” tasks and return to Sleep
before the device starts to operate from the primary
oscillator.
User code can also check if the primary clock source is
currently providing the system clocking by checking the
status of the OSTS bit (OSCCON<3>). If the bit is set,
the primary oscillator is providing the system clock.
Otherwise, the internal oscillator block is providing the
clock during wake-up from Reset or Sleep mode.
FIGURE 19-2: TIMING TRANSITION FOR TWO-SPEED START-UP (INTOSC TO HSPLL)
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
CONFIG2H — — — WDTPS3 WDTPS2 WDTPS2 WDTPS0 WDTEN
RCON IPEN — — RI TO PD POR BOR
WDTCON — — — — — — — SWDTEN
Legend: Shaded cells are not used by the Watchdog Timer.
Q1 Q3 Q4
OSC1
Peripheral
Program PC PC + 2
INTOSC
PLL Clock
Q1
PC + 6
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 4
Clock
Counter
Q2 Q2 Q3 Q4
Note 1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
Wake from Interrupt Event
TPLL(1)
12345678
Clock Transition
OSTS bit Set
Multiplexer
TOST(1)PIC18F1220/1320
DS39605F-page 182 © 2007 Microchip Technology Inc.
19.4 Fail-Safe Clock Monitor
The Fail-Safe Clock Monitor (FSCM) allows the microcontroller
to continue operation, in the event of an
external oscillator failure, by automatically switching
the system clock to the internal oscillator block. The
FSCM function is enabled by setting the Fail-Safe
Clock Monitor Enable bit, FSCM (CONFIG1H<6>).
When FSCM is enabled, the INTRC oscillator runs at
all times to monitor clocks to peripherals and provide
an instant backup clock in the event of a clock failure.
Clock monitoring (shown in Figure 19-3) is accomplished
by creating a sample clock signal, which is the
INTRC output divided by 64. This allows ample time
between FSCM sample clocks for a peripheral clock
edge to occur. The peripheral system clock and the
sample clock are presented as inputs to the Clock
Monitor latch (CM). The CM is set on the falling edge of
the system clock source, but cleared on the rising edge
of the sample clock.
FIGURE 19-3: FSCM BLOCK DIAGRAM
Clock failure is tested for on the falling edge of the sample
clock. If a sample clock falling edge occurs while
CM is still set, a clock failure has been detected
(Figure 19-4). This causes the following:
• the FSCM generates an oscillator fail interrupt by
setting bit, OSCFIF (PIR2<7>);
• the system clock source is switched to the internal
oscillator block (OSCCON is not updated to show
the current clock source – this is the Fail-Safe
condition); and
• the WDT is reset.
Since the postscaler frequency from the internal oscillator
block may not be sufficiently stable, it may be
desirable to select another clock configuration and
enter an alternate power managed mode (see
Section 19.3.1 “Special Considerations for Using
Two-Speed Start-up” and Section 3.1.3 “Multiple
Sleep Commands” for more details). This can be
done to attempt a partial recovery, or execute a
controlled shutdown.
To use a higher clock speed on wake-up, the INTOSC
or postscaler clock sources can be selected to provide
a higher clock speed by setting bits, IFRC2:IFRC0,
immediately after Reset. For wake-ups from Sleep, the
INTOSC or postscaler clock sources can be selected
by setting IFRC2:IFRC0 prior to entering Sleep mode.
Adjustments to the internal oscillator block, using the
OSCTUNE register, also affect the period of the FSCM
by the same factor. This can usually be neglected, as
the clock frequency being monitored is generally much
higher than the sample clock frequency.
The FSCM will detect failures of the primary or secondary
clock sources only. If the internal oscillator block
fails, no failure would be detected, nor would any action
be possible.
19.4.1 FSCM AND THE WATCHDOG TIMER
Both the FSCM and the WDT are clocked by the
INTRC oscillator. Since the WDT operates with a
separate divider and counter, disabling the WDT has
no effect on the operation of the INTRC oscillator when
the FSCM is enabled.
As already noted, the clock source is switched to the
INTOSC clock when a clock failure is detected.
Depending on the frequency selected by the
IRCF2:IRCF0 bits, this may mean a substantial change
in the speed of code execution. If the WDT is enabled
with a small prescale value, a decrease in clock speed
allows a WDT time-out to occur and a subsequent
device Reset. For this reason, Fail-Safe Clock events
also reset the WDT and postscaler, allowing it to start
timing from when execution speed was changed and
decreasing the likelihood of an erroneous time-out.
Peripheral
INTRC ÷ 64
S
C
Q
(32 μs) 488 Hz
(2.048 ms)
Clock Monitor
Latch (CM)
(edge-triggered)
Clock
Failure
Detected
Source
Clock
Q© 2007 Microchip Technology Inc. DS39605F-page 183
PIC18F1220/1320
19.4.2 EXITING FAIL-SAFE OPERATION
The Fail-Safe condition is terminated by either a device
Reset, or by entering a power managed mode. On
Reset, the controller starts the primary clock source
specified in Configuration Register 1H (with any
required start-up delays that are required for the
oscillator mode, such as OST or PLL timer). The
INTOSC multiplexer provides the system clock until the
primary clock source becomes ready (similar to a TwoSpeed
Start-up). The clock system source is then
switched to the primary clock (indicated by the OSTS
bit in the OSCCON register becoming set). The FailSafe
Clock Monitor then resumes monitoring the
peripheral clock.
The primary clock source may never become ready
during start-up. In this case, operation is clocked by the
INTOSC multiplexer. The OSCCON register will remain
in its Reset state until a power managed mode is
entered.
Entering a power managed mode by loading the
OSCCON register and executing a SLEEP instruction
will clear the Fail-Safe condition. When the Fail-Safe
condition is cleared, the clock monitor will resume
monitoring the peripheral clock.
19.4.3 FSCM INTERRUPTS IN POWER
MANAGED MODES
As previously mentioned, entering a power managed
mode clears the Fail-Safe condition. By entering a
power managed mode, the clock multiplexer selects
the clock source selected by the OSCCON register.
Fail-Safe monitoring of the power managed clock
source resumes in the power managed mode.
If an oscillator failure occurs during power managed
operation, the subsequent events depend on whether
or not the oscillator failure interrupt is enabled. If
enabled (OSCFIF = 1), code execution will be clocked
by the INTOSC multiplexer. An automatic transition
back to the failed clock source will not occur.
If the interrupt is disabled, the device will not exit the
power managed mode on oscillator failure. Instead, the
device will continue to operate as before, but clocked
by the INTOSC multiplexer. While in Idle mode, subsequent
interrupts will cause the CPU to begin executing
instructions while being clocked by the INTOSC multiplexer.
The device will not transition to a different clock
source until the Fail-Safe condition is cleared.
FIGURE 19-4: FSCM TIMING DIAGRAM
OSCFIF
CM Output
System
Clock
Output
Sample Clock
Failure
Detected
Oscillator
Failure
Note: The system clock is normally at a much higher frequency than the sample clock. The relative frequencies in
this example have been chosen for clarity.
(Q)
CM Test CM Test CM TestPIC18F1220/1320
DS39605F-page 184 © 2007 Microchip Technology Inc.
19.4.4 POR OR WAKE FROM SLEEP
The FSCM is designed to detect oscillator failure at any
point after the device has exited Power-on Reset
(POR) or Low-Power Sleep mode. When the primary
system clock is EC, RC or INTRC modes, monitoring
can begin immediately following these events.
For oscillator modes involving a crystal or resonator
(HS, HSPLL, LP or XT), the situation is somewhat different.
Since the oscillator may require a start-up time
considerably longer than the FCSM sample clock time,
a false clock failure may be detected. To prevent this,
the internal oscillator block is automatically configured
as the system clock and functions until the primary
clock is stable (the OST and PLL timers have timed
out). This is identical to Two-Speed Start-up mode.
Once the primary clock is stable, the INTRC returns to
its role as the FSCM source
As noted in Section 19.3.1 “Special Considerations
for Using Two-Speed Start-up”, it is also possible to
select another clock configuration and enter an alternate
power managed mode while waiting for the
primary system clock to become stable. When the new
powered managed mode is selected, the primary clock
is disabled.
Note: The same logic that prevents false oscillator
failure interrupts on POR or wake from
Sleep will also prevent the detection of the
oscillator’s failure to start at all following
these events. This can be avoided by
monitoring the OSTS bit and using a
timing routine to determine if the oscillator
is taking too long to start. Even so, no
oscillator failure interrupt will be flagged. © 2007 Microchip Technology Inc. DS39605F-page 185
PIC18F1220/1320
19.5 Program Verification and
Code Protection
The overall structure of the code protection on the
PIC18 Flash devices differs significantly from other PIC
devices.
The user program memory is divided into three blocks.
One of these is a boot block of 512 bytes. The remainder
of the memory is divided into two blocks on binary
boundaries.
Each of the three blocks has three protection bits
associated with them. They are:
• Code-Protect bit (CPn)
• Write-Protect bit (WRTn)
• External Block Table Read bit (EBTRn)
Figure 19-5 shows the program memory organization
for 4 and 8-Kbyte devices and the specific code protection
bit associated with each block. The actual locations
of the bits are summarized in Table 19-3.
FIGURE 19-5: CODE-PROTECTED PROGRAM MEMORY FOR PIC18F1220/1320
TABLE 19-3: SUMMARY OF CODE PROTECTION REGISTERS
Block Code
Protection
Controlled By:
MEMORY SIZE/DEVICE Block Code
Protection
Controlled By: Address
Range
4 Kbytes
(PIC18F1220)
8 Kbytes
(PIC18F1320)
Address
Range
CPB, WRTB, EBTRB 000000h
0001FFh Boot Block Boot Block 000000h
0001FFh CPB, WRTB, EBTRB
CP0, WRT0, EBTR0
000200h
0007FFh
Block 0
Block 0
000200h
CP0, WRT0, EBTR0
CP1, WRT1, EBTR1
000800h
000FFFh
Block 1
000FFFh
(Unimplemented
Memory Space)
001000h
Unimplemented
Read ‘0’s
Block 1
001000h
CP1, WRT1, EBTR1
001FFFh
1FFFFFh
Unimplemented
Read ‘0’s
002000h
1FFFFFh
(Unimplemented
Memory Space)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
300008h CONFIG5L — — — — — — CP1 CP0
300009h CONFIG5H CPD CPB — — — — — —
30000Ah CONFIG6L — — — — — — WRT1 WRT0
30000Bh CONFIG6H WRTD WRTB WRTC — — — — —
30000Ch CONFIG7L — — — — — — EBTR1 EBTR0
30000Dh CONFIG7H — EBTRB — — — — — —
Legend: Shaded cells are unimplemented.PIC18F1220/1320
DS39605F-page 186 © 2007 Microchip Technology Inc.
19.5.1 PROGRAM MEMORY
CODE PROTECTION
The program memory may be read to, or written from,
any location using the table read and table write
instructions. The device ID may be read with table
reads. The configuration registers may be read and
written with the table read and table write instructions.
In normal execution mode, the CPn bits have no direct
effect. CPn bits inhibit external reads and writes. A
block of user memory may be protected from table
writes if the WRTn configuration bit is ‘0’. The EBTRn
bits control table reads. For a block of user memory
with the EBTRn bit set to ‘0’, a table read instruction
that executes from within that block is allowed to read.
A table read instruction that executes from a location
outside of that block is not allowed to read and will
result in reading ‘0’s. Figures 19-6 through 19-8
illustrate table write and table read protection.
FIGURE 19-6: TABLE WRITE (WRTn) DISALLOWED: PIC18F1320
Note: Code protection bits may only be written to
a ‘0’ from a ‘1’ state. It is not possible to
write a ‘1’ to a bit in the ‘0’ state. Code protection
bits are only set to ‘1’ by a full Chip
Erase or Block Erase function. The full
Chip Erase and Block Erase functions can
only be initiated via ICSP or an external
programmer.
000000h
0001FFh
000200h
000FFFh
001000h
001FFFh
WRTB, EBTRB = 11
WRT0, EBTR0 = 01
TBLWT *
TBLPTR = 0002FFh
PC = 0007FEh
PC = 0017FEh TBLWT *
Register Values Program Memory Configuration Bit Settings
Results: All table writes disabled to Blockn whenever WRTn = 0.
WRT1, EBTR1 = 11© 2007 Microchip Technology Inc. DS39605F-page 187
PIC18F1220/1320
FIGURE 19-7: EXTERNAL BLOCK TABLE READ (EBTRn) DISALLOWED: PIC18F1320
FIGURE 19-8: EXTERNAL BLOCK TABLE READ (EBTRn) ALLOWED: PIC18F1320
000000h
0001FFh
000200h
000FFFh
001000h
001FFFh
WRTB, EBTRB = 11
WRT0, EBTR0 = 10
WRT1, EBTR1 = 11
TBLPTR = 0002FFh
Register Values Program Memory Configuration Bit Settings
PC = 001FFEh TBLRD *
Results: All table reads from external blocks to Blockn are disabled whenever EBTRn = 0.
TABLAT register returns a value of ‘0’.
000000h
0001FFh
000200h
000FFFh
001000h
001FFFh
WRTB, EBTRB = 11
WRT0, EBTR0 = 10
WRT1, EBTR1 = 11
TBLRD *
TBLPTR = 0002FFh
PC = 0007FEh
Register Values Program Memory Configuration Bit Settings
Results: Table reads permitted within Blockn, even when EBTRBn = 0.
TABLAT register returns the value of the data at the location TBLPTR.PIC18F1220/1320
DS39605F-page 188 © 2007 Microchip Technology Inc.
19.5.2 DATA EEPROM
CODE PROTECTION
The entire data EEPROM is protected from external
reads and writes by two bits: CPD and WRTD. CPD
inhibits external reads and writes of data EEPROM.
WRTD inhibits external writes to data EEPROM. The
CPU can continue to read and write data EEPROM,
regardless of the protection bit settings.
19.5.3 CONFIGURATION REGISTER
PROTECTION
The configuration registers can be write-protected. The
WRTC bit controls protection of the configuration
registers. In normal execution mode, the WRTC bit is
readable only. WRTC can only be written via ICSP or
an external programmer.
19.6 ID Locations
Eight memory locations (200000h-200007h) are
designated as ID locations, where the user can store
checksum or other code identification numbers. These
locations are both readable and writable during normal
execution through the TBLRD and TBLWT instructions,
or during program/verify. The ID locations can be read
when the device is code-protected.
19.7 In-Circuit Serial Programming
PIC18F1220/1320 microcontrollers can be serially
programmed while in the end application circuit. This is
simply done with two lines for clock and data and three
other lines for power, ground and the programming
voltage. This allows customers to manufacture boards
with unprogrammed devices and then program the
microcontroller just before shipping the product. This
also allows the most recent firmware or a custom
firmware to be programmed (see Table 19-4).
19.8 In-Circuit Debugger
When the DEBUG bit in configuration register,
CONFIG4L, is programmed to a ‘0’, the In-Circuit
Debugger functionality is enabled. This function allows
simple debugging functions when used with MPLAB®
IDE. When the microcontroller has this feature
enabled, some resources are not available for general
use. Table 19-5 shows which resources are required by
the background debugger.
TABLE 19-5: DEBUGGER RESOURCES
To use the In-Circuit Debugger function of the
microcontroller, the design must implement In-Circuit
Serial Programming connections to MCLR/VPP, VDD,
VSS, RB7 and RB6. This will interface to the In-Circuit
Debugger module available from Microchip, or one of the
third party development tool companies (see the note following
Section 19.7 “In-Circuit Serial Programming”
for more information). Note: The Timer1 oscillator shares the T1OSI
and T1OSO pins with the PGD and PGC
pins used for programming and
debugging.
When using the Timer1 oscillator, In-Circuit
Serial Programming (ICSP) may not
function correctly (high voltage or low
voltage), or the In-Circuit Debugger (ICD)
may not communicate with the controller.
As a result of using either ICSP or ICD, the
Timer1 crystal may be damaged.
If ICSP or ICD operations are required, the
crystal should be disconnected from the
circuit (disconnect either lead), or installed
after programming. The oscillator loading
capacitors may remain in-circuit during
ICSP or ICD operation.
TABLE 19-4: ICSP/ICD CONNECTIONS
Signal Pin Notes
PGD RB7/PGD/T1OSI/
P1D/KBI3
Shared with T1OSC – protect
crystal
PGC RB6/PGC/T1OSO/
T13CKI/P1C/KBI2
Shared with T1OSC – protect
crystal
MCLR MCLR/VPP/RA5
VDD VDD
VSS VSS
PGM RB5/PGM/KBI1 Optional – pull RB5 low is
LVP enabled
I/O pins: RB6, RB7
Stack: 2 levels
Program Memory: 512 bytes
Data Memory: 10 bytes© 2007 Microchip Technology Inc. DS39605F-page 189
PIC18F1220/1320
19.9 Low-Voltage ICSP Programming
The LVP bit in configuration register, CONFIG4L,
enables Low-Voltage Programming (LVP). When LVP
is enabled, the microcontroller can be programmed
without requiring high voltage being applied to the
MCLR/VPP/RA5 pin, but the RB5/PGM/KBI1 pin is then
dedicated to controlling Program mode entry and is not
available as a general purpose I/O pin.
LVP is enabled in erased devices.
While programming using LVP, VDD is applied to the
MCLR/VPP/RA5 pin as in normal execution mode. To
enter Programming mode, VDD is applied to the PGM
pin.
If Low-Voltage Programming mode will not be used, the
LVP bit can be cleared and RB5/PGM/KBI1 becomes
available as the digital I/O pin RB5. The LVP bit may be
set or cleared only when using standard high-voltage
programming (VIHH applied to the MCLR/VPP/RA5 pin).
Once LVP has been disabled, only the standard highvoltage
programming is available and must be used to
program the device.
Memory that is not code-protected can be erased,
using either a Block Erase, or erased row by row, then
written at any specified VDD. If code-protected memory
is to be erased, a Block Erase is required. If a Block
Erase is to be performed when using Low-Voltage
Programming, the device must be supplied with VDD of
4.5V to 5.5V.
Note 1: High-voltage programming is always
available, regardless of the state of the
LVP bit or the PGM pin, by applying VIHH
to the MCLR pin.
2: When Low-Voltage Programming is
enabled, the RB5 pin can no longer be
used as a general purpose I/O pin.
3: When LVP is enabled, externally pull the
PGM pin to VSS to allow normal program
execution.PIC18F1220/1320
DS39605F-page 190 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 191
PIC18F1220/1320
20.0 INSTRUCTION SET SUMMARY
The PIC18 instruction set adds many enhancements to
the previous PIC instruction sets, while maintaining an
easy migration from these PIC instruction sets.
Most instructions are a single program memory word
(16 bits), but there are three instructions that require
two program memory locations.
Each single-word instruction is a 16-bit word divided
into an opcode, which specifies the instruction type and
one or more operands, which further specify the
operation of the instruction.
The instruction set is highly orthogonal and is grouped
into four basic categories:
• Byte-oriented operations
• Bit-oriented operations
• Literal operations
• Control operations
The PIC18 instruction set summary in Table 20-1 lists
byte-oriented, bit-oriented, literal and control
operations. Table 20-1 shows the opcode field
descriptions.
Most byte-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The destination of the result
(specified by ‘d’)
3. The accessed memory
(specified by ‘a’)
The file register designator ‘f’ specifies which file
register is to be used by the instruction.
The destination designator ‘d’ specifies where the
result of the operation is to be placed. If ‘d’ is zero, the
result is placed in the WREG register. If ‘d’ is one, the
result is placed in the file register specified in the
instruction.
All bit-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The bit in the file register
(specified by ‘b’)
3. The accessed memory
(specified by ‘a’)
The bit field designator ‘b’ selects the number of the bit
affected by the operation, while the file register designator
‘f’ represents the number of the file in which the
bit is located.
The literal instructions may use some of the following
operands:
• A literal value to be loaded into a file register
(specified by ‘k’)
• The desired FSR register to load the literal value
into (specified by ‘f’)
• No operand required
(specified by ‘—’)
The control instructions may use some of the following
operands:
• A program memory address (specified by ‘n’)
• The mode of the CALL or RETURN instructions
(specified by ‘s’)
• The mode of the table read and table write
instructions (specified by ‘m’)
• No operand required
(specified by ‘—’)
All instructions are a single word, except for three
double-word instructions. These three instructions
were made double-word instructions so that all the
required information is available in these 32 bits. In the
second word, the 4 MSbs are ‘1’s. If this second word
is executed as an instruction (by itself), it will execute
as a NOP.
All single-word instructions are executed in a single
instruction cycle, unless a conditional test is true, or the
program counter is changed as a result of the instruction.
In these cases, the execution takes two instruction
cycles, with the additional instruction cycle(s) executed
as a NOP.
The double-word instructions execute in two instruction
cycles.
One instruction cycle consists of four oscillator periods.
Thus, for an oscillator frequency of 4 MHz, the normal
instruction execution time is 1 μs. If a conditional test is
true, or the program counter is changed as a result of
an instruction, the instruction execution time is 2 μs.
Two-word branch instructions (if true) would take 3 μs.
Figure 20-1 shows the general formats that the
instructions can have.
All examples use the format ‘nnh’ to represent a hexadecimal
number, where ‘h’ signifies a hexadecimal
digit.
The Instruction Set Summary, shown in Table 20-1,
lists the instructions recognized by the Microchip
Assembler (MPASMTM). Section 20.2 “Instruction
Set” provides a description of each instruction.
20.1 Read-Modify-Write Operations
Any instruction that specifies a file register as part of
the instruction performs a Read-Modify-Write (R-M-W)
operation. The register is read, the data is modified and
the result is stored according to either the instruction or
the destination designator ‘d’. A read operation is
performed on a register even if the instruction writes to
that register.
For example, a “BCF PORTB,1” instruction will read
PORTB, clear bit 1 of the data, then write the result
back to PORTB. The read operation would have the
unintended result that any condition that sets the RBIF
flag would be cleared. The R-M-W operation may also
copy the level of an input pin to its corresponding output
latch.PIC18F1220/1320
DS39605F-page 192 © 2007 Microchip Technology Inc.
TABLE 20-1: OPCODE FIELD DESCRIPTIONS
Field Description
a RAM access bit
a = 0: RAM location in Access RAM (BSR register is ignored)
a = 1: RAM bank is specified by BSR register
bbb Bit address within an 8-bit file register (0 to 7).
BSR Bank Select Register. Used to select the current RAM bank.
d Destination select bit
d = 0: store result in WREG
d = 1: store result in file register f
dest Destination either the WREG register or the specified register file location.
f 8-bit register file address (0x00 to 0xFF).
fs 12-bit register file address (0x000 to 0xFFF). This is the source address.
fd 12-bit register file address (0x000 to 0xFFF). This is the destination address.
k Literal field, constant data or label (may be either an 8-bit, 12-bit or a 20-bit value).
label Label name.
mm The mode of the TBLPTR register for the table read and table write instructions.
Only used with table read and table write instructions:
* No change to register (such as TBLPTR with table reads and writes)
*+ Post-Increment register (such as TBLPTR with table reads and writes)
*- Post-Decrement register (such as TBLPTR with table reads and writes)
+* Pre-Increment register (such as TBLPTR with table reads and writes)
n The relative address (2’s complement number) for relative branch instructions, or the direct address for
call/branch and return instructions.
PRODH Product of Multiply High Byte.
PRODL Product of Multiply Low Byte.
s Fast Call/Return mode select bit
s = 0: do not update into/from shadow registers
s = 1: certain registers loaded into/from shadow registers (Fast mode)
u Unused or unchanged.
WREG Working register (accumulator).
x Don’t care (‘0’ or ‘1’).
The assembler will generate code with x = 0. It is the recommended form of use for compatibility with all
Microchip software tools.
TBLPTR 21-bit Table Pointer (points to a program memory location).
TABLAT 8-bit Table Latch.
TOS Top-of-Stack.
PC Program Counter.
PCL Program Counter Low Byte.
PCH Program Counter High Byte.
PCLATH Program Counter High Byte Latch.
PCLATU Program Counter Upper Byte Latch.
GIE Global Interrupt Enable bit.
WDT Watchdog Timer.
TO Time-out bit.
PD Power-down bit.
C, DC, Z, OV, N ALU Status bits: Carry, Digit Carry, Zero, Overflow, Negative.
[ ] Optional.
( ) Contents.
→ Assigned to.
< > Register bit field.
∈ In the set of.
italics User defined term (font is Courier).© 2007 Microchip Technology Inc. DS39605F-page 193
PIC18F1220/1320
FIGURE 20-1: GENERAL FORMAT FOR INSTRUCTIONS
Byte-oriented file register operations
15 10 9 8 7 0
d = 0 for result destination to be WREG register
OPCODE d a f (FILE #)
d = 1 for result destination to be file register (f)
a = 0 to force Access Bank
Bit-oriented file register operations
15 12 11 9 8 7 0
OPCODE b (BIT #) a f (FILE #)
b = 3-bit position of bit in file register (f)
Literal operations
15 8 7 0
OPCODE k (literal)
k = 8-bit immediate value
Byte to Byte move operations (2-word)
15 12 11 0
OPCODE f (Source FILE #)
CALL, GOTO and Branch operations
15 8 7 0
OPCODE n<7:0> (literal)
n = 20-bit immediate value
a = 1 for BSR to select bank
f = 8-bit file register address
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
15 12 11 0
1111 n<19:8> (literal)
15 12 11 0
1111 f (Destination FILE #)
f = 12-bit file register address
Control operations
Example Instruction
ADDWF MYREG, W, B
MOVFF MYREG1, MYREG2
BSF MYREG, bit, B
MOVLW 0x7F
GOTO Label
15 8 7 0
OPCODE n<7:0> (literal)
15 12 11 0
n<19:8> (literal)
CALL MYFUNC
15 11 10 0
OPCODE n<10:0> (literal)
S = Fast bit
BRA MYFUNC
15 8 7 0
OPCODE n<7:0> (literal) BC MYFUNC
SPIC18F1220/1320
DS39605F-page 194 © 2007 Microchip Technology Inc.
TABLE 20-1: PIC18FXXXX INSTRUCTION SET
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
SUBWF
SUBWFB
SWAPF
TSTFSZ
XORWF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, skip =
Compare f with WREG, skip >
Compare f with WREG, skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to 1st word
fd (destination) 2nd word
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
borrow
Subtract WREG from f
Subtract WREG from f with
borrow
Swap nibbles in f
Test f, skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1 (2 or 3)
1
0010
0010
0001
0110
0001
0110
0110
0110
0000
0010
0100
0010
0011
0100
0001
0101
1100
1111
0110
0000
0110
0011
0100
0011
0100
0110
0101
0101
0101
0011
0110
0001
01da
00da
01da
101a
11da
001a
010a
000a
01da
11da
11da
10da
11da
10da
00da
00da
ffff
ffff
111a
001a
110a
01da
01da
00da
00da
100a
01da
11da
10da
10da
011a
10da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z, N
Z, N
None
None
None
C, DC, Z, OV, N
C, Z, N
Z, N
C, Z, N
Z, N
None
C, DC, Z, OV, N
C, DC, Z, OV, N
C, DC, Z, OV, N
None
None
Z, N
1, 2
1, 2
1,2
2
1, 2
4
4
1, 2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
4
1, 2
1, 2
1
1, 2
1, 2
1, 2
1, 2
4
1, 2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
Note 1: When a Port 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.
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 of the instruction 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.© 2007 Microchip Technology Inc. DS39605F-page 195
PIC18F1220/1320
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
CLRWDT
DAW
GOTO
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
RETLW
RETURN
SLEEP
n
n
n
n
n
n
n
n
n
n, s
—
—
n
—
—
—
—
n
s
k
s
—
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call subroutine 1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to address 1st word
2nd word
No Operation
No Operation
Pop top of return stack (TOS)
Push top of return stack (TOS)
Relative Call
Software device Reset
Return from interrupt enable
Return with literal in WREG
Return from Subroutine
Go into Standby mode
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
2
1
1
2
1
1
1
1
2
1
2
2
2
1
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0000
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
1100
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
kkkk
0001
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
kkkk
001s
0011
None
None
None
None
None
None
None
None
None
None
TO, PD
C
None
None
None
None
None
None
All
GIE/GIEH,
PEIE/GIEL
None
None
TO, PD
4
TABLE 20-1: PIC18FXXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a Port 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.
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 of the instruction 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.PIC18F1220/1320
DS39605F-page 196 © 2007 Microchip Technology Inc.
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
LFSR
MOVLB
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
f, k
k
k
k
k
k
k
Add literal and WREG
AND literal with WREG
Inclusive OR literal with WREG
Move literal (12-bit) 2nd word
to FSRx 1st word
Move literal to BSR<3:0>
Move literal to WREG
Multiply literal with WREG
Return with literal in WREG
Subtract WREG from literal
Exclusive OR literal with WREG
1
1
1
2
1
1
1
2
1
1
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
0000
1111
1011
1001
1110
0000
0001
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
00ff
kkkk
0000
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
None
None
None
None
C, DC, Z, OV, N
Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD*
TBLRD*+
TBLRD*-
TBLRD+*
TBLWT*
TBLWT*+
TBLWT*-
TBLWT+*
Table read
Table read with post-increment
Table read with post-decrement
Table read with pre-increment
Table write
Table write with post-increment
Table write with post-decrement
Table write with pre-increment
2
2 (5)
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
1000
1001
1010
1011
1100
1101
1110
1111
None
None
None
None
None
None
None
None
TABLE 20-1: PIC18FXXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a Port 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.
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 of the instruction 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.© 2007 Microchip Technology Inc. DS39605F-page 197
PIC18F1220/1320
20.2 Instruction Set
ADDLW ADD literal to W
Syntax: [ label ] ADDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) + k → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1111 kkkk kkkk
Description: The contents of W are added to the
8-bit literal ‘k’ and the result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: ADDLW 0x15
Before Instruction
W = 0x10
After Instruction
W = 0x25
ADDWF ADD W to f
Syntax: [ label ] ADDWF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0010 01da ffff ffff
Description: Add W to register ‘f’. If ‘d’ is ‘0’, the
result is stored in W. If ‘d’ is ‘1’, the
result is stored back in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected. If ‘a’ is ‘1’,
the BSR is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ADDWF REG, W
Before Instruction
W = 0x17
REG = 0xC2
After Instruction
W = 0xD9
REG = 0xC2PIC18F1220/1320
DS39605F-page 198 © 2007 Microchip Technology Inc.
ADDWFC ADD W and Carry bit to f
Syntax: [ label ] ADDWFC f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) + (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0010 00da ffff ffff
Description: Add W, the Carry flag and data
memory location ‘f’. If ‘d’ is ‘0’, the
result is placed in W. If ‘d’ is ‘1’, the
result is placed in data memory
location ‘f’. If ‘a’ is ‘0’, the Access
Bank will be selected. If ‘a’ is ‘1’, the
BSR will not be overridden.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ADDWFC REG, W
Before Instruction
Carry bit = 1
REG = 0x02
W = 0x4D
After Instruction
Carry bit = 0
REG = 0x02
W = 0x50
ANDLW AND literal with W
Syntax: [ label ] ANDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .AND. k → W
Status Affected: N, Z
Encoding: 0000 1011 kkkk kkkk
Description: The contents of W are AND’ed with
the 8-bit literal ‘k’. The result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’
Process
Data
Write to W
Example: ANDLW 0x5F
Before Instruction
W = 0xA3
After Instruction
W = 0x03© 2007 Microchip Technology Inc. DS39605F-page 199
PIC18F1220/1320
ANDWF AND W with f
Syntax: [ label ] ANDWF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .AND. (f) → dest
Status Affected: N, Z
Encoding: 0001 01da ffff ffff
Description: The contents of W are AND’ed with
register ‘f’. If ‘d’ is ‘0’, the result is
stored in W. If ‘d’ is ‘1’, the result is
stored back in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank will be
selected. If ‘a’ is ‘1’, the BSR will
not be overridden (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ANDWF REG, W
Before Instruction
W = 0x17
REG = 0xC2
After Instruction
W = 0x02
REG = 0xC2
BC Branch if Carry
Syntax: [ label ] BC n
Operands: -128 ≤ n ≤ 127
Operation: if Carry bit is ‘1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0010 nnnn nnnn
Description: If the Carry bit is ‘1’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BC JUMP
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 1;
PC = address (JUMP)
If Carry = 0;
PC = address (HERE + 2)PIC18F1220/1320
DS39605F-page 200 © 2007 Microchip Technology Inc.
BCF Bit Clear f
Syntax: [ label ] BCF f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 0 → f
Status Affected: None
Encoding: 1001 bbba ffff ffff
Description: Bit ‘b’ in register ‘f’ is cleared. If ‘a’
is ‘0’, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BCF FLAG_REG, 7
Before Instruction
FLAG_REG = 0xC7
After Instruction
FLAG_REG = 0x47
BN Branch if Negative
Syntax: [ label ] BN n
Operands: -128 ≤ n ≤ 127
Operation: if Negative bit is ‘1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0110 nnnn nnnn
Description: If the Negative bit is ‘1’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 1;
PC = address (Jump)
If Negative = 0;
PC = address (HERE + 2)© 2007 Microchip Technology Inc. DS39605F-page 201
PIC18F1220/1320
BNC Branch if Not Carry
Syntax: [ label ] BNC n
Operands: -128 ≤ n ≤ 127
Operation: if Carry bit is ‘0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0011 nnnn nnnn
Description: If the Carry bit is ‘0’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNC Jump
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 0;
PC = address (Jump)
If Carry = 1;
PC = address (HERE + 2)
BNN Branch if Not Negative
Syntax: [ label ] BNN n
Operands: -128 ≤ n ≤ 127
Operation: if Negative bit is ‘0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0111 nnnn nnnn
Description: If the Negative bit is ‘0’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 0;
PC = address (Jump)
If Negative = 1;
PC = address (HERE + 2)PIC18F1220/1320
DS39605F-page 202 © 2007 Microchip Technology Inc.
BNOV Branch if Not Overflow
Syntax: [ label ] BNOV n
Operands: -128 ≤ n ≤ 127
Operation: if Overflow bit is ‘0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0101 nnnn nnnn
Description: If the Overflow bit is ‘0’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNOV Jump
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 0;
PC = address (Jump)
If Overflow = 1;
PC = address (HERE + 2)
BNZ Branch if Not Zero
Syntax: [ label ] BNZ n
Operands: -128 ≤ n ≤ 127
Operation: if Zero bit is ‘0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0001 nnnn nnnn
Description: If the Zero bit is ‘0’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 0;
PC = address (Jump)
If Zero = 1;
PC = address (HERE + 2)© 2007 Microchip Technology Inc. DS39605F-page 203
PIC18F1220/1320
BRA Unconditional Branch
Syntax: [ label ] BRA n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 0nnn nnnn nnnn
Description: Add the 2’s complement number
‘2n’ to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is a
two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE BRA Jump
Before Instruction
PC = address (HERE)
After Instruction
PC = address (Jump)
BSF Bit Set f
Syntax: [ label ] BSF f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 1 → f
Status Affected: None
Encoding: 1000 bbba ffff ffff
Description: Bit ‘b’ in register ‘f’ is set. If ‘a’ is ‘0’,
the Access Bank will be selected,
overriding the BSR value. If ‘a’ = 1,
then the bank will be selected as
per the BSR value.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BSF FLAG_REG, 7
Before Instruction
FLAG_REG = 0x0A
After Instruction
FLAG_REG = 0x8APIC18F1220/1320
DS39605F-page 204 © 2007 Microchip Technology Inc.
BTFSC Bit Test File, Skip if Clear
Syntax: [ label ] BTFSC f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: skip if (f) = 0
Status Affected: None
Encoding: 1011 bbba ffff ffff
Description: If bit ‘b’ in register ‘f’ is ‘0’, then the
next instruction is skipped.
If bit ‘b’ is ‘0’, then the next
instruction fetched during the current
instruction execution is discarded
and a NOP is executed instead,
making this a two-cycle instruction. If
‘a’ is ‘0’, the Access Bank will be
selected, overriding the BSR value. If
‘a’ = 1, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSC
:
:
FLAG, 1
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (TRUE)
If FLAG<1> = 1;
PC = address (FALSE)
BTFSS Bit Test File, Skip if Set
Syntax: [ label ] BTFSS f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b < 7
a ∈ [0,1]
Operation: skip if (f) = 1
Status Affected: None
Encoding: 1010 bbba ffff ffff
Description: If bit ‘b’ in register ‘f’ is ‘1’, then the
next instruction is skipped.
If bit ‘b’ is ‘1’, then the next
instruction fetched during the current
instruction execution is discarded
and a NOP is executed instead,
making this a two-cycle instruction. If
‘a’ is ‘0’, the Access Bank will be
selected, overriding the BSR value. If
‘a’ = 1, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSS
:
:
FLAG, 1
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (FALSE)
If FLAG<1> = 1;
PC = address (TRUE)© 2007 Microchip Technology Inc. DS39605F-page 205
PIC18F1220/1320
BTG Bit Toggle f
Syntax: [ label ] BTG f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b < 7
a ∈ [0,1]
Operation: (f) → f
Status Affected: None
Encoding: 0111 bbba ffff ffff
Description: Bit ‘b’ in data memory location ‘f’ is
inverted. If ‘a’ is ‘0’, the Access Bank
will be selected, overriding the BSR
value. If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BTG PORTB, 4
Before Instruction:
PORTB = 0111 0101 [0x75]
After Instruction:
PORTB = 0110 0101 [0x65]
BOV Branch if Overflow
Syntax: [ label ] BOV n
Operands: -128 ≤ n ≤ 127
Operation: if Overflow bit is ‘1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0100 nnnn nnnn
Description: If the Overflow bit is ‘1’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BOV JUMP
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 1;
PC = address (JUMP)
If Overflow = 0;
PC = address (HERE + 2)PIC18F1220/1320
DS39605F-page 206 © 2007 Microchip Technology Inc.
BZ Branch if Zero
Syntax: [ label ] BZ n
Operands: -128 ≤ n ≤ 127
Operation: if Zero bit is ‘1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0000 nnnn nnnn
Description: If the Zero bit is ‘1’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 1;
PC = address (Jump)
If Zero = 0;
PC = address (HERE + 2)
CALL Subroutine Call
Syntax: [ label ] CALL k [,s]
Operands: 0 ≤ k ≤ 1048575
s ∈ [0,1]
Operation: (PC) + 4 → TOS,
k → PC<20:1>,
if s = 1
(W) → WS,
(Status) → STATUSS,
(BSR) → BSRS
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
110s
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: Subroutine call of entire 2-Mbyte
memory range. First, return
address (PC + 4) is pushed onto
the return stack. If ‘s’ = 1, the W,
Status and BSR registers are also
pushed into their respective
shadow registers, WS, STATUSS
and BSRS. If ‘s’ = 0, no update
occurs (default). Then, the 20-bit
value ‘k’ is loaded into PC<20:1>.
CALL is a two-cycle instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’<7:0>,
Push PC to
stack
Read literal
‘k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE CALL THERE, FAST
Before Instruction
PC = address (HERE)
After Instruction
PC = address (THERE)
TOS = address (HERE + 4)
WS = W
BSRS = BSR
STATUSS = Status© 2007 Microchip Technology Inc. DS39605F-page 207
PIC18F1220/1320
CLRF Clear f
Syntax: [ label ] CLRF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: 000h → f
1 → Z
Status Affected: Z
Encoding: 0110 101a ffff ffff
Description: Clears the contents of the specified
register. If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: CLRF FLAG_REG
Before Instruction
FLAG_REG = 0x5A
After Instruction
FLAG_REG = 0x00
CLRWDT Clear Watchdog Timer
Syntax: [ label ] CLRWDT
Operands: None
Operation: 000h → WDT,
000h → WDT postscaler,
1 → TO,
1 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0100
Description: CLRWDT instruction resets the
Watchdog Timer. It also resets the
postscaler of the WDT. Status bits,
TO and PD, are set.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
No
operation
Example: CLRWDT
Before Instruction
WDT Counter = ?
After Instruction
WDT Counter = 0x00
WDT Postscaler = 0
TO = 1
PD = 1PIC18F1220/1320
DS39605F-page 208 © 2007 Microchip Technology Inc.
COMF Complement f
Syntax: [ label ] COMF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest
Status Affected: N, Z
Encoding: 0001 11da ffff ffff
Description: The contents of register ‘f’ are
complemented. If ‘d’ is ‘0’, the
result is stored in W. If ‘d’ is ‘1’, the
result is stored back in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: COMF REG, W
Before Instruction
REG = 0x13
After Instruction
REG = 0x13
W = 0xEC
CPFSEQ Compare f with W, skip if f = W
Syntax: [ label ] CPFSEQ f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) = (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 001a ffff ffff
Description: Compares the contents of data
memory location ‘f’ to the contents
of W by performing an unsigned
subtraction.
If ‘f’ = W, then the fetched
instruction is discarded and a NOP
is executed instead, making this a
two-cycle instruction. If ‘a’ is ‘0’, the
Access Bank will be selected,
overriding the BSR value. If ‘a’ = 1,
then the bank will be selected as
per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSEQ REG
NEQUAL :
EQUAL :
Before Instruction
PC Address = HERE
W =?
REG = ?
After Instruction
If REG = W;
PC = Address (EQUAL)
If REG ≠ W;
PC = Address (NEQUAL)© 2007 Microchip Technology Inc. DS39605F-page 209
PIC18F1220/1320
CPFSGT Compare f with W, skip if f > W
Syntax: [ label ] CPFSGT f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) > (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 010a ffff ffff
Description: Compares the contents of data
memory location ‘f’ to the contents
of W by performing an unsigned
subtraction.
If the contents of ‘f’ are greater than
the contents of WREG, then the
fetched instruction is discarded and
a NOP is executed instead, making
this a two-cycle instruction. If ‘a’ is
‘0’, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSGT REG
NGREATER :
GREATER :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG > W;
PC = Address (GREATER)
If REG ≤ W;
PC = Address (NGREATER)
CPFSLT Compare f with W, skip if f < W
Syntax: [ label ] CPFSLT f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) < (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 000a ffff ffff
Description: Compares the contents of data
memory location ‘f’ to the contents
of W by performing an unsigned
subtraction.
If the contents of ‘f’ are less than
the contents of W, then the fetched
instruction is discarded and a NOP
is executed instead, making this a
two-cycle instruction. If ‘a’ is ‘0’, the
Access Bank will be selected. If ‘a’
is ‘1’, the BSR will not be
overridden (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSLT REG
NLESS :
LESS :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG < W;
PC = Address (LESS)
If REG ≥ W;
PC = Address (NLESS)PIC18F1220/1320
DS39605F-page 210 © 2007 Microchip Technology Inc.
DAW Decimal Adjust W Register
Syntax: [ label ] DAW
Operands: None
Operation: If [W<3:0> > 9] or [DC = 1] then
(W<3:0>) + 6 → W<3:0>;
else
(W<3:0>) → W<3:0>;
If [W<7:4> > 9] or [C = 1] then
(W<7:4>) + 6 → W<7:4>;
else
(W<7:4>) → W<7:4>;
Status Affected: C, DC
Encoding: 0000 0000 0000 0111
Description: DAW adjusts the eight-bit value in
W, resulting from the earlier addition
of two variables (each in
packed BCD format) and produces
a correct packed BCD result. The
Carry bit may be set by DAW regardless
of its setting prior to the DAW
instruction.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register W
Process
Data
Write
W
Example 1: DAW
Before Instruction
W = 0xA5
C =0
DC = 0
After Instruction
W = 0x05
C =1
DC = 0
Example 2:
Before Instruction
W = 0xCE
C =0
DC = 0
After Instruction
W = 0x34
C =1
DC = 0
DECF Decrement f
Syntax: [ label ] DECF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0000 01da ffff ffff
Description: Decrement register ‘f’. If ‘d’ is ‘0’,
the result is stored in W. If ‘d’ is ‘1’,
the result is stored back in register
‘f’ (default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: DECF CNT
Before Instruction
CNT = 0x01
Z =0
After Instruction
CNT = 0x00
Z =1© 2007 Microchip Technology Inc. DS39605F-page 211
PIC18F1220/1320
DECFSZ Decrement f, skip if 0
Syntax: [ label ] DECFSZ f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0010 11da ffff ffff
Description: The contents of register ‘f’ are
decremented. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default).
If the result is ‘0’, the next instruction,
which is already fetched, is
discarded and a NOP is executed
instead, making it a two-cycle
instruction. If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DECFSZ CNT
GOTO LOOP
CONTINUE
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT – 1
If CNT = 0;
PC = Address (CONTINUE)
If CNT ≠ 0;
PC = Address (HERE + 2)
DCFSNZ Decrement f, skip if not 0
Syntax: [ label ] DCFSNZ f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 11da ffff ffff
Description: The contents of register ‘f’ are
decremented. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default).
If the result is not ‘0’, the next
instruction, which is already
fetched, is discarded and a NOP is
executed instead, making it a twocycle
instruction. If ‘a’ is ‘0’, the
Access Bank will be selected,
overriding the BSR value. If ‘a’ = 1,
then the bank will be selected as
per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DCFSNZ TEMP
ZERO :
NZERO :
Before Instruction
TEMP = ?
After Instruction
TEMP = TEMP – 1,
If TEMP = 0;
PC = Address (ZERO)
If TEMP ≠ 0;
PC = Address (NZERO)PIC18F1220/1320
DS39605F-page 212 © 2007 Microchip Technology Inc.
GOTO Unconditional Branch
Syntax: [ label ] GOTO k
Operands: 0 ≤ k ≤ 1048575
Operation: k → PC<20:1>
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
1111
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: GOTO allows an unconditional
branch anywhere within the entire
2-Mbyte memory range. The 20-bit
value ‘k’ is loaded into PC<20:1>.
GOTO is always a two-cycle
instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’<7:0>,
No
operation
Read literal
‘k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: GOTO THERE
After Instruction
PC = Address (THERE)
INCF Increment f
Syntax: [ label ] INCF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0010 10da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: INCF CNT
Before Instruction
CNT = 0xFF
Z =0
C =?
DC = ?
After Instruction
CNT = 0x00
Z =1
C =1
DC = 1© 2007 Microchip Technology Inc. DS39605F-page 213
PIC18F1220/1320
INCFSZ Increment f, skip if 0
Syntax: [ label ] INCFSZ f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0011 11da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default).
If the result is ‘0’, the next instruction,
which is already fetched, is
discarded and a NOP is executed
instead, making it a two-cycle
instruction. If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INCFSZ CNT
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT + 1
If CNT = 0;
PC = Address (ZERO)
If CNT ≠ 0;
PC = Address (NZERO)
INFSNZ Increment f, skip if not 0
Syntax: [ label ] INFSNZ f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 10da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default).
If the result is not ‘0’, the next
instruction, which is already
fetched, is discarded and a NOP is
executed instead, making it a
two-cycle instruction. If ‘a’ is ‘0’, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INFSNZ REG
ZERO
NZERO
Before Instruction
PC = Address (HERE)
After Instruction
REG = REG + 1
If REG ≠ 0;
PC = Address (NZERO)
If REG = 0;
PC = Address (ZERO)PIC18F1220/1320
DS39605F-page 214 © 2007 Microchip Technology Inc.
IORLW Inclusive OR literal with W
Syntax: [ label ] IORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .OR. k → W
Status Affected: N, Z
Encoding: 0000 1001 kkkk kkkk
Description: The contents of W are OR’ed with
the eight-bit literal ‘k’. The result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: IORLW 0x35
Before Instruction
W = 0x9A
After Instruction
W = 0xBF
IORWF Inclusive OR W with f
Syntax: [ label ] IORWF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .OR. (f) → dest
Status Affected: N, Z
Encoding: 0001 00da ffff ffff
Description: Inclusive OR W with register ‘f’. If
‘d’ is ‘0’, the result is placed in W. If
‘d’ is ‘1’, the result is placed back in
register ‘f’ (default). If ‘a’ is ‘0’, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: IORWF RESULT, W
Before Instruction
RESULT = 0x13
W = 0x91
After Instruction
RESULT = 0x13
W = 0x93© 2007 Microchip Technology Inc. DS39605F-page 215
PIC18F1220/1320
LFSR Load FSR
Syntax: [ label ] LFSR f,k
Operands: 0 ≤ f ≤ 2
0 ≤ k ≤ 4095
Operation: k → FSRf
Status Affected: None
Encoding: 1110
1111
1110
0000
00ff
k7kkk
k11kkk
kkkk
Description: The 12-bit literal ‘k’ is loaded into
the file select register pointed to
by ‘f’.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’ MSB
Process
Data
Write literal
‘k’ MSB to
FSRfH
Decode Read literal
‘k’ LSB
Process
Data
Write literal
‘k’ to FSRfL
Example: LFSR 2, 0x3AB
After Instruction
FSR2H = 0x03
FSR2L = 0xAB
MOVF Move f
Syntax: [ label ] MOVF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: f → dest
Status Affected: N, Z
Encoding: 0101 00da ffff ffff
Description: The contents of register ‘f’ are
moved to a destination dependent
upon the status of ‘d’. If ‘d’ is ‘f’, the
result is placed in W. If ‘d’ is ‘f’, the
result is placed back in register ‘f’
(default). Location ‘f’ can be anywhere
in the 256-byte bank. If ‘a’ is
‘0’, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write W
Example: MOVF REG, W
Before Instruction
REG = 0x22
W = 0xFF
After Instruction
REG = 0x22
W = 0x22PIC18F1220/1320
DS39605F-page 216 © 2007 Microchip Technology Inc.
MOVFF Move f to f
Syntax: [ label ] MOVFF fs,fd
Operands: 0 ≤ fs ≤ 4095
0 ≤ fd ≤ 4095
Operation: (fs) → fd
Status Affected: None
Encoding:
1st word (source)
2nd word (destin.)
1100
1111
ffff
ffff
ffff
ffff
ffffs
ffffd
Description: The contents of source register ‘fs’
are moved to destination register
‘fd’. Location of source ‘fs’ can be
anywhere in the 4096-byte data
space (000h to FFFh) and location
of destination ‘fd’ can also be
anywhere from 000h to FFFh.
Either source or destination can be
W (a useful special situation).
MOVFF is particularly useful for
transferring a data memory location
to a peripheral register (such as the
transmit buffer or an I/O port).
The MOVFF instruction cannot use
the PCL, TOSU, TOSH or TOSL as
the destination register.
The MOVFF instruction should not
be used to modify interrupt settings
while any interrupt is enabled (see
page 73).
Words: 2
Cycles: 2 (3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
(src)
Process
Data
No
operation
Decode No
operation
No dummy
read
No
operation
Write
register ‘f’
(dest)
Example: MOVFF REG1, REG2
Before Instruction
REG1 = 0x33
REG2 = 0x11
After Instruction
REG1 = 0x33,
REG2 = 0x33
MOVLB Move literal to low nibble in BSR
Syntax: [ label ] MOVLB k
Operands: 0 ≤ k ≤ 255
Operation: k → BSR
Status Affected: None
Encoding: 0000 0001 kkkk kkkk
Description: The 8-bit literal ‘k’ is loaded into
the Bank Select Register (BSR).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’
Process
Data
Write
literal ‘k’ to
BSR
Example: MOVLB 5
Before Instruction
BSR register = 0x02
After Instruction
BSR register = 0x05© 2007 Microchip Technology Inc. DS39605F-page 217
PIC18F1220/1320
MOVLW Move literal to W
Syntax: [ label ] MOVLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W
Status Affected: None
Encoding: 0000 1110 kkkk kkkk
Description: The eight-bit literal ‘k’ is loaded
into W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: MOVLW 0x5A
After Instruction
W = 0x5A
MOVWF Move W to f
Syntax: [ label ] MOVWF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) → f
Status Affected: None
Encoding: 0110 111a ffff ffff
Description: Move data from W to register ‘f’.
Location ‘f’ can be anywhere in the
256-byte bank. If ‘a’ is ‘0’, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: MOVWF REG
Before Instruction
W = 0x4F
REG = 0xFF
After Instruction
W = 0x4F
REG = 0x4FPIC18F1220/1320
DS39605F-page 218 © 2007 Microchip Technology Inc.
MULLW Multiply Literal with W
Syntax: [ label ] MULLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) x k → PRODH:PRODL
Status Affected: None
Encoding: 0000 1101 kkkk kkkk
Description: An unsigned multiplication is
carried out between the contents
of W and the 8-bit literal ‘k’. The
16-bit result is placed in the
PRODH:PRODL register pair.
PRODH contains the high byte.
W is unchanged.
None of the Status flags are
affected.
Note that neither Overflow nor
Carry is possible in this operation.
A Zero result is possible but
not detected.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write
registers
PRODH:
PRODL
Example: MULLW 0xC4
Before Instruction
W = 0xE2
PRODH = ?
PRODL = ?
After Instruction
W = 0xE2
PRODH = 0xAD
PRODL = 0x08
MULWF Multiply W with f
Syntax: [ label ] MULWF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) x (f) → PRODH:PRODL
Status Affected: None
Encoding: 0000 001a ffff ffff
Description: An unsigned multiplication is
carried out between the contents
of W and the register file location
‘f’. The 16-bit result is stored in
the PRODH:PRODL register
pair. PRODH contains the high
byte.
Both W and ‘f’ are unchanged.
None of the Status flags are
affected.
Note that neither Overflow nor
Carry is possible in this operation.
A Zero result is possible,
but not detected. If ‘a’ is ‘0’, the
Access Bank will be selected,
overriding the BSR value. If
‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
registers
PRODH:
PRODL
Example: MULWF REG
Before Instruction
W = 0xC4
REG = 0xB5
PRODH = ?
PRODL = ?
After Instruction
W = 0xC4
REG = 0xB5
PRODH = 0x8A
PRODL = 0x94© 2007 Microchip Technology Inc. DS39605F-page 219
PIC18F1220/1320
NEGF Negate f
Syntax: [ label ] NEGF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) + 1 → f
Status Affected: N, OV, C, DC, Z
Encoding: 0110 110a ffff ffff
Description: Location ‘f’ is negated using two’s
complement. The result is placed in
the data memory location ‘f’. If ‘a’ is
‘0’, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: NEGF REG, 1
Before Instruction
REG = 0011 1010 [0x3A]
After Instruction
REG = 1100 0110 [0xC6]
NOP No Operation
Syntax: [ label ] NOP
Operands: None
Operation: No operation
Status Affected: None
Encoding: 0000
1111
0000
xxxx
0000
xxxx
0000
xxxx
Description: No operation.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
Example:
None.PIC18F1220/1320
DS39605F-page 220 © 2007 Microchip Technology Inc.
POP Pop Top of Return Stack
Syntax: [ label ] POP
Operands: None
Operation: (TOS) → bit bucket
Status Affected: None
Encoding: 0000 0000 0000 0110
Description: The TOS value is pulled off the
return stack and is discarded. The
TOS value then becomes the
previous value that was pushed
onto the return stack.
This instruction is provided to
enable the user to properly manage
the return stack to incorporate a
software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Pop TOS
value
No
operation
Example: POP
GOTO NEW
Before Instruction
TOS = 0x0031A2
Stack (1 level down) = 0x014332
After Instruction
TOS = 0x014332
PC = NEW
PUSH Push Top of Return Stack
Syntax: [ label ] PUSH
Operands: None
Operation: (PC + 2) → TOS
Status Affected: None
Encoding: 0000 0000 0000 0101
Description: The PC + 2 is pushed onto the top
of the return stack. The previous
TOS value is pushed down on the
stack.
This instruction allows implementing
a software stack by modifying
TOS and then pushing it onto the
return stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Push
PC + 2 onto
return stack
No
operation
No
operation
Example: PUSH
Before Instruction
TOS = 0x00345A
PC = 0x000124
After Instruction
PC = 0x000126
TOS = 0x000126
Stack (1 level down) = 0x00345A© 2007 Microchip Technology Inc. DS39605F-page 221
PIC18F1220/1320
RCALL Relative Call
Syntax: [ label ] RCALL n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 → TOS,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 1nnn nnnn nnnn
Description: Subroutine call with a jump up to 1K
from the current location. First,
return address (PC + 2) is pushed
onto the stack. Then, add the 2’s
complement number ‘2n’ to the PC.
Since the PC will have incremented
to fetch the next instruction, the new
address will be PC + 2 + 2n. This
instruction is a two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Push PC to
stack
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE RCALL Jump
Before Instruction
PC = Address (HERE)
After Instruction
PC = Address (Jump)
TOS = Address (HERE + 2)
RESET Reset
Syntax: [ label ] RESET
Operands: None
Operation: Reset all registers and flags that
are affected by a MCLR Reset.
Status Affected: All
Encoding: 0000 0000 1111 1111
Description: This instruction provides a way to
execute a MCLR Reset in software.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Start
Reset
No
operation
No
operation
Example: RESET
After Instruction
Registers = Reset Value
Flags* = Reset ValuePIC18F1220/1320
DS39605F-page 222 © 2007 Microchip Technology Inc.
RETFIE Return from Interrupt
Syntax: [ label ] RETFIE [s]
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
1 → GIE/GIEH or PEIE/GIEL,
if s = 1
(WS) → W,
(STATUSS) → Status,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged.
Status Affected: GIE/GIEH, PEIE/GIEL.
Encoding: 0000 0000 0001 000s
Description: Return from interrupt. Stack is
popped and Top-of-Stack (TOS) is
loaded into the PC. Interrupts are
enabled by setting either the high
or low priority global interrupt
enable bit. If ‘s’ = 1, the contents of
the shadow registers, WS,
STATUSS and BSRS, are loaded
into their corresponding registers,
W, Status and BSR. If ‘s’ = 0, no
update of these registers occurs
(default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
Pop PC
from stack
Set GIEH or
GIEL
No
operation
No
operation
No
operation
No
operation
Example: RETFIE 1
After Interrupt
PC = TOS
W = WS
BSR = BSRS
Status = STATUSS
GIE/GIEH, PEIE/GIEL = 1
RETLW Return Literal to W
Syntax: [ label ] RETLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W,
(TOS) → PC,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 1100 kkkk kkkk
Description: W is loaded with the eight-bit literal
‘k’. The program counter is loaded
from the top of the stack (the return
address). The high address latch
(PCLATH) remains unchanged.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Pop PC
from stack,
Write to W
No
operation
No
operation
No
operation
No
operation
Example:
CALL TABLE ; W contains table
; offset value
; W now has
; table value
:
TABLE
ADDWF PCL ; W = offset
RETLW k0 ; Begin table
RETLW k1 ;
:
:
RETLW kn ; End of table
Before Instruction
W = 0x07
After Instruction
W = value of kn© 2007 Microchip Technology Inc. DS39605F-page 223
PIC18F1220/1320
RETURN Return from Subroutine
Syntax: [ label ] RETURN [s]
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
if s = 1
(WS) → W,
(STATUSS) → Status,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 0000 0001 001s
Description: Return from subroutine. The stack
is popped and the top of the stack
is loaded into the program counter.
If ‘s’= 1, the contents of the shadow
registers, WS, STATUSS and
BSRS, are loaded into their corresponding
registers, W, Status and
BSR. If ‘s’ = 0, no update of these
registers occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
Pop PC
from stack
No
operation
No
operation
No
operation
No
operation
Example: RETURN
After Interrupt
PC = TOS
RLCF Rotate Left f through Carry
Syntax: [ label ] RLCF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → C,
(C) → dest<0>
Status Affected: C, N, Z
Encoding: 0011 01da ffff ffff
Description: The contents of register ‘f’ are
rotated one bit to the left through
the Carry flag. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is stored back in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RLCF REG, W
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 1100 1100
C =1
C register fPIC18F1220/1320
DS39605F-page 224 © 2007 Microchip Technology Inc.
RLNCF Rotate Left f (no carry)
Syntax: [ label ] RLNCF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → dest<0>
Status Affected: N, Z
Encoding: 0100 01da ffff ffff
Description: The contents of register ‘f’ are
rotated one bit to the left. If ‘d’ is ‘0’,
the result is placed in W. If ‘d’ is ‘1’,
the result is stored back in register
‘f’ (default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ is ‘1’, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RLNCF REG
Before Instruction
REG = 1010 1011
After Instruction
REG = 0101 0111
register f
RRCF Rotate Right f through Carry
Syntax: [ label ] RRCF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → C,
(C) → dest<7>
Status Affected: C, N, Z
Encoding: 0011 00da ffff ffff
Description: The contents of register ‘f’ are
rotated one bit to the right through
the Carry flag. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result
is placed back in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ is ‘1’, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RRCF REG, W
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 0111 0011
C =0
C register f© 2007 Microchip Technology Inc. DS39605F-page 225
PIC18F1220/1320
RRNCF Rotate Right f (no carry)
Syntax: [ label ] RRNCF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → dest<7>
Status Affected: N, Z
Encoding: 0100 00da ffff ffff
Description: The contents of register ‘f’ are
rotated one bit to the right. If ‘d’ is
‘0’, the result is placed in W. If ‘d’ is
‘1’, the result is placed back in
register ‘f’ (default). If ‘a’ is ‘0’, the
Access Bank will be selected,
overriding the BSR value. If ‘a’ is
‘1’, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: RRNCF REG, 1, 0
Before Instruction
REG = 1101 0111
After Instruction
REG = 1110 1011
Example 2: RRNCF REG, W
Before Instruction
W =?
REG = 1101 0111
After Instruction
W = 1110 1011
REG = 1101 0111
register f
SETF Set f
Syntax: [ label ] SETF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: FFh → f
Status Affected: None
Encoding: 0110 100a ffff ffff
Description: The contents of the specified
register are set to FFh. If ‘a’ is ‘0’,
the Access Bank will be selected,
overriding the BSR value. If ‘a’ is
‘1’, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: SETF REG
Before Instruction
REG = 0x5A
After Instruction
REG = 0xFFPIC18F1220/1320
DS39605F-page 226 © 2007 Microchip Technology Inc.
SLEEP Enter Sleep mode
Syntax: [ label ] SLEEP
Operands: None
Operation: 00h → WDT,
0 → WDT postscaler,
1 → TO,
0 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0011
Description: The Power-down status bit (PD) is
cleared. The Time-out status bit
(TO) is set. The Watchdog Timer
and its postscaler are cleared.
The processor is put into Sleep
mode with the oscillator stopped.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
Go to
Sleep
Example: SLEEP
Before Instruction
TO = ?
PD = ?
After Instruction
TO = 1 †
PD = 0
† If WDT causes wake-up, this bit is cleared.
SUBFWB Subtract f from W with borrow
Syntax: [ label ] SUBFWB f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) – (f) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 01da ffff ffff
Description: Subtract register ‘f’ and Carry flag
(borrow) from W (2’s complement
method). If ‘d’ is ‘0’, the result is
stored in W. If ‘d’ is ‘1’, the result is
stored in register ‘f’ (default). If ‘a’ is
‘0’, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ is ‘1’, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBFWB REG
Before Instruction
REG = 0x03
W = 0x02
C = 0x01
After Instruction
REG = 0xFF
W = 0x02
C = 0x00
Z = 0x00
N = 0x01 ; result is negative
Example 2: SUBFWB REG, 0, 0
Before Instruction
REG = 2
W =5
C =1
After Instruction
REG = 2
W =3
C =1
Z =0
N = 0 ; result is positive
Example 3: SUBFWB REG, 1, 0
Before Instruction
REG = 1
W =2
C =0
After Instruction
REG = 0
W =2
C =1
Z = 1 ; result is zero
N =0© 2007 Microchip Technology Inc. DS39605F-page 227
PIC18F1220/1320
SUBLW Subtract W from literal
Syntax: [ label ] SUBLW k
Operands: 0 ≤ k ≤ 255
Operation: k – (W) → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1000 kkkk kkkk
Description: W is subtracted from the eight-bit
literal ‘k’. The result is placed
in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example 1: SUBLW 0x02
Before Instruction
W =1
C =?
After Instruction
W =1
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBLW 0x02
Before Instruction
W =2
C =?
After Instruction
W =0
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBLW 0x02
Before Instruction
W =3
C =?
After Instruction
W = FF ; (2’s complement)
C = 0 ; result is negative
Z =0
N =1
SUBWF Subtract W from f
Syntax: [ label ] SUBWF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 11da ffff ffff
Description: Subtract W from register ‘f’ (2’s
complement method). If ‘d’ is ‘0’,
the result is stored in W. If ‘d’ is
‘1’, the result is stored back in
register ‘f’ (default). If ‘a’ is ‘0’, the
Access Bank will be selected,
overriding the BSR value. If ‘a’ is
‘1’, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBWF REG
Before Instruction
REG = 3
W =2
C =?
After Instruction
REG = 1
W =2
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBWF REG, W
Before Instruction
REG = 2
W =2
C =?
After Instruction
REG = 2
W =0
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBWF REG
Before Instruction
REG = 0x01
W = 0x02
C =?
After Instruction
REG = 0xFFh ;(2’s complement)
W = 0x02
C = 0x00 ;result is negative
Z = 0x00
N = 0x01PIC18F1220/1320
DS39605F-page 228 © 2007 Microchip Technology Inc.
SUBWFB Subtract W from f with Borrow
Syntax: [ label ] SUBWFB f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 10da ffff ffff
Description: Subtract W and the Carry flag
(borrow) from register ‘f’ (2’s complement
method). If ‘d’ is ‘0’, the result is
stored in W. If ‘d’ is ‘1’, the result is
stored back in register ‘f’ (default). If
‘a’ is ‘0’, the Access Bank will be
selected, overriding the BSR value. If
‘a’ is ‘1’, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBWFB REG, 1, 0
Before Instruction
REG = 0x19 (0001 1001)
W = 0x0D (0000 1101)
C = 0x01
After Instruction
REG = 0x0C (0000 1011)
W = 0x0D (0000 1101)
C = 0x01
Z = 0x00
N = 0x00 ; result is positive
Example 2: SUBWFB REG, 0, 0
Before Instruction
REG = 0x1B (0001 1011)
W = 0x1A (0001 1010)
C = 0x00
After Instruction
REG = 0x1B (0001 1011)
W = 0x00
C = 0x01
Z = 0x01 ; result is zero
N = 0x00
Example 3: SUBWFB REG, 1, 0
Before Instruction
REG = 0x03 (0000 0011)
W = 0x0E (0000 1101)
C = 0x01
After Instruction
REG = 0xF5 (1111 0100)
; [2’s comp]
W = 0x0E (0000 1101)
C = 0x00
Z = 0x00
N = 0x01 ; result is negative
SWAPF Swap f
Syntax: [ label ] SWAPF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f<3:0>) → dest<7:4>,
(f<7:4>) → dest<3:0>
Status Affected: None
Encoding: 0011 10da ffff ffff
Description: The upper and lower nibbles of
register ‘f’ are exchanged. If ‘d’ is
‘0’, the result is placed in W. If ‘d’ is
‘1’, the result is placed in register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ is ‘1’, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: SWAPF REG
Before Instruction
REG = 0x53
After Instruction
REG = 0x35© 2007 Microchip Technology Inc. DS39605F-page 229
PIC18F1220/1320
TBLRD Table Read
Syntax: [ label ] TBLRD ( *; *+; *-; +*)
Operands: None
Operation: if TBLRD *,
(Prog Mem (TBLPTR)) → TABLAT;
TBLPTR – No Change;
if TBLRD *+,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) + 1 → TBLPTR;
if TBLRD *-,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) – 1 → TBLPTR;
if TBLRD +*,
(TBLPTR) + 1 → TBLPTR;
(Prog Mem (TBLPTR)) → TABLAT;
Status Affected: None
Encoding: 0000 0000 0000 10nn
nn = 0*
= 1*+
= 2*-
= 3+*
Description: This instruction is used to read the
contents of Program Memory (P.M.). To
address the program memory, a pointer
called Table Pointer (TBLPTR) is used.
The TBLPTR (a 21-bit pointer) points
to each byte in the program memory.
TBLPTR has a 2-Mbyte address
range.
TBLPTR[0] = 0: Least Significant
Byte of Program
Memory Word
TBLPTR[0] = 1: Most Significant
Byte of Program
Memory Word
The TBLRD instruction can modify the
value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No operation
(Read Program
Memory)
No
operation
No operation
(Write
TABLAT)
TBLRD Table Read (Continued)
Example 1: TBLRD *+ ;
Before Instruction
TABLAT = 0x55
TBLPTR = 0x00A356
MEMORY(0x00A356) = 0x34
After Instruction
TABLAT = 0x34
TBLPTR = 0x00A357
Example 2: TBLRD +* ;
Before Instruction
TABLAT = 0xAA
TBLPTR = 0x01A357
MEMORY(0x01A357) = 0x12
MEMORY(0x01A358) = 0x34
After Instruction
TABLAT = 0x34
TBLPTR = 0x01A358PIC18F1220/1320
DS39605F-page 230 © 2007 Microchip Technology Inc.
TBLWT Table Write
Syntax: [ label ] TBLWT ( *; *+; *-; +*)
Operands: None
Operation: if TBLWT*,
(TABLAT) → Holding Register;
TBLPTR – No Change;
if TBLWT*+,
(TABLAT) → Holding Register;
(TBLPTR) + 1 → TBLPTR;
if TBLWT*-,
(TABLAT) → Holding Register;
(TBLPTR) – 1 → TBLPTR;
if TBLWT+*,
(TBLPTR) + 1 → TBLPTR;
(TABLAT) → Holding Register;
Status Affected: None
Encoding: 0000 0000 0000 11nn
nn = 0*
= 1*+
= 2*-
= 3+*
Description: This instruction uses the 3 LSBs of
TBLPTR to determine which of the
8 holding registers the TABLAT is
written to. The holding registers are
used to program the contents of
Program Memory (P.M.). (Refer
to Section 6.0 “Flash Program
Memory” for additional details on
programming Flash memory.)
The TBLPTR (a 21-bit pointer) points
to each byte in the program memory.
TBLPTR has a 2-Mbyte address
range. The LSb of the TBLPTR
selects which byte of the program
memory location to access.
TBLPTR[0] = 0:Least Significant
Byte of Program
Memory Word
TBLPTR[0] = 1:Most Significant
Byte of Program
Memory Word
The TBLWT instruction can modify the
value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
TBLWT Table Write (Continued)
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No
operation
(Read
TABLAT)
No
operation
No
operation
(Write to
Holding
Register)
Example 1: TBLWT *+;
Before Instruction
TABLAT = 0x55
TBLPTR = 0x00A356
HOLDING REGISTER
(0x00A356) = 0xFF
After Instructions (table write completion)
TABLAT = 0x55
TBLPTR = 0x00A357
HOLDING REGISTER
(0x00A356) = 0x55
Example 2: TBLWT +*;
Before Instruction
TABLAT = 0x34
TBLPTR = 0x01389A
HOLDING REGISTER
(0x01389A) = 0xFF
HOLDING REGISTER
(0x01389B) = 0xFF
After Instruction (table write completion)
TABLAT = 0x34
TBLPTR = 0x01389B
HOLDING REGISTER
(0x01389A) = 0xFF
HOLDING REGISTER
(0x01389B) = 0x34© 2007 Microchip Technology Inc. DS39605F-page 231
PIC18F1220/1320
TSTFSZ Test f, skip if 0
Syntax: [ label ] TSTFSZ f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: skip if f = 0
Status Affected: None
Encoding: 0110 011a ffff ffff
Description: If ‘f’ = 0, the next instruction,
fetched during the current
instruction execution is discarded
and a NOP is executed, making this
a two-cycle instruction. If ‘a’ is ‘0’,
the Access Bank will be selected,
overriding the BSR value. If ‘a’ is
‘1’, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE TSTFSZ CNT
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
If CNT = 0x00,
PC = Address (ZERO)
If CNT ≠ 0x00,
PC = Address (NZERO)
XORLW Exclusive OR literal with W
Syntax: [ label ] XORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .XOR. k → W
Status Affected: N, Z
Encoding: 0000 1010 kkkk kkkk
Description: The contents of W are XOR’ed
with the 8-bit literal ‘k’. The result
is placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: XORLW 0xAF
Before Instruction
W = 0xB5
After Instruction
W = 0x1APIC18F1220/1320
DS39605F-page 232 © 2007 Microchip Technology Inc.
XORWF Exclusive OR W with f
Syntax: [ label ] XORWF f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .XOR. (f) → dest
Status Affected: N, Z
Encoding: 0001 10da ffff ffff
Description: Exclusive OR the contents of W
with register ‘f’. If ‘d’ is ‘0’, the result
is stored in W. If ‘d’ is ‘1’, the result
is stored back in the register ‘f’
(default). If ‘a’ is ‘0’, the Access
Bank will be selected, overriding
the BSR value. If ‘a’ is ‘1’, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: XORWF REG
Before Instruction
REG = 0xAF
W = 0xB5
After Instruction
REG = 0x1A
W = 0xB5© 2007 Microchip Technology Inc. DS39605F-page 233
PIC18F1220/1320
21.0 DEVELOPMENT SUPPORT
The PIC® microcontrollers are supported with a full
range of hardware and software development tools:
• Integrated Development Environment
- MPLAB® IDE Software
• Assemblers/Compilers/Linkers
- MPASMTM Assembler
- MPLAB C18 and MPLAB C30 C Compilers
- MPLINKTM Object Linker/
MPLIBTM Object Librarian
- MPLAB ASM30 Assembler/Linker/Library
• Simulators
- MPLAB SIM Software Simulator
• Emulators
- MPLAB ICE 2000 In-Circuit Emulator
- MPLAB REAL ICE™ In-Circuit Emulator
• In-Circuit Debugger
- MPLAB ICD 2
• Device Programmers
- PICSTART® Plus Development Programmer
- MPLAB PM3 Device Programmer
- PICkit™ 2 Development Programmer
• Low-Cost Demonstration and Development
Boards and Evaluation Kits
21.1 MPLAB Integrated Development
Environment Software
The MPLAB IDE software brings an ease of software
development previously unseen in the 8/16-bit microcontroller
market. The MPLAB IDE is a Windows®
operating system-based application that contains:
• A single graphical interface to all debugging tools
- Simulator
- Programmer (sold separately)
- Emulator (sold separately)
- In-Circuit Debugger (sold separately)
• A full-featured editor with color-coded context
• A multiple project manager
• Customizable data windows with direct edit of
contents
• High-level source code debugging
• Visual device initializer for easy register
initialization
• Mouse over variable inspection
• Drag and drop variables from source to watch
windows
• Extensive on-line help
• Integration of select third party tools, such as
HI-TECH Software C Compilers and IAR
C Compilers
The MPLAB IDE allows you to:
• Edit your source files (either assembly or C)
• One touch assemble (or compile) and download
to PIC MCU emulator and simulator tools
(automatically updates all project information)
• Debug using:
- Source files (assembly or C)
- Mixed assembly and C
- Machine code
MPLAB IDE supports multiple debugging tools in a
single development paradigm, from the cost-effective
simulators, through low-cost in-circuit debuggers, to
full-featured emulators. This eliminates the learning
curve when upgrading to tools with increased flexibility
and power.PIC18F1220/1320
DS39605F-page 234 © 2007 Microchip Technology Inc.
21.2 MPASM Assembler
The MPASM Assembler is a full-featured, universal
macro assembler for all PIC MCUs.
The MPASM Assembler generates relocatable object
files for the MPLINK Object Linker, Intel® standard HEX
files, MAP files to detail memory usage and symbol
reference, absolute LST files that contain source lines
and generated machine code and COFF files for
debugging.
The MPASM Assembler features include:
• Integration into MPLAB IDE projects
• User-defined macros to streamline
assembly code
• Conditional assembly for multi-purpose
source files
• Directives that allow complete control over the
assembly process
21.3 MPLAB C18 and MPLAB C30
C Compilers
The MPLAB C18 and MPLAB C30 Code Development
Systems are complete ANSI C compilers for
Microchip’s PIC18 family of microcontrollers and the
dsPIC30, dsPIC33 and PIC24 family of digital signal
controllers. These compilers provide powerful integration
capabilities, superior code optimization and ease
of use not found with other compilers.
For easy source level debugging, the compilers provide
symbol information that is optimized to the MPLAB IDE
debugger.
21.4 MPLINK Object Linker/
MPLIB Object Librarian
The MPLINK Object Linker combines relocatable
objects created by the MPASM Assembler and the
MPLAB C18 C Compiler. It can link relocatable objects
from precompiled libraries, using directives from a
linker script.
The MPLIB Object Librarian manages the creation and
modification of library files of precompiled code. When
a routine from a library is called from a source file, only
the modules that contain that routine will be linked in
with the application. This allows large libraries to be
used efficiently in many different applications.
The object linker/library features include:
• Efficient linking of single libraries instead of many
smaller files
• Enhanced code maintainability by grouping
related modules together
• Flexible creation of libraries with easy module
listing, replacement, deletion and extraction
21.5 MPLAB ASM30 Assembler, Linker
and Librarian
MPLAB ASM30 Assembler produces relocatable
machine code from symbolic assembly language for
dsPIC30F devices. MPLAB C30 C Compiler uses the
assembler to produce its object file. The assembler
generates relocatable object files that can then be
archived or linked with other relocatable object files and
archives to create an executable file. Notable features
of the assembler include:
• Support for the entire dsPIC30F instruction set
• Support for fixed-point and floating-point data
• Command line interface
• Rich directive set
• Flexible macro language
• MPLAB IDE compatibility
21.6 MPLAB SIM Software Simulator
The MPLAB SIM Software Simulator allows code
development in a PC-hosted environment by simulating
the PIC MCUs and dsPIC® DSCs on an instruction
level. On any given instruction, the data areas can be
examined or modified and stimuli can be applied from
a comprehensive stimulus controller. Registers can be
logged to files for further run-time analysis. The trace
buffer and logic analyzer display extend the power of
the simulator to record and track program execution,
actions on I/O, most peripherals and internal registers.
The MPLAB SIM Software Simulator fully supports
symbolic debugging using the MPLAB C18 and
MPLAB C30 C Compilers, and the MPASM and
MPLAB ASM30 Assemblers. The software simulator
offers the flexibility to develop and debug code outside
of the hardware laboratory environment, making it an
excellent, economical software development tool. © 2007 Microchip Technology Inc. DS39605F-page 235
PIC18F1220/1320
21.7 MPLAB ICE 2000
High-Performance
In-Circuit Emulator
The MPLAB ICE 2000 In-Circuit Emulator is intended
to provide the product development engineer with a
complete microcontroller design tool set for PIC
microcontrollers. Software control of the MPLAB ICE
2000 In-Circuit Emulator is advanced by the MPLAB
Integrated Development Environment, which allows
editing, building, downloading and source debugging
from a single environment.
The MPLAB ICE 2000 is a full-featured emulator
system with enhanced trace, trigger and data monitoring
features. Interchangeable processor modules allow
the system to be easily reconfigured for emulation of
different processors. The architecture of the MPLAB
ICE 2000 In-Circuit Emulator allows expansion to
support new PIC microcontrollers.
The MPLAB ICE 2000 In-Circuit Emulator system has
been designed as a real-time emulation system with
advanced features that are typically found on more
expensive development tools. The PC platform and
Microsoft® Windows® 32-bit operating system were
chosen to best make these features available in a
simple, unified application.
21.8 MPLAB REAL ICE In-Circuit
Emulator System
MPLAB REAL ICE In-Circuit Emulator System is
Microchip’s next generation high-speed emulator for
Microchip Flash DSC® and MCU devices. It debugs and
programs PIC® and dsPIC® Flash microcontrollers with
the easy-to-use, powerful graphical user interface of the
MPLAB Integrated Development Environment (IDE),
included with each kit.
The MPLAB REAL ICE probe is connected to the design
engineer’s PC using a high-speed USB 2.0 interface and
is connected to the target with either a connector
compatible with the popular MPLAB ICD 2 system
(RJ11) or with the new high speed, noise tolerant, lowvoltage
differential signal (LVDS) interconnection
(CAT5).
MPLAB REAL ICE is field upgradeable through future
firmware downloads in MPLAB IDE. In upcoming
releases of MPLAB IDE, new devices will be supported,
and new features will be added, such as software breakpoints
and assembly code trace. MPLAB REAL ICE
offers significant advantages over competitive emulators
including low-cost, full-speed emulation, real-time
variable watches, trace analysis, complex breakpoints, a
ruggedized probe interface and long (up to three meters)
interconnection cables.
21.9 MPLAB ICD 2 In-Circuit Debugger
Microchip’s In-Circuit Debugger, MPLAB ICD 2, is a
powerful, low-cost, run-time development tool,
connecting to the host PC via an RS-232 or high-speed
USB interface. This tool is based on the Flash PIC
MCUs and can be used to develop for these and other
PIC MCUs and dsPIC DSCs. The MPLAB ICD 2 utilizes
the in-circuit debugging capability built into the Flash
devices. This feature, along with Microchip’s In-Circuit
Serial ProgrammingTM (ICSPTM) protocol, offers costeffective,
in-circuit Flash debugging from the graphical
user interface of the MPLAB Integrated Development
Environment. This enables a designer to develop and
debug source code by setting breakpoints, single stepping
and watching variables, and CPU status and
peripheral registers. Running at full speed enables
testing hardware and applications in real time. MPLAB
ICD 2 also serves as a development programmer for
selected PIC devices.
21.10 MPLAB PM3 Device Programmer
The MPLAB PM3 Device Programmer is a universal,
CE compliant device programmer with programmable
voltage verification at VDDMIN and VDDMAX for
maximum reliability. It features a large LCD display
(128 x 64) for menus and error messages and a modular,
detachable socket assembly to support various
package types. The ICSP™ cable assembly is included
as a standard item. In Stand-Alone mode, the MPLAB
PM3 Device Programmer can read, verify and program
PIC devices without a PC connection. It can also set
code protection in this mode. The MPLAB PM3
connects to the host PC via an RS-232 or USB cable.
The MPLAB PM3 has high-speed communications and
optimized algorithms for quick programming of large
memory devices and incorporates an SD/MMC card for
file storage and secure data applications.PIC18F1220/1320
DS39605F-page 236 © 2007 Microchip Technology Inc.
21.11 PICSTART Plus Development
Programmer
The PICSTART Plus Development Programmer is an
easy-to-use, low-cost, prototype programmer. It
connects to the PC via a COM (RS-232) port. MPLAB
Integrated Development Environment software makes
using the programmer simple and efficient. The
PICSTART Plus Development Programmer supports
most PIC devices in DIP packages up to 40 pins.
Larger pin count devices, such as the PIC16C92X and
PIC17C76X, may be supported with an adapter socket.
The PICSTART Plus Development Programmer is CE
compliant.
21.12 PICkit 2 Development Programmer
The PICkit™ 2 Development Programmer is a low-cost
programmer and selected Flash device debugger with
an easy-to-use interface for programming many of
Microchip’s baseline, mid-range and PIC18F families of
Flash memory microcontrollers. The PICkit 2 Starter Kit
includes a prototyping development board, twelve
sequential lessons, software and HI-TECH’s PICC™
Lite C compiler, and is designed to help get up to speed
quickly using PIC® microcontrollers. The kit provides
everything needed to program, evaluate and develop
applications using Microchip’s powerful, mid-range
Flash memory family of microcontrollers.
21.13 Demonstration, Development and
Evaluation Boards
A wide variety of demonstration, development and
evaluation boards for various PIC MCUs and dsPIC
DSCs allows quick application development on fully functional
systems. Most boards include prototyping areas for
adding custom circuitry and provide application firmware
and source code for examination and modification.
The boards support a variety of features, including LEDs,
temperature sensors, switches, speakers, RS-232
interfaces, LCD displays, potentiometers and additional
EEPROM memory.
The demonstration and development boards can be
used in teaching environments, for prototyping custom
circuits and for learning about various microcontroller
applications.
In addition to the PICDEM™ and dsPICDEM™ demonstration/development
board series of circuits, Microchip
has a line of evaluation kits and demonstration software
for analog filter design, KEELOQ® security ICs, CAN,
IrDA®, PowerSmart® battery management, SEEVAL®
evaluation system, Sigma-Delta ADC, flow rate
sensing, plus many more.
Check the Microchip web page (www.microchip.com)
and the latest “Product Selector Guide” (DS00148) for
the complete list of demonstration, development and
evaluation kits.© 2007 Microchip Technology Inc. DS39605F-page 237
PIC18F1220/1320
22.0 ELECTRICAL CHARACTERISTICS
Absolute Maximum Ratings(†)
Ambient temperature under bias.............................................................................................................-40°C to +125°C
Storage temperature .............................................................................................................................. -65°C to +150°C
Voltage on any pin with respect to VSS (except VDD, MCLR and RA4) .......................................... -0.3V to (VDD + 0.3V)
Voltage on VDD with respect to VSS ......................................................................................................... -0.3V to +5.5V
Voltage on MCLR with respect to VSS (Note 2) ......................................................................................... 0V to +13.25V
Voltage on RA4 with respect to Vss............................................................................................................... 0V to +8.5V
Total power dissipation (Note 1) ...............................................................................................................................1.0W
Maximum current out of VSS pin ...........................................................................................................................300 mA
Maximum current into VDD pin ..............................................................................................................................250 mA
Input clamp current, IIK (VI < 0 or VI > VDD)...................................................................................................................... ±20 mA
Output clamp current, IOK (VO < 0 or VO > VDD) .............................................................................................................. ±20 mA
Maximum output current sunk by any I/O pin..........................................................................................................25 mA
Maximum output current sourced by any I/O pin ....................................................................................................25 mA
Maximum current sunk by all ports .......................................................................................................................200 mA
Maximum current sourced by all ports ..................................................................................................................200 mA
Note 1: Power dissipation is calculated as follows:
Pdis = VDD x {IDD – ∑ IOH} + ∑ {(VDD – VOH) x IOH} + ∑(VOL x IOL)
2: Voltage spikes below VSS at the MCLR/VPP pin, inducing currents greater than 80 mA, may cause latch-up.
Thus, a series resistor of 50-100Ω should be used when applying a “low” level to the MCLR/VPP pin, rather
than pulling this pin directly to VSS.
† NOTICE: Stresses above those listed under “Absolute Maximum Ratings” may cause permanent damage to the
device. This is a stress rating only and functional operation of the device at those or any other conditions above those
indicated in the operation listings of this specification is not implied. Exposure to maximum rating conditions for
extended periods may affect device reliability.PIC18F1220/1320
DS39605F-page 238 © 2007 Microchip Technology Inc.
FIGURE 22-1: PIC18F1220/1320 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
FIGURE 22-2: PIC18LF1220/1320 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
PIC18F1X20
4.2V
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
FMAX = (16.36 MHz/V) (VDDAPPMIN – 2.0V) + 4 MHz
Note: VDDAPPMIN is the minimum voltage of the PIC® device in the application.
4 MHz
4.2V
PIC18LF1X20© 2007 Microchip Technology Inc. DS39605F-page 239
PIC18F1220/1320
FIGURE 22-3: PIC18F1220/1320 VOLTAGE-FREQUENCY GRAPH (EXTENDED)
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
25 MHz
5.0V
3.5V
3.0V
2.5V
PIC18F1X20-E
4.2VPIC18F1220/1320
DS39605F-page 240 © 2007 Microchip Technology Inc.
22.1 DC Characteristics: Supply Voltage
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
VDD Supply Voltage
D001 PIC18LF1220/1320 2.0 — 5.5 V HS, XT, RC and LP Oscillator mode
PIC18F1220/1320 4.2 — 5.5 V
D002 VDR RAM Data Retention
Voltage(1)
1.5 — — V
D003 VPOR VDD Start Voltage to ensure
internal Power-on Reset signal
— — 0.7 V See Section 4.1 “Power-on Reset (POR)”
for details.
D004 SVDD VDD Rise Rate to ensure
internal Power-on Reset signal
0.05 — — V/ms See Section 4.1 “Power-on Reset (POR)”
for details.
VBOR Brown-out Reset Voltage
D005D PIC18LF1220/1320 Industrial Low Voltage (-10°C to +85°C)
BORV1:BORV0 = 11 N/A N/A N/A V Reserved
BORV1:BORV0 = 10 2.50 2.72 2.94 V
BORV1:BORV0 = 01 3.88 4.22 4.56 V (Note 2)
BORV1:BORV0 = 00 4.18 4.54 4.90 V (Note 2)
D005F PIC18LF1220/1320 Industrial Low Voltage (-40°C to -10°C)
BORV1:BORV0 = 11 N/A N/A N/A V Reserved
BORV1:BORV0 = 10 2.34 2.72 3.10 V
BORV1:BORV0 = 01 3.63 4.22 4.81 V (Note 2)
BORV1:BORV0 = 00 3.90 4.54 5.18 V (Note 2)
D005G PIC18F1220/1320 Industrial (-10°C to +85°C)
BORV1:BORV0 = 1x N/A N/A N/A V Reserved
BORV1:BORV0 = 01 3.88 4.22 4.56 V (Note 2)
BORV1:BORV0 = 00 4.18 4.54 4.90 V (Note 2)
D005H PIC18F1220/1320 Industrial (-40°C to -10°C)
BORV1:BORV0 = 1x N/A N/A N/A V Reserved
BORV1:BORV0 = 01 N/A N/A N/A V Reserved
BORV1:BORV0 = 00 3.90 4.54 5.18 V (Note 2)
D005J PIC18F1220/1320 Extended (-10°C to +85°C)
BORV1:BORV0 = 1x N/A N/A N/A V Reserved
BORV1:BORV0 = 01 3.88 4.22 4.56 V (Note 3)
BORV1:BORV0 = 00 4.18 4.54 4.90 V (Note 3)
D005K PIC18F1220/1320 Extended (-40°C to -10°C, +85°C to +125°C)
BORV1:BORV0 = 1x N/A N/A N/A V Reserved
BORV1:BORV0 = 01 N/A N/A N/A V Reserved
BORV1:BORV0 = 00 3.90 4.54 5.18 V (Note 3)
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in Sleep mode, or during a device Reset, without losing RAM data.
2: When BOR is on and BORV<1:0> = 0x, the device will operate correctly at 40 MHz for any VDD at which the BOR allows
execution (low-voltage and industrial devices only).
3: When BOR is on and BORV<1:0> = 0x, the device will operate correctly at 25 MHz for any VDD at which the BOR allows
execution (extended devices only).© 2007 Microchip Technology Inc. DS39605F-page 241
PIC18F1220/1320
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Power-Down Current (IPD)
(1)
PIC18LF1220/1320 0.1 0.5 μA -40°C
VDD = 2.0V,
(Sleep mode) 0.1 0.5 μA +25°C
0.2 1.9 μA +85°C
PIC18LF1220/1320 0.1 0.5 μA -40°C
VDD = 3.0V,
(Sleep mode) 0.1 0.5 μA + 25°C
0.3 1.9 μA +85°C
All devices 0.1 2.0 μA -40°C
VDD = 5.0V,
(Sleep mode)
0.1 2.0 μA +25°C
0.4 6.5 μA +85°C
Extended devices 11.2 50 μA +125°C
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 8 40 μA -40°C
FOSC = 31 kHz
(RC_RUN mode,
Internal oscillator source)
9 40 μA +25°C VDD = 2.0V
11 40 μA +85°C
PIC18LF1220/1320 25 68 μA -40°C
25 68 μA +25°C VDD = 3.0V
20 68 μA +85°C
All devices 55 80 μA -40°C
VDD = 5.0V
55 80 μA +25°C
50 80 μA +85°C
Extended devices 50 80 μA +125°C
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.PIC18F1220/1320
DS39605F-page 242 © 2007 Microchip Technology Inc.
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 140 220 μA -40°C
FOSC = 1 MHz
(RC_RUN mode,
Internal oscillator source)
145 220 μA +25°C VDD = 2.0V
155 220 μA +85°C
PIC18LF1220/1320 215 330 μA -40°C
225 330 μA +25°C VDD = 3.0V
235 330 μA +85°C
All devices 385 550 μA -40°C
VDD = 5.0V
390 550 μA +25°C
405 550 μA +85°C
Extended devices 410 650 μA +125°C
PIC18LF1220/1320 410 600 μA -40°C
FOSC = 4 MHz
(RC_RUN mode,
Internal oscillator source)
425 600 μA +25°C VDD = 2.0V
435 600 μA +85°C
PIC18LF1220/1320 650 900 μA -40°C
670 900 μA +25°C VDD = 3.0V
680 900 μA +85°C
All devices 1.2 1.8 mA -40°C
VDD = 5.0V
1.2 1.8 mA +25°C
1.2 1.8 mA +85°C
Extended devices 1.2 1.8 mA +125°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.© 2007 Microchip Technology Inc. DS39605F-page 243
PIC18F1220/1320
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 4.7 8 μA -40°C
FOSC = 31 kHz
(RC_IDLE mode,
Internal oscillator source)
5.0 8 μA +25°C VDD = 2.0V
5.8 11 μA +85°C
PIC18LF1220/1320 7.0 11 μA -40°C
7.8 11 μA +25°C VDD = 3.0V
8.7 15 μA +85°C
All devices 12 16 μA -40°C
VDD = 5.0V
14 16 μA +25°C
14 22 μA +85°C
Extended devices 25 75 μA +125°C
PIC18LF1220/1320 75 150 μA -40°C
FOSC = 1 MHz
(RC_IDLE mode,
Internal oscillator source)
85 150 μA +25°C VDD = 2.0V
95 150 μA +85°C
PIC18LF1220/1320 110 180 μA -40°C
125 180 μA +25°C VDD = 3.0V
135 180 μA +85°C
All devices 180 380 μA -40°C
VDD = 5.0V
195 380 μA +25°C
200 380 μA +85°C
Extended devices 350 435 μA +125°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.PIC18F1220/1320
DS39605F-page 244 © 2007 Microchip Technology Inc.
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 140 275 μA -40°C
FOSC = 4 MHz
(RC_IDLE mode,
Internal oscillator source)
140 275 μA +25°C VDD = 2.0V
150 275 μA +85°C
PIC18LF1220/1320 220 375 μA -40°C
220 375 μA +25°C VDD = 3.0V
220 375 μA +85°C
All devices 390 800 μA -40°C
VDD = 5.0V
400 800 μA +25°C
380 800 μA +85°C
Extended devices 410 800 μA +125°C
PIC18LF1220/1320 150 250 μA -40°C
FOSC = 1 MHZ
(PRI_RUN mode,
EC oscillator)
150 250 μA +25°C VDD = 2.0V
160 250 μA +85°C
PIC18LF1220/1320 340 350 μA -40°C
300 350 μA +25°C VDD = 3.0V
280 350 μA +85°C
All devices 0.72 1.0 mA -40°C
VDD = 5.0V
0.63 1.0 mA +25°C
0.58 1.0 mA +85°C
Extended devices 0.53 1.0 mA +125°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.© 2007 Microchip Technology Inc. DS39605F-page 245
PIC18F1220/1320
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 415 600 μA -40°C
FOSC = 4 MHz
(PRI_RUN mode,
EC oscillator)
425 600 μA +25°C VDD = 2.0V
435 600 μA +85°C
PIC18LF1220/1320 0.87 1.0 mA -40°C
0.75 1.0 mA +25°C VDD = 3.0V
0.75 1.0 mA +85°C
All devices 1.6 2.0 mA -40°C
VDD = 5.0V
1.6 2.0 mA +25°C
1.5 2.0 mA +85°C
Extended devices 1.5 2.0 mA +125°C
Extended devices 6.3 9.0 mA +125°C VDD = 4.2V FOSC = 25 MHz
(PRI_RUN mode,
EC oscillator)
9.7 10.0 mA +125°C VDD = 5.0V
All devices 9.4 12 mA -40°C
FOSC = 40 MHZ
(PRI_RUN mode,
EC oscillator)
9.5 12 mA +25°C VDD = 4.2V
9.6 12 mA +85°C
All devices 11.9 15 mA -40°C
12.1 15 mA +25°C VDD = 5.0V
12.2 15 mA +85°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.PIC18F1220/1320
DS39605F-page 246 © 2007 Microchip Technology Inc.
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 35 50 μA -40°C
FOSC = 1 MHz
(PRI_IDLE mode,
EC oscillator)
35 50 μA +25°C VDD = 2.0V
35 60 μA +85°C
PIC18LF1220/1320 55 80 μA -40°C
50 80 μA +25°C VDD = 3.0V
60 100 μA +85°C
All devices 105 150 μA -40°C
VDD = 5.0V
110 150 μA +25°C
115 150 μA +85°C
Extended devices 125 300 μA +125°C
PIC18LF1220/1320 135 180 μA -40°C
FOSC = 4 MHz
(PRI_IDLE mode,
EC oscillator)
140 180 μA +25°C VDD = 2.0V
140 180 μA +85°C
PIC18LF1220/1320 215 280 μA -40°C
225 280 μA +25°C VDD = 3.0V
230 280 μA +85°C
All devices 410 525 μA -40°C
VDD = 5.0V
420 525 μA +25°C
430 525 μA +85°C
Extended devices 450 800 μA +125°C
Extended devices 2.2 3.0 mA +125°C VDD = 4.2V FOSC = 25 MHz
(PRI_IDLE mode,
EC oscillator)
2.7 3.5 mA +125°C VDD = 5.0V
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.© 2007 Microchip Technology Inc. DS39605F-page 247
PIC18F1220/1320
Supply Current (IDD)
(2,3)
All devices 3.2 4.1 mA -40°C
FOSC = 40 MHz
(PRI_IDLE mode,
EC oscillator)
3.2 4.1 mA +25°C VDD = 4.2 V
3.3 4.1 mA +85°C
All devices 4.0 5.1 mA -40°C
4.1 5.1 mA +25°C VDD = 5.0V
4.1 5.1 mA +85°C
PIC18LF1220/1320 5.1 9 μA -10°C
FOSC = 32 kHz(4)
(SEC_RUN mode,
Timer1 as clock)
5.8 9 μA +25°C VDD = 2.0V
7.9 11 μA +70°C
PIC18LF1220/1320 7.9 12 μA -10°C
8.9 12 μA +25°C VDD = 3.0V
10.5 14 μA +70°C
All devices 12.5 20 μA -10°C
16.3 20 μA +25°C VDD = 5.0V
18.4 25 μA +70°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.PIC18F1220/1320
DS39605F-page 248 © 2007 Microchip Technology Inc.
Supply Current (IDD)
(2,3)
PIC18LF1220/1320 9.2 15 μA -10°C
FOSC = 32 kHz(4)
(SEC_IDLE mode,
Timer1 as clock)
9.6 15 μA +25°C VDD = 2.0V
12.7 18 μA +70°C
PIC18LF1220/1320 22 30 μA -10°C
21 30 μA +25°C VDD = 3.0V
20 35 μA +70°C
All devices 50 80 μA -10°C
45 80 μA +25°C VDD = 5.0V
45 80 μA +70°C
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.© 2007 Microchip Technology Inc. DS39605F-page 249
PIC18F1220/1320
Module Differential Currents (ΔIWDT, ΔIBOR, ΔILVD, ΔIOSCB, ΔIAD)
D022
(ΔIWDT)
Watchdog Timer 1.5 4.0 μA -40°C
2.2 4.0 μA +25°C VDD = 2.0V
3.1 5.0 μA +85°C
2.5 6.0 μA -40°C
3.3 6.0 μA +25°C VDD = 3.0V
4.7 7.0 μA +85°C
3.7 10.0 μA -40°C
4.5 10.0 μA +25°C VDD = 5.0V
6.1 13.0 μA +85°C
D022A
(ΔIBOR)
Brown-out Reset 19 35.0 μA -40°C to +85°C VDD = 3.0V
24 45.0 μA -40°C to +85°C VDD = 5.0V
D022B
(ΔILVD)
Low-Voltage Detect 8.5 25.0 μA -40°C to +85°C VDD = 2.0V
16 35.0 μA -40°C to +85°C VDD = 3.0V
20 45.0 μA -40°C to +85°C VDD = 5.0V
D025
(ΔIOSCB)
Timer1 Oscillator 1.7 3.5 μA -40°C
1.8 3.5 μA +25°C VDD = 2.0V 32 kHz on Timer1(4)
2.1 4.5 μA +85°C
2.2 4.5 μA -40°C
2.6 4.5 μA +25°C VDD = 3.0V 32 kHz on Timer1(4)
2.8 5.5 μA +85°C
3.0 6.0 μA -40°C
3.3 6.0 μA +25°C VDD = 5.0V 32 kHz on Timer1(4)
3.6 7.0 μA +85°C
D026
(ΔIAD)
A/D Converter 1.0 3.0 μA -40°C to +85°C VDD = 2.0V
A/D on, not converting
1.0 4.0 μA -40°C to +85°C VDD = 3.0V
2.0 10.0 μA -40°C to +85°C VDD = 5.0V
1.0 8.0 μA -40°C to +125°C VDD = 5.0V
22.2 DC Characteristics: Power-Down and Supply Current
PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured with
the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that add delta
current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin loading
and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have an impact on
the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD;
MCLR = VDD; WDT enabled/disabled as specified.
3: For RC oscillator configurations, current through REXT is not included. The current through the resistor can be estimated
by the formula Ir = VDD/2REXT (mA) with REXT in kΩ.
4: Standard low-cost 32 kHz crystals have an operating temperature range of -10°C to +70°C. Extended temperature
crystals are available at a much higher cost.PIC18F1220/1320
DS39605F-page 250 © 2007 Microchip Technology Inc.
22.3 DC Characteristics: PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial)
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Max Units Conditions
VIL Input Low Voltage
I/O ports:
D030 with TTL buffer VSS 0.15 VDD V VDD < 4.5V
D030A — 0.8 V 4.5V ≤ VDD ≤ 5.5V
D031 with Schmitt Trigger buffer VSS 0.2 VDD V
D032 MCLR VSS 0.2 VDD V
D032A OSC1 (in XT, HS and LP modes)
and T1OSI
VSS 0.3 VDD V
D033 OSC1 (in RC and EC mode)(1) VSS 0.2 VDD V
VIH Input High Voltage
I/O ports:
D040 with TTL buffer 0.25 VDD + 0.8V VDD V VDD < 4.5V
D040A 2.0 VDD V 4.5V ≤ VDD ≤ 5.5V
D041 with Schmitt Trigger buffer 0.8 VDD VDD V
D042 MCLR, OSC1 (EC mode) 0.8 VDD VDD V
D042A OSC1 (in XT, HS and LP modes)
and T1OSI
1.6 VDD VDD V
D043 OSC1 (RC mode)(1) 0.9 VDD VDD V
IIL Input Leakage Current(2,3)
D060 I/O ports — ±1 μA VSS ≤ VPIN ≤ VDD,
Pin at high-impedance
D061 MCLR — ±5 μA VSS ≤ VPIN ≤ VDD
D063 OSC1 — ±5 μA VSS ≤ VPIN ≤ VDD
IPU Weak Pull-up Current
D070 IPURB PORTB weak pull-up current 50 400 μA VDD = 5V, VPIN = VSS
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PIC® device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.
4: Parameter is characterized but not tested.© 2007 Microchip Technology Inc. DS39605F-page 251
PIC18F1220/1320
VOL Output Low Voltage
D080 I/O ports — 0.6 V IOL = 8.5 mA, VDD = 4.5V,
-40°C to +85°C
D083 OSC2/CLKO
(RC mode)
— 0.6 V IOL = 1.6 mA, VDD = 4.5V,
-40°C to +85°C
VOH Output High Voltage(3)
D090 I/O ports VDD – 0.7 — V IOH = -3.0 mA, VDD = 4.5V,
-40°C to +85°C
D092 OSC2/CLKO
(RC mode)
VDD – 0.7 — V IOH = -1.3 mA, VDD = 4.5V,
-40°C to +85°C
D150 VOD Open-Drain High Voltage — 8.5 V RA4 pin
Capacitive Loading Specs
on Output Pins
D100(4) COSC2 OSC2 pin — 15 pF In XT, HS and LP modes
when external clock is
used to drive OSC1
D101 CIO All I/O pins and OSC2
(in RC mode)
— 50 pF To meet the AC timing
specifications
D102 CB SCL, SDA — 400 pF In I2C mode
22.3 DC Characteristics: PIC18F1220/1320 (Industrial)
PIC18LF1220/1320 (Industrial) (Continued)
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Max Units Conditions
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PIC® device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.
4: Parameter is characterized but not tested.PIC18F1220/1320
DS39605F-page 252 © 2007 Microchip Technology Inc.
TABLE 22-1: MEMORY PROGRAMMING REQUIREMENTS
DC CHARACTERISTICS Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Sym Characteristic Min Typ† Max Units Conditions
Internal Program Memory
Programming Specifications(1)
D110 VPP Voltage on MCLR/VPP pin 9.00 — 13.25 V (Note 2)
D112 IPP Current into MCLR/VPP pin — — 5 μA
D113 IDDP Supply Current during
Programming
— — 10 mA
Data EEPROM Memory
D120 ED Byte Endurance 100K 1M — E/W -40°C to +85°C
D121 VDRW VDD for Read/Write VMIN — 5.5 V Using EECON to read/write
VMIN = Minimum operating
voltage
D122 TDEW Erase/Write Cycle Time — 4 — ms
D123 TRETD Characteristic Retention 40 — — Year Provided no other
specifications are violated
D124 TREF Number of Total Erase/Write
Cycles before Refresh(3)
1M 10M — E/W -40°C to +85°C
Program Flash Memory
D130 EP Cell Endurance 10K 100K — E/W -40°C to +85°C
D131 VPR VDD for Read VMIN — 5.5 V VMIN = Minimum operating
voltage
D132 VIE VDD for Block Erase 4.5 — 5.5 V Using ICSP port
D132A VIW VDD for Externally Timed Erase
or Write
4.5 — 5.5 V Using ICSP port
D132B VPEW VDD for Self-Timed Write VMIN — 5.5 V VMIN = Minimum operating
voltage
D133 TIE ICSP™ Block Erase Cycle Time — 4 — ms VDD > 4.5V
D133A TIW ICSP Erase or Write Cycle Time
(externally timed)
1 — — ms VDD > 4.5V
D133A TIW Self-Timed Write Cycle Time — 2 — ms
D134 TRETD Characteristic Retention 40 — — Year Provided no other
specifications are violated
† Data in “Typ” column is at 5.0V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
Note 1: These specifications are for programming the on-chip program memory through the use of table write
instructions.
2: The pin may be kept in this range at times other than programming, but it is not recommended.
3: Refer to Section 7.8 “Using the Data EEPROM” for a more detailed discussion on data EEPROM
endurance.© 2007 Microchip Technology Inc. DS39605F-page 253
PIC18F1220/1320
FIGURE 22-4: LOW-VOLTAGE DETECT CHARACTERISTICS
VLVD
LVDIF
VDD
(LVDIF set by hardware)
(LVDIF can be
cleared in software)
TABLE 22-2: LOW-VOLTAGE DETECT CHARACTERISTICS
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ† Max Units Conditions
D420D LVD Voltage on VDD Transition High-to-Low Industrial Low Voltage (-10°C to +85°C)
PIC18LF1220/1320 LVDL<3:0> = 0000 N/A N/A N/A V Reserved
LVDL<3:0> = 0001 N/A N/A N/A V Reserved
LVDL<3:0> = 0010 2.08 2.26 2.44 V
LVDL<3:0> = 0011 2.26 2.45 2.65 V
LVDL<3:0> = 0100 2.35 2.55 2.76 V
LVDL<3:0> = 0101 2.55 2.77 2.99 V
LVDL<3:0> = 0110 2.64 2.87 3.10 V
LVDL<3:0> = 0111 2.82 3.07 3.31 V
LVDL<3:0> = 1000 3.09 3.36 3.63 V
LVDL<3:0> = 1001 3.29 3.57 3.86 V
LVDL<3:0> = 1010 3.38 3.67 3.96 V
LVDL<3:0> = 1011 3.56 3.87 4.18 V
LVDL<3:0> = 1100 3.75 4.07 4.40 V
LVDL<3:0> = 1101 3.93 4.28 4.62 V
LVDL<3:0> = 1110 4.23 4.60 4.96 V
Legend: Shading of rows is to assist in readability of the table.
† Production tested at TAMB = 25°C. Specifications over temperature limits ensured by characterization.PIC18F1220/1320
DS39605F-page 254 © 2007 Microchip Technology Inc.
D420F LVD Voltage on VDD Transition High-to-Low Industrial Low Voltage (-40°C to -10°C)
PIC18LF1220/1320 LVDL<3:0> = 0000 N/A N/A N/A V Reserved
LVDL<3:0> = 0001 N/A N/A N/A V Reserved
LVDL<3:0> = 0010 1.99 2.26 2.53 V
LVDL<3:0> = 0011 2.16 2.45 2.75 V
LVDL<3:0> = 0100 2.25 2.55 2.86 V
LVDL<3:0> = 0101 2.43 2.77 3.10 V
LVDL<3:0> = 0110 2.53 2.87 3.21 V
LVDL<3:0> = 0111 2.70 3.07 3.43 V
LVDL<3:0> = 1000 2.96 3.36 3.77 V
LVDL<3:0> = 1001 3.14 3.57 4.00 V
LVDL<3:0> = 1010 3.23 3.67 4.11 V
LVDL<3:0> = 1011 3.41 3.87 4.34 V
LVDL<3:0> = 1100 3.58 4.07 4.56 V
LVDL<3:0> = 1101 3.76 4.28 4.79 V
LVDL<3:0> = 1110 4.04 4.60 5.15 V
LVD Voltage on VDD Transition High-to-Low Industrial (-10°C to +85°C)
D420G PIC18F1220/1320 LVDL<3:0> = 1101 3.93 4.28 4.62 V
LVDL<3:0> = 1110 4.23 4.60 4.96 V
LVD Voltage on VDD Transition High-to-Low Industrial (-40°C to -10°C)
D420H PIC18F1220/1320 LVDL<3:0> = 1101 3.76 4.28 4.79 V
LVDL<3:0> = 1110 4.04 4.60 5.15 V
LVD Voltage on VDD Transition High-to-Low Extended (-10°C to +85°C)
D420J PIC18F1220/1320 LVDL<3:0> = 1101 3.94 4.28 4.62 V
LVDL<3:0> = 1110 4.23 4.60 4.96 V
LVD Voltage on VDD Transition High-to-Low Extended (-40°C to -10°C, +85°C to +125°C)
D420K PIC18F1220/1320 LVDL<3:0> = 1101 3.77 4.28 4.79 V
LVDL<3:0> = 1110 4.05 4.60 5.15 V
TABLE 22-2: LOW-VOLTAGE DETECT CHARACTERISTICS (CONTINUED)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ† Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
† Production tested at TAMB = 25°C. Specifications over temperature limits ensured by characterization.© 2007 Microchip Technology Inc. DS39605F-page 255
PIC18F1220/1320
22.4 AC (Timing) Characteristics
22.4.1 TIMING PARAMETER SYMBOLOGY
The timing parameter symbols have been created
following one of the following formats:
1. TppS2ppS 3. TCC:ST (I2C specifications only)
2. TppS 4. Ts (I2C specifications only)
T
F Frequency T Time
Lowercase letters (pp) and their meanings:
pp
cc CCP1 osc OSC1
ck CLKO rd RD
cs CS rw RD or WR
di SDI sc SCK
do SDO ss SS
dt Data in t0 T0CKI
io I/O port t1 T13CKI
mc MCLR wr WR
Uppercase letters and their meanings:
S
F Fall P Period
H High R Rise
I Invalid (High-Impedance) V Valid
L Low Z High-Impedance
I
2C only
AA output access High High
BUF Bus free Low Low
TCC:ST (I2C specifications only)
CC
HD Hold SU Setup
ST
DAT DATA input hold STO Stop condition
STA Start conditionPIC18F1220/1320
DS39605F-page 256 © 2007 Microchip Technology Inc.
22.4.2 TIMING CONDITIONS
The temperature and voltages specified in Table 22-3
apply to all timing specifications unless otherwise
noted. Figure 22-5 specifies the load conditions for the
timing specifications.
TABLE 22-3: TEMPERATURE AND VOLTAGE SPECIFICATIONS – AC
FIGURE 22-5: LOAD CONDITIONS FOR DEVICE TIMING SPECIFICATIONS
AC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Section 22.1 and
Section 22.3.
LF parts operate for industrial temperatures only.
VDD/2
CL
RL
pin
Pin
VSS
VSS
CL
RL = 464Ω
CL = 50 pF for all pins except OSC2/CLKO
Load Condition 1 Load Condition 2© 2007 Microchip Technology Inc. DS39605F-page 257
PIC18F1220/1320
22.4.3 TIMING DIAGRAMS AND SPECIFICATIONS
FIGURE 22-6: EXTERNAL CLOCK TIMING (ALL MODES EXCEPT PLL)
TABLE 22-4: EXTERNAL CLOCK TIMING REQUIREMENTS
OSC1
CLKO
Q4 Q1 Q2 Q3 Q4 Q1
1
2
3 3 4 4
Param.
No. Symbol Characteristic Min Max Units Conditions
1A FOSC External CLKI Frequency(1) DC 40 MHz EC, ECIO (LF and Industrial)
DC 25 MHz EC, ECIO (Extended)
Oscillator Frequency(1) DC 4 MHz RC oscillator
DC 1 MHz XT oscillator
DC 25 MHz HS oscillator
1 10 MHz HS + PLL oscillator
DC 33 kHz LP Oscillator mode
1 TOSC External CLKI Period(1) 25 — ns EC, ECIO (LF and Industrial)
40 — ns EC, ECIO (Extended)
Oscillator Period(1) 250 — ns RC oscillator
1000 — ns XT oscillator
25
100
—
1000
ns
ns
HS oscillator
HS + PLL oscillator
30 — μs LP oscillator
2 TCY Instruction Cycle Time(1) 100 — ns TCY = 4/FOSC
3 TosL,
TosH
External Clock in (OSC1)
High or Low Time
30 — ns XT oscillator
2.5 — μs LP oscillator
10 — ns HS oscillator
4 TosR,
TosF
External Clock in (OSC1)
Rise or Fall Time
— 20 ns XT oscillator
— 50 ns LP oscillator
— 7.5 ns HS oscillator
Note 1: Instruction cycle period (TCY) equals four times the input oscillator time base period for all configurations
except PLL. All specified values are based on characterization data for that particular oscillator type under
standard operating conditions, with the device executing code. Exceeding these specified limits may result
in an unstable oscillator operation and/or higher than expected current consumption. All devices are tested
to operate at “min.” values with an external clock applied to the OSC1/CLKI pin. When an external clock
input is used, the “max.” cycle time limit is “DC” (no clock) for all devices.PIC18F1220/1320
DS39605F-page 258 © 2007 Microchip Technology Inc.
TABLE 22-5: PLL CLOCK TIMING SPECIFICATIONS, HS/HSPLL MODE (VDD = 4.2V TO 5.5V)
Param
No. Sym Characteristic Min Typ† Max Units Conditions
F10 FOSC Oscillator Frequency Range 4 — 10 MHz HS and HSPLL mode only
F11 FSYS On-Chip VCO System Frequency 16 — 40 MHz HSPLL mode only
F12 TPLL PLL Start-up Time (Lock Time) — — 2 ms HSPLL mode only
F13 ΔCLK CLKO Stability (Jitter) -2 — +2 % HSPLL mode only
† Data in “Typ” column is at 5V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
TABLE 22-6: INTERNAL RC ACCURACY: PIC18F1220/1320 (INDUSTRIAL)
PIC18LF1220/1320 (INDUSTRIAL)
PIC18LF1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F1220/1320
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Min Typ Max Units Conditions
INTOSC Accuracy @ Freq = 8 MHz, 4 MHz, 2 MHz, 1 MHz, 500 kHz, 250 kHz, 125 kHz(1)
PIC18LF1220/1320 -2 +/-1 2 % +25°C VDD = 2.7-3.3V
-5 — 5 % -10°C to +85°C VDD = 2.7-3.3V
-10 — 10 % -40°C to +85°C VDD = 2.7-3.3V
PIC18F1220/1320PIC18F
1220/1320
-2 +/-1 2 % +25°C VDD = 4.5-5.5V
-5 — 5 % -10°C to +85°C VDD = 4.5-5.5V
-10 — 10 % -40°C to +85°C VDD = 4.5-5.5V
INTRC Accuracy @ Freq = 31 kHz(2)
PIC18LF1220/1320 26.562 — 35.938 kHz -40°C to +85°C VDD = 2.7-3.3V
PIC18F1220/1320PIC18F
1220/1320
26.562 — 35.938 kHz -40°C to +85°C VDD = 4.5-5.5V
Legend: Shading of rows is to assist in readability of the table.
Note 1: Frequency calibrated at 25°C. OSCTUNE register can be used to compensate for temperature and VDD drift.
2: INTRC frequency after calibration.
3: Change of INTRC frequency as VDD changes.© 2007 Microchip Technology Inc. DS39605F-page 259
PIC18F1220/1320
FIGURE 22-7: CLKO AND I/O TIMING
TABLE 22-7: CLKO AND I/O TIMING REQUIREMENTS
Note: Refer to Figure 22-5 for load conditions.
OSC1
CLKO
I/O pin
(Input)
I/O pin
(Output)
Q4 Q1 Q2 Q3
10
13
14
17
20, 21
19 18
15
11
12
16
Old Value New Value
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
10 TosH2ckL OSC1↑ to CLKO↓ — 75 200 ns (Note 1)
11 TosH2ckH OSC1↑ to CLKO↑ — 75 200 ns (Note 1)
12 TckR CLKO Rise Time — 35 100 ns (Note 1)
13 TckF CLKO Fall Time — 35 100 ns (Note 1)
14 TckL2ioV CLKO↓ to Port Out Valid — — 0.5 TCY + 20 ns (Note 1)
15 TioV2ckH Port In Valid before CLKO↑ 0.25 TCY + 25 — — ns (Note 1)
16 TckH2ioI Port In Hold after CLKO↑ 0 — — ns (Note 1)
17 TosH2ioV OSC1↑ (Q1 cycle) to Port Out Valid — 50 150 ns
18 TosH2ioI OSC1↑ (Q2 cycle) to Port
Input Invalid (I/O in hold time)
PIC18F1X20 100 — — ns
18A PIC18LF1X20 200 — — ns
19 TioV2osH Port Input Valid to OSC1↑
(I/O in setup time)
0 — — ns
20 TioR Port Output Rise Time PIC18F1X20 — 10 25 ns
20A PIC18LF1X20 — — 60 ns
21 TioF Port Output Fall Time PIC18F1X20 — 10 25 ns
21A PIC18LF1X20 — — 60 ns
Note 1: Measurements are taken in RC mode, where CLKO output is 4 x TOSC.PIC18F1220/1320
DS39605F-page 260 © 2007 Microchip Technology Inc.
FIGURE 22-8: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER AND
POWER-UP TIMER TIMING
FIGURE 22-9: BROWN-OUT RESET TIMING
VDD
MCLR
Internal
POR
PWRT
Time-out
OSC
Time-out
Internal
Reset
Watchdog
Timer
Reset
33
32
30
31
34
I/O pins
34
Note: Refer to Figure 22-5 for load conditions.
VDD
BVDD
35
VBGAP = 1.2V
VIRVST
Enable Internal
Internal Reference 36
Reference Voltage
Voltage Stable© 2007 Microchip Technology Inc. DS39605F-page 261
PIC18F1220/1320
TABLE 22-8: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER, POWER-UP TIMER
AND BROWN-OUT RESET REQUIREMENTS
FIGURE 22-10: TIMER0 AND TIMER1 EXTERNAL CLOCK TIMINGS
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
30 TmcL MCLR Pulse Width (low) 2 — — μs
31 TWDT Watchdog Timer Time-out Period
(No postscaler)
3.48 4.00 4.71 ms
32 TOST Oscillation Start-up Timer Period 1024 TOSC — 1024 TOSC — TOSC = OSC1 period
33 TPWRT Power-up Timer Period — 65.5 132 ms
34 TIOZ I/O High-Impedance from MCLR
Low or Watchdog Timer Reset
—2— μs
35 TBOR Brown-out Reset Pulse Width 200 — — μs VDD ≤ BVDD (see D005)
36 TIVRST Time for Internal Reference
Voltage to become stable
— 20 50 μs
37 TLVD Low-Voltage Detect Pulse Width 200 — — μs VDD ≤ VLVD
Note: Refer to Figure 22-5 for load conditions.
46
47
45
48
41
42
40
T0CKI
T1OSO/T13CKI
TMR0 or
TMR1PIC18F1220/1320
DS39605F-page 262 © 2007 Microchip Technology Inc.
TABLE 22-9: TIMER0 AND TIMER1 EXTERNAL CLOCK REQUIREMENTS
FIGURE 22-11: CAPTURE/COMPARE/PWM TIMINGS (ALL CCP MODULES)
Param
No. Symbol Characteristic Min Max Units Conditions
40 Tt0H T0CKI High Pulse Width No prescaler 0.5 TCY + 20 — ns
With prescaler 10 — ns
41 Tt0L T0CKI Low Pulse Width No prescaler 0.5 TCY + 20 — ns
With prescaler 10 — ns
42 Tt0P T0CKI Period No prescaler TCY + 10 — ns
With prescaler Greater of:
20 ns or TCY + 40
N
— ns N = prescale
value
(1, 2, 4,..., 256)
45 Tt1H T13CKI High Time Synchronous, no prescaler 0.5 TCY + 20 — ns
Synchronous,
with prescaler
PIC18F1X20 10 — ns
PIC18LF1X20 25 — ns
Asynchronous PIC18F1X20 30 — ns
PIC18LF1X20 50 — ns
46 Tt1L T13CKI Low Time Synchronous, no prescaler 0.5 TCY + 5 — ns
Synchronous,
with prescaler
PIC18F1X20 10 — ns
PIC18LF1X20 25 — ns
Asynchronous PIC18F1X20 30 — ns
PIC18LF1X20 50 — ns
47 Tt1P T13CKI Input
Period
Synchronous Greater of:
20 ns or TCY + 40
N
— ns N = prescale
value
(1, 2, 4, 8)
Asynchronous 60 — ns
Ft1 T13CKI Oscillator Input Frequency Range DC 50 kHz
48 Tcke2tmrI Delay from External T13CKI Clock Edge to
Timer Increment
2 TOSC 7 TOSC —
Note: Refer to Figure 22-5 for load conditions.
CCPx
(Capture Mode)
50 51
52
CCPx
53 54
(Compare or PWM Mode)© 2007 Microchip Technology Inc. DS39605F-page 263
PIC18F1220/1320
TABLE 22-10: CAPTURE/COMPARE/PWM REQUIREMENTS (ALL CCP MODULES)
FIGURE 22-12: EUSART SYNCHRONOUS TRANSMISSION (MASTER/SLAVE) TIMING
TABLE 22-11: EUSART SYNCHRONOUS TRANSMISSION REQUIREMENTS
Param.
No. Symbol Characteristic Min Max Units Conditions
50 TccL CCPx Input Low
Time
No prescaler 0.5 TCY + 20 — ns
With prescaler PIC18F1X20 10 — ns
PIC18LF1X20 20 — ns
51 TccH CCPx Input High
Time
No prescaler 0.5 TCY + 20 — ns
With prescaler PIC18F1X20 10 — ns
PIC18LF1X20 20 — ns
52 TccP CCPx Input Period 3 TCY + 40
N
— ns N = prescale
value (1, 4 or 16)
53 TccR CCPx Output Fall Time PIC18F1X20 — 25 ns
PIC18LF1X20 — 45 ns
54 TccF CCPx Output Fall Time PIC18F1X20 — 25 ns
PIC18LF1X20 — 45 ns
121 121
120
122
RB1/AN5/TX/
RB4/AN6/RX/
DT/KBI0 pin
CK/INT1 pin
Note: Refer to Figure 22-5 for load conditions.
Param.
No. Symbol Characteristic Min Max Units Conditions
120 TckH2dtV SYNC XMIT (MASTER & SLAVE)
Clock High to Data Out Valid PIC18F1X20 — 40 ns
PIC18LF1X20 — 100 ns
121 Tckrf Clock Out Rise Time and Fall Time
(Master mode)
PIC18F1X20 — 20 ns
PIC18LF1X20 — 50 ns
122 Tdtrf Data Out Rise Time and Fall Time PIC18F1X20 — 20 ns
PIC18LF1X20 — 50 nsPIC18F1220/1320
DS39605F-page 264 © 2007 Microchip Technology Inc.
FIGURE 22-13: EUSART SYNCHRONOUS RECEIVE (MASTER/SLAVE) TIMING
TABLE 22-12: EUSART SYNCHRONOUS RECEIVE REQUIREMENTS
TABLE 22-13: A/D CONVERTER CHARACTERISTICS: PIC18F1220/1320 (INDUSTRIAL)
PIC18LF1220/1320 (INDUSTRIAL)
Param.
No. Symbol Characteristic Min Max Units Conditions
125 TdtV2ckl SYNC RCV (MASTER & SLAVE)
Data Hold before CK↓ (DT hold time) 10 — ns
126 TckL2dtl Data Hold after CK↓ (DT hold time) 15 — ns
Param
No. Symbol Characteristic Min Typ Max Units Conditions
A01 NR Resolution — — 10 bit ΔVREF ≥ 3.0V
A03 EIL Integral Linearity Error — — <±1 LSb ΔVREF ≥ 3.0V
A04 EDL Differential Linearity Error — — <±1 LSb ΔVREF ≥ 3.0V
A06 EOFF Offset Error — — <±1 LSb ΔVREF ≥ 3.0V
A07 EGN Gain Error — — <±1 LSb ΔVREF ≥ 3.0V
A10 — Monotonicity guaranteed(2) —
A20 ΔVREF Reference Voltage Range
(VREFH – VREFL)
3 — AVDD – AVSS V For 10-bit resolution
A21 VREFH Reference Voltage High AVSS + 3.0V — AVDD + 0.3V V For 10-bit resolution
A22 VREFL Reference Voltage Low AVSS – 0.3V — AVDD – 3.0V V For 10-bit resolution
A25 VAIN Analog Input Voltage VREFL — VREFH V
A28 AVDD Analog Supply Voltage VDD – 0.3 — VDD + 0.3 V
A29 AVSS Analog Supply Voltage VSS – 0.3 — VSS + 0.3 V
A30 ZAIN Recommended Impedance of
Analog Voltage Source
— — 2.5 kΩ
A40 IAD A/D Conversion
Current (VDD)
PIC18F1X20 — 180 — μA Average current
consumption when
A/D is on (Note 1)
PIC18LF1X20 — 90 — μA
A50 IREF VREF Input Current (Note 3) —
—
—
—
±5
±150
μA
μA
During VAIN acquisition.
During A/D conversion
cycle.
Note 1: When A/D is off, it will not consume any current other than minor leakage current. The power-down current
specification includes any such leakage from the A/D module.
2: The A/D conversion result never decreases with an increase in the input voltage and has no missing codes.
3: VREFH current is from RA3/AN3/VREF+ pin or AVDD, whichever is selected as the VREFH source.
VREFL current is from RA2/AN2/VREF- pin or AVSS, whichever is selected as the VREFL source.
125
126
Note: Refer to Figure 22-5 for load conditions.
RB1/AN5/TX/
RB4/AN6/RX/
DT/KBI0 pin
CK/INT1 pin© 2007 Microchip Technology Inc. DS39605F-page 265
PIC18F1220/1320
FIGURE 22-14: A/D CONVERSION TIMING
TABLE 22-14: A/D CONVERSION REQUIREMENTS
131
130
132
BSF ADCON0, GO
Q4
A/D CLK(1)
A/D DATA
ADRES
ADIF
GO
SAMPLE
OLD_DATA
Sampling Stopped
DONE
NEW_DATA
(Note 2)
9 87 2 1 0
Note 1: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts.
This allows the SLEEP instruction to be executed.
2: This is a minimal RC delay (typically 100 ns), which also disconnects the holding capacitor from the analog input.
. . . . . .
TCY
Param
No. Symbol Characteristic Min Max Units Conditions
130 TAD A/D Clock Period PIC18F1X20 1.6 20(5) μs TOSC based, VREF ≥ 3.0V
PIC18LF1X20 3.0 20(5) μs TOSC based, VREF full range
PIC18F1X20 2.0 6.0 μs A/D RC mode
PIC18LF1X20 3.0 9.0 μs A/D RC mode
131 TCNV Conversion Time
(not including acquisition time) (Note 1)
11 12 TAD
132 TACQ Acquisition Time (Note 3) 15
10
—
—
μs
μs
-40°C ≤ Temp ≤ +125°C
0°C ≤ Temp ≤ +125°C
135 TSWC Switching Time from Convert → Sample — (Note 4)
136 TAMP Amplifier Settling Time (Note 2) 1 — μs This may be used if the
“new” input voltage has not
changed by more than 1 LSb
(i.e., 5 mV @ 5.12V) from the
last sampled voltage (as
stated on CHOLD).
Note 1: ADRES register may be read on the following TCY cycle.
2: See Section 17.0 “10-Bit Analog-to-Digital Converter (A/D) Module” for minimum conditions when input
voltage has changed more than 1 LSb.
3: The time for the holding capacitor to acquire the “New” input voltage, when the voltage changes full scale after
the conversion (AVDD to AVSS, or AVSS to AVDD). The source impedance (RS) on the input channels is 50Ω.
4: On the next Q4 cycle of the device clock.
5: The time of the A/D clock period is dependent on the device frequency and the TAD clock divider. PIC18F1220/1320
DS39605F-page 266 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 267
PIC18F1220/1320
23.0 DC AND AC CHARACTERISTICS GRAPHS AND TABLES
“Typical” represents the mean of the distribution at 25°C. “Maximum” or “minimum” represents (mean + 3σ) or (mean – 3σ)
respectively, where σ is a standard deviation, over the whole temperature range.
FIGURE 23-1: TYPICAL IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, +25°C
FIGURE 23-2: MAXIMUM IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, -40°C TO +85°C
Note: The graphs and tables provided following this note are a statistical summary based on a limited number of
samples and are provided for informational purposes only. The performance characteristics listed herein
are not tested or guaranteed. In some graphs or tables, the data presented may be outside the specified
operating range (e.g., outside specified power supply range) and therefore, outside the warranted range.
0.0
0.1
0.2
0.3
0.4
0.5
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 268 © 2007 Microchip Technology Inc.
FIGURE 23-3: MAXIMUM IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, -40°C TO +125°C
FIGURE 23-4: TYPICAL IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, +25°C
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 269
PIC18F1220/1320
FIGURE 23-5: MAXIMUM IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, -40°C TO +125°C
FIGURE 23-6: TYPICAL IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, +25°C
0.0
0.5
1.0
1.5
2.0
2.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
2
4
6
8
10
12
14
16
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 270 © 2007 Microchip Technology Inc.
FIGURE 23-7: MAXIMUM IDD vs. FOSC OVER VDD PRI_RUN, EC MODE, -40°C TO +125°C
FIGURE 23-8: TYPICAL IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, +25°C
0
2
4
6
8
10
12
14
16
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.000
0.005
0.010
0.015
0.020
0.025
0.030
0.035
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 271
PIC18F1220/1320
FIGURE 23-9: MAXIMUM IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, -40°C TO +85°C
FIGURE 23-10: MAXIMUM IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, -40°C TO +125°C
0.000
0.005
0.010
0.015
0.020
0.025
0.030
0.035
0.040
0.045
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.000
0.010
0.020
0.030
0.040
0.050
0.060
0.070
0.080
0.090
0.100
0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20
FOSC (MHz)
IDD (mA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 272 © 2007 Microchip Technology Inc.
FIGURE 23-11: TYPICAL IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, +25°C
FIGURE 23-12: MAXIMUM IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, -40°C TO +125°C
Typical I vs F over V PRI_IDLE, EC mode, +25°C
0
100
200
300
400
500
600
1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (μA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
100
200
300
400
500
600
1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (μA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 273
PIC18F1220/1320
FIGURE 23-13: TYPICAL IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, +25°C
FIGURE 23-14: MAXIMUM IDD vs. FOSC OVER VDD PRI_IDLE, EC MODE, -40°C TO +125°C
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
6.0
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
6.0
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
5.0V
5.5V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 274 © 2007 Microchip Technology Inc.
FIGURE 23-15: TYPICAL IPD vs. VDD (+25°C), 125 kHz TO 8 MHz RC_RUN MODE,
ALL PERIPHERALS DISABLED
FIGURE 23-16: MAXIMUM IPD vs. VDD (-40°C TO +125°C), 125 kHz TO 8 MHz RC_RUN MODE,
ALL PERIPHERALS DISABLED
0
500
1000
1500
2000
2500
3000
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
8 MHz
125 kHz
4 MHz
2 MHz
1 MHz
250 kHz and 500 kHz curves are
bounded by 125 kHz and 1 MHz
curves.
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
500
1000
1500
2000
2500
3000
3500
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
8 MHz
125 kHz
4 MHz
2 MHz
1 MHz
250 kHz and 500 kHz curves are
bounded by 125 kHz and 1 MHz
curves.
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 275
PIC18F1220/1320
FIGURE 23-17: TYPICAL AND MAXIMUM IPD vs. VDD (-40°C TO +125°C), 31.25 kHz RC_RUN MODE,
ALL PERIPHERALS DISABLED
FIGURE 23-18: TYPICAL IPD vs. VDD (+25°C), 125 kHz TO 8 MHz RC_IDLE MODE,
ALL PERIPHERALS DISABLED
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (+85°C)
Max (+125°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
100
150
200
250
300
350
400
450
500
550
600
650
700
750
800
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
8 MHz
125 kHz
4 MHz
2 MHz
1 MHz
250 kHz and 500 kHz curves are
bounded by 125 kHz and 1 MHz
curves.
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 276 © 2007 Microchip Technology Inc.
FIGURE 23-19: MAXIMUM IPD vs. VDD (-40°C TO +125°C), 125 kHz TO 8 MHz RC_IDLE MODE,
ALL PERIPHERALS DISABLED
FIGURE 23-20: TYPICAL AND MAXIMUM IPD vs. VDD (-40°C TO +125°C), 31.25 kHz RC_IDLE MODE,
ALL PERIPHERALS DISABLED
100
150
200
250
300
350
400
450
500
550
600
650
700
750
800
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
8 MHz
125 kHz
4 MHz
2 MHz
1 MHz
250 kHz and 500 kHz curves are
bounded by 125 kHz and 1 MHz
curves.
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (+85°C)
Max (+125°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 277
PIC18F1220/1320
FIGURE 23-21: IPD SEC_RUN MODE, -10°C TO +70°C, 32.768 kHz XTAL, 2 x 22 pF,
ALL PERIPHERALS DISABLED
FIGURE 23-22: IPD SEC_IDLE MODE, -10°C TO +70°C, 32.768 kHz, 2 x 22 pF,
ALL PERIPHERALS DISABLED
0
10
20
30
40
50
60
70
80
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (+70°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
2
4
6
8
10
12
14
16
18
20
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (+70°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 278 © 2007 Microchip Technology Inc.
FIGURE 23-23: TOTAL IPD, -40°C TO +125°C SLEEP MODE, ALL PERIPHERALS DISABLED
FIGURE 23-24: VOH vs. IOH OVER TEMPERATURE (-40°C TO +125°C), VDD = 3.0V
0.001
0.01
0.1
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Max (+85°C)
Max (+125°C)
Typ (+25°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
0 5 10 15 20 25
IOH (-mA)
VOH (V)
Max (+125°C)
Min (+125°C)
Typ (+25°C)© 2007 Microchip Technology Inc. DS39605F-page 279
PIC18F1220/1320
FIGURE 23-25: VOH vs. IOH OVER TEMPERATURE (-40°C TO +125°C), VDD = 5.0V
FIGURE 23-26: VOL vs. IOL OVER TEMPERATURE (-40°C TO +125°C), VDD = 3.0V
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
0 5 10 15 20 25
IOH (-mA)
VOH (V)
Max (+125°C)
Min (+125°C)
Typ (+25°C)
V vs I over Temp (-40°C to +125°C) V = 3.0V
0.0
0.5
1.0
1.5
2.0
2.5
3.0
0 5 10 15 20 25
IOL (-mA)
VOL (V)
Max (+125°C)
Max (+85°C)
Typ (+25°C)
Min (+125°C)PIC18F1220/1320
DS39605F-page 280 © 2007 Microchip Technology Inc.
FIGURE 23-27: VOL vs. IOL OVER TEMPERATURE (-40°C TO +125°C), VDD = 5.0V
FIGURE 23-28: ΔIPD TIMER1 OSCILLATOR, -10°C TO +70°C SLEEP MODE,
TMR1 COUNTER DISABLED
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
0 5 10 15 20 25
IOL (-mA)
VOL (V)
Max (+125°C)
Max (+85°C)
Typ (+25°C)
Min (+125°C)
IPD Timer1 Oscillator, -10°C to +70°C SLEEP mode, TMR1 counter disabled
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (-10°C to +70°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 281
PIC18F1220/1320
FIGURE 23-29: ΔIPD FSCM vs. VDD OVER TEMPERATURE PRI_IDLE MODE,
EC OSCILLATOR AT 32 kHz, -40°C TO +125°C
FIGURE 23-30: ΔIPD WDT, -40°C TO +125°C SLEEP MODE, ALL PERIPHERALS DISABLED
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
ΔIPD (μA)
Typ (+25°C)
Max (-40°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
2
4
6
8
10
12
14
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
ΔIPD (μA)
Typ (+25°C)
Max (+85°C)
Max (+125°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)PIC18F1220/1320
DS39605F-page 282 © 2007 Microchip Technology Inc.
FIGURE 23-31: ΔIPD LVD vs. VDD SLEEP MODE, LVDL3:LVDL0 = 0001 (2V)
FIGURE 23-32: ΔIPD BOR vs. VDD, -40°C TO +125°C SLEEP MODE,
BORV1:BORV0 = 11 (2V)
0
5
10
15
20
25
30
35
40
45
50
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Typ (+25°C)
Max (+85°C)
Max (+125°C)
Low-Voltage Detection Range
Normal Operating Range
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0
5
10
15
20
25
30
35
40
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Max (+125°C)
Typ (+25°C)
Device may be in Reset
Device is Operating
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)© 2007 Microchip Technology Inc. DS39605F-page 283
PIC18F1220/1320
FIGURE 23-33: ΔIPD A/D, -40°C TO +125°C SLEEP MODE, A/D ENABLED (NOT CONVERTING)
FIGURE 23-34: AVERAGE FOSC vs. VDD FOR VARIOUS R’s EXTERNAL RC MODE,
C = 20 pF, TEMPERATURE = +25°C
0.001
0.01
0.1
1
10
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Max (+125°C)
Max (+85°C)
Typ (+25°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to +125°C)
Minimum: mean – 3σ (-40°C to +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (MHz)
5.1K
10K
33K
100K
Operation above 4 MHz is not recomendedPIC18F1220/1320
DS39605F-page 284 © 2007 Microchip Technology Inc.
FIGURE 23-35: AVERAGE FOSC vs. VDD FOR VARIOUS R’s EXTERNAL RC MODE,
C = 100 pF, TEMPERATURE = +25°C
FIGURE 23-36: AVERAGE FOSC vs. VDD FOR VARIOUS R’s EXTERNAL RC MODE,
C = 300 pF, TEMPERATURE = +25°C
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (MHz)
5.1K
10K
33K
100K
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (MHz)
5.1K
10K
33K
100K© 2007 Microchip Technology Inc. DS39605F-page 285
PIC18F1220/1320
24.0 PACKAGING INFORMATION
24.1 Package Marking Information
18-Lead PDIP
XXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F1320-I/P
0710017
18-Lead SOIC
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
YYWWNNN
Example
PIC18F1220-
E/SO
0710017
20-Lead SSOP
XXXXXXXXXXX
XXXXXXXXXXX
YYWWNNN
Example
PIC18F1220-
E/SS
0710017
28-Lead QFN
XXXXXXXX
XXXXXXXX
YYWWNNN
Example
18F1320
-I/ML
0710017
Legend: XX...X Customer-specific information
Y Year code (last digit of calendar year)
YY Year code (last 2 digits of calendar year)
WW Week code (week of January 1 is week ‘01’)
NNN Alphanumeric traceability code
Pb-free JEDEC designator for Matte Tin (Sn)
* This package is Pb-free. The Pb-free JEDEC designator ( )
can be found on the outer packaging for this package.
Note: In the event the full Microchip part number cannot be marked on one line, it will
be carried over to the next line, thus limiting the number of available
characters for customer-specific information.
e3
e3
e3
e3
e3
e3PIC18F1220/1320
DS39605F-page 286 © 2007 Microchip Technology Inc.
24.2 Package Details
The following sections give the technical details of the packages.
18-Lead Plastic Dual In-Line (P) – 300 mil Body [PDIP]
Notes:
1. Pin 1 visual index feature may vary, but must be located within the hatched area.
2. § Significant Characteristic.
3. Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010" per side.
4. Dimensioning and tolerancing per ASME Y14.5M.
BSC: Basic Dimension. Theoretically exact value shown without tolerances.
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Units INCHES
Dimension Limits MIN NOM MAX
Number of Pins N 18
Pitch e .100 BSC
Top to Seating Plane A – – .210
Molded Package Thickness A2 .115 .130 .195
Base to Seating Plane A1 .015 – –
Shoulder to Shoulder Width E .300 .310 .325
Molded Package Width E1 .240 .250 .280
Overall Length D .880 .900 .920
Tip to Seating Plane L .115 .130 .150
Lead Thickness c .008 .010 .014
Upper Lead Width b1 .045 .060 .070
Lower Lead Width b .014 .018 .022
Overall Row Spacing § eB – – .430
NOTE 1
N
E1
D
1 2 3
A
A1
A2
L
E
eB
c
e
b1
b
Microchip Technology Drawing C04-007B© 2007 Microchip Technology Inc. DS39605F-page 287
PIC18F1220/1320
18-Lead Plastic Small Outline (SO) – Wide, 7.50 mm Body [SOIC]
Notes:
1. Pin 1 visual index feature may vary, but must be located within the hatched area.
2. § Significant Characteristic.
3. Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed 0.15 mm per side.
4. Dimensioning and tolerancing per ASME Y14.5M.
BSC: Basic Dimension. Theoretically exact value shown without tolerances.
REF: Reference Dimension, usually without tolerance, for information purposes only.
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Units MILLIMETERS
Dimension Limits MIN NOM MAX
Number of Pins N 18
Pitch e 1.27 BSC
Overall Height A – – 2.65
Molded Package Thickness A2 2.05 – –
Standoff § A1 0.10 – 0.30
Overall Width E 10.30 BSC
Molded Package Width E1 7.50 BSC
Overall Length D 11.55 BSC
Chamfer (optional) h 0.25 – 0.75
Foot Length L 0.40 – 1.27
Footprint L1 1.40 REF
Foot Angle φ 0° – 8°
Lead Thickness c 0.20 – 0.33
Lead Width b 0.31 – 0.51
Mold Draft Angle Top α 5° – 15°
Mold Draft Angle Bottom β 5° – 15°
NOTE 1
D
N
E
E1
e
b
1 2 3
A
A1
A2
L
L1
h
h
c
β
φ
α
Microchip Technology Drawing C04-051BPIC18F1220/1320
DS39605F-page 288 © 2007 Microchip Technology Inc.
20-Lead Plastic Shrink Small Outline (SS) – 5.30 mm Body [SSOP]
Notes:
1. Pin 1 visual index feature may vary, but must be located within the hatched area.
2. Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed 0.20 mm per side.
3. Dimensioning and tolerancing per ASME Y14.5M.
BSC: Basic Dimension. Theoretically exact value shown without tolerances.
REF: Reference Dimension, usually without tolerance, for information purposes only.
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Units MILLIMETERS
Dimension Limits MIN NOM MAX
Number of Pins N 20
Pitch e 0.65 BSC
Overall Height A – – 2.00
Molded Package Thickness A2 1.65 1.75 1.85
Standoff A1 0.05 – –
Overall Width E 7.40 7.80 8.20
Molded Package Width E1 5.00 5.30 5.60
Overall Length D 6.90 7.20 7.50
Foot Length L 0.55 0.75 0.95
Footprint L1 1.25 REF
Lead Thickness c 0.09 – 0.25
Foot Angle φ 0° 4° 8°
Lead Width b 0.22 – 0.38
φ
L1 L
A2 c
e
b
A1
A
1 2
NOTE 1
E1
E
D
N
Microchip Technology Drawing C04-072B© 2007 Microchip Technology Inc. DS39605F-page 289
PIC18F1220/1320
28-Lead Plastic Quad Flat, No Lead Package (ML) – 6x6 mm Body [QFN]
with 0.55 mm Contact Length
Notes:
1. Pin 1 visual index feature may vary, but must be located within the hatched area.
2. Package is saw singulated.
3. Dimensioning and tolerancing per ASME Y14.5M.
BSC: Basic Dimension. Theoretically exact value shown without tolerances.
REF: Reference Dimension, usually without tolerance, for information purposes only.
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Units MILLIMETERS
Dimension Limits MIN NOM MAX
Number of Pins N 28
Pitch e 0.65 BSC
Overall Height A 0.80 0.90 1.00
Standoff A1 0.00 0.02 0.05
Contact Thickness A3 0.20 REF
Overall Width E 6.00 BSC
Exposed Pad Width E2 3.65 3.70 4.20
Overall Length D 6.00 BSC
Exposed Pad Length D2 3.65 3.70 4.20
Contact Width b 0.23 0.30 0.35
Contact Length L 0.50 0.55 0.70
Contact-to-Exposed Pad K 0.20 – –
D EXPOSED D2
e
b
K
E2
E
L
N
NOTE 1
1
2 2
1
N
A
A3 A1
TOP VIEW BOTTOM VIEW
PAD
Microchip Technology Drawing C04-105BPIC18F1220/1320
DS39605F-page 290 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 291
PIC18F1220/1320
APPENDIX A: REVISION HISTORY
Revision A (August 2002)
Original data sheet for PIC18F1220/1320 devices.
Revision B (November 2002)
This revision includes significant changes to
Section 2.0, Section 3.0 and Section 19.0, as well as
updates to the Electrical Specifications in Section 22.0
and includes minor corrections to the data sheet text.
Revision C (May 2004)
This revision includes updates to the Electrical Specifications
in Section 22.0, the DC and AC Characteristics
Graphs and Tables in Section 23.0 and includes minor
corrections to the data sheet text.
Revision D (October 2006)
This revision includes updates to the packaging
diagrams.
Revision E (January 2007)
This revision includes updates to the packaging
diagrams.
Revision F (February 2007)
This revision includes updates to the packaging
diagrams.
APPENDIX B: DEVICE
DIFFERENCES
The differences between the devices listed in this data
sheet are shown in Table B-1.
TABLE B-1: DEVICE DIFFERENCES
Features PIC18F1220 PIC18F1320
Program Memory (Bytes) 4096 8192
Program Memory (Instructions) 2048 4096
Interrupt Sources 15 15
I/O Ports Ports A, B Ports A, B
Enhanced Capture/Compare/PWM Modules 1 1
10-bit Analog-to-Digital Module 7 input channels 7 input channels
Packages
18-pin SDIP
18-pin SOIC
20-pin SSOP
28-pin QFN
18-pin SDIP
18-pin SOIC
20-pin SSOP
28-pin QFNPIC18F1220/1320
DS39605F-page 292 © 2007 Microchip Technology Inc.
APPENDIX C: CONVERSION
CONSIDERATIONS
This appendix discusses the considerations for converting
from previous versions of a device to the ones
listed in this data sheet. Typically, these changes are
due to the differences in the process technology used.
An example of this type of conversion is from a
PIC16C74A to a PIC16C74B.
Not Applicable
APPENDIX D: MIGRATION FROM
BASELINE TO
ENHANCED DEVICES
This section discusses how to migrate from a baseline
device (i.e., PIC16C5X) to an enhanced MCU device
(i.e., PIC18FXXX).
The following are the list of modifications over the
PIC16C5X microcontroller family:
Not Currently Available© 2007 Microchip Technology Inc. DS39605F-page 293
PIC18F1220/1320
APPENDIX E: MIGRATION FROM
MID-RANGE TO
ENHANCED DEVICES
A detailed discussion of the differences between the
mid-range MCU devices (i.e., PIC16CXXX) and the
enhanced devices (i.e., PIC18FXXX) is provided in
AN716, “Migrating Designs from PIC16C74A/74B to
PIC18C442”. The changes discussed, while device
specific, are generally applicable to all mid-range to
enhanced device migrations.
This Application Note is available as Literature Number
DS00716.
APPENDIX F: MIGRATION FROM
HIGH-END TO
ENHANCED DEVICES
A detailed discussion of the migration pathway and
differences between the high-end MCU devices (i.e.,
PIC17CXXX) and the enhanced devices (i.e.,
PIC18FXXX) is provided in AN726, “PIC17CXXX to
PIC18CXXX Migration”.
This Application Note is available as Literature Number
DS00726.PIC18F1220/1320
DS39605F-page 294 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 295
PIC18F1220/1320
INDEX
A
A/D ................................................................................... 155
A/D Converter Interrupt, Configuring ....................... 159
Acquisition Requirements ........................................ 160
ADCON0 Register .................................................... 155
ADCON1 Register .................................................... 155
ADCON2 Register .................................................... 155
ADRESH Register .................................................... 155
ADRESH/ADRESL Registers .................................. 158
ADRESL Register .................................................... 155
Analog Port Pins, Configuring .................................. 162
Associated Registers ............................................... 164
Configuring the Module ............................................ 159
Conversion Clock (Tad) ........................................... 161
Conversion Requirements ....................................... 265
Conversion Status (GO/DONE Bit) .......................... 158
Conversions ............................................................. 163
Converter Characteristics ........................................ 264
Operation in Low-Power Modes ............................... 162
Selecting, Configuring Automatic
Acquisition Time ............................................... 161
Special Event Trigger (CCP) .................................... 117
Special Event Trigger (CCP1) .................................. 164
Use of the CCP1 Trigger .......................................... 164
Vref+ and Vref- References ..................................... 160
Absolute Maximum Ratings ............................................. 237
AC (Timing) Characteristics ............................................. 255
Conditions ................................................................ 256
Load Conditions for Device
Timing Specifications ....................................... 256
Parameter Symbology ............................................. 255
Temperature and Voltage Specifications ................. 256
ADCON0 Register ............................................................ 155
GO/DONE Bit ........................................................... 158
ADCON1 Register ............................................................ 155
ADCON2 Register ............................................................ 155
ADDLW ............................................................................ 197
ADDWF ............................................................................ 197
ADDWFC ......................................................................... 198
ADRESH Register ............................................................ 155
ADRESH/ADRESL Registers ........................................... 158
ADRESL Register ............................................................ 155
Analog-to-Digital Converter. See A/D.
ANDLW ............................................................................ 198
ANDWF ............................................................................ 199
Assembler
MPASM Assembler .................................................. 234
Auto-Wake-up on Sync Break Character ......................... 145
B
BC .................................................................................... 199
BCF .................................................................................. 200
Block Diagrams
A/D ........................................................................... 158
Analog Input Model .................................................. 159
Capture Mode Operation ......................................... 117
Compare Mode Operation ....................................... 118
Enhanced PWM ....................................................... 120
EUSART Receive .................................................... 143
EUSART Transmit ................................................... 141
Fail-Safe Clock Monitor ............................................ 182
Generic I/O Port Operation ........................................ 87
Low-Voltage Detect (LVD) ....................................... 166
Low-Voltage Detect (LVD) with External Input ........ 166
MCLR/VPP/RA5 Pin ................................................... 89
On-Chip Reset Circuit ................................................ 33
OSC1/CLKI/RA7 Pin .................................................. 88
OSC2/CLKO/RA6 Pin ................................................ 88
PIC18F1220/1320 ....................................................... 7
PLL ............................................................................ 12
RA3:RA0 Pins ............................................................ 88
RA4/T0CKI Pin .......................................................... 88
RB0/AN4/INT0 Pin ..................................................... 90
RB1/AN5/TX/CK/INT1 Pin ......................................... 91
RB2/P1B/INT2 Pin ..................................................... 92
RB3/CCP1/P1A Pin ................................................... 93
RB4/AN6/RX/DT/KBI0 Pin ......................................... 94
RB5/PGM/KBI1 Pin .................................................... 95
RB6/PGC/T1OSO/T13CKI/P1C/KBI2 Pin .................. 96
RB7/PGD/T1OSI/P1D/KBI3 Pin ................................. 97
Reads from Flash Program Memory .......................... 61
System Clock ............................................................. 16
Table Read Operation ............................................... 57
Table Write Operation ................................................ 58
Table Writes to Flash Program Memory .................... 63
Timer0 in 16-Bit Mode ............................................. 100
Timer0 in 8-Bit Mode ............................................... 100
Timer1 ..................................................................... 104
Timer1 (16-Bit Read/Write Mode) ............................ 104
Timer2 ..................................................................... 110
Timer3 ..................................................................... 112
Timer3 (16-bit Read/Write Mode) ............................ 112
WDT ........................................................................ 180
BN .................................................................................... 200
BNC ................................................................................. 201
BNN ................................................................................. 201
BNOV ............................................................................... 202
BNZ .................................................................................. 202
BOR. See Brown-out Reset.
BOV ................................................................................. 205
BRA ................................................................................. 203
Break Character (12-bit) Transmit and Receive .............. 146
Brown-out Reset (BOR) ..............................................34, 171
BSF .................................................................................. 203
BTFSC ............................................................................. 204
BTFSS ............................................................................. 204
BTG ................................................................................. 205
BZ .................................................................................... 206
C
C Compilers
MPLAB C18 ............................................................. 234
MPLAB C30 ............................................................. 234
CALL ................................................................................ 206
Capture (CCP Module) .................................................... 116
CCP Pin Configuration ............................................. 116
CCPR1H:CCPR1L Registers ................................... 116
Software Interrupt .................................................... 116
Timer1/Timer3 Mode Selection ................................ 116
Capture, Compare, Timer1 and Timer3
Associated Registers ............................................... 118PIC18F1220/1320
DS39605F-page 296 © 2007 Microchip Technology Inc.
Capture/Compare/PWM (CCP)
Capture Mode. See Capture.
CCP1 ........................................................................116
CCPR1H Register ............................................ 116
CCPR1L Register ............................................ 116
Compare Mode. See Compare.
Timer Resources ...................................................... 116
Clock Sources .................................................................... 15
Selection Using OSCCON Register ........................... 16
Clocking Scheme ............................................................... 45
CLRF ................................................................................ 207
CLRWDT .......................................................................... 207
Code Examples
16 x 16 Signed Multiply Routine ................................. 72
16 x 16 Unsigned Multiply Routine ............................. 72
8 x 8 Signed Multiply Routine ..................................... 71
8 x 8 Unsigned Multiply Routine ................................. 71
Changing Between Capture Prescalers ................... 117
Computed GOTO Using an Offset Value ................... 47
Data EEPROM Read .................................................69
Data EEPROM Refresh Routine ................................70
Data EEPROM Write .................................................. 69
Erasing a Flash Program Memory Row ..................... 62
Fast Register Stack .................................................... 44
How to Clear RAM (Bank 1) Using
Indirect Addressing ............................................ 53
Implementing a Real-Time Clock Using a
Timer1 Interrupt Service .................................. 107
Initializing PORTA ...................................................... 87
Initializing PORTB ...................................................... 90
Reading a Flash Program Memory Word ................... 61
Saving Status, WREG and
BSR Registers in RAM ....................................... 85
Writing to Flash Program Memory ....................... 64–65
Code Protection ............................................................... 171
COMF ............................................................................... 208
Compare (CCP Module) ...................................................117
CCP Pin Configuration ............................................. 117
CCPR1 Register ....................................................... 117
Software Interrupt ..................................................... 117
Special Event Trigger ....................................... 113, 117
Timer1/Timer3 Mode Selection ................................ 117
Compare (CCP1 Module)
Special Event Trigger ...............................................164
Computed GOTO ............................................................... 47
Configuration Bits ............................................................. 171
Context Saving During Interrupts ....................................... 85
Conversion Considerations .............................................. 292
CPFSEQ .......................................................................... 208
CPFSGT ........................................................................... 209
CPFSLT ........................................................................... 209
Customer Change Notification Service ............................302
Customer Notification Service .......................................... 302
Customer Support ............................................................ 302
D
Data EEPROM Memory .....................................................67
Associated Registers .................................................70
EEADR Register ........................................................ 67
EECON1 Register ...................................................... 67
EECON2 Register ...................................................... 67
Operation During Code-Protect .................................. 70
Protection Against Spurious Write ............................. 69
Reading ......................................................................69
Using ..........................................................................70
Write Verify ................................................................. 69
Writing ........................................................................69
Data Memory ..................................................................... 47
General Purpose Registers ....................................... 47
Map for PIC18F1220/1320 Devices ........................... 48
Special Function Registers ........................................ 49
DAW ................................................................................ 210
DC and AC Characteristics
Graphs and Tables .................................................. 267
DC Characteristics ........................................................... 250
Power-Down and Supply Current ............................ 241
Supply Voltage ......................................................... 240
DCFSNZ .......................................................................... 211
DECF ............................................................................... 210
DECFSZ .......................................................................... 211
Details on Individual Family Members ................................. 6
Development Support ...................................................... 233
Device Differences ........................................................... 291
Direct Addressing ............................................................... 54
E
Effects of Power Managed Modes on
Various Clock Sources .............................................. 18
Electrical Characteristics .................................................. 237
Enhanced Capture/Compare/PWM (ECCP) .................... 115
Outputs .................................................................... 116
PWM Mode. See PWM (ECCP Module).
Enhanced PWM Mode. See PWM (ECCP Module). ........ 119
Enhanced Universal Synchronous Asynchronous
Receiver Transmitter (EUSART) ............................. 131
Equations
16 x 16 Signed Multiplication Algorithm ..................... 72
16 x 16 Unsigned Multiplication Algorithm ................. 72
A/D Minimum Charging Time ................................... 160
Acquisition Time ...................................................... 160
Errata ................................................................................... 4
EUSART
Asynchronous Mode ................................................ 140
12-bit Break Transmit and Receive ................. 146
Associated Registers, Receive ........................ 144
Associated Registers, Transmit ....................... 142
Auto-Wake-up on Sync Break ......................... 145
Receiver .......................................................... 143
Setting up 9-bit Mode with
Address Detect ........................................ 143
Transmitter ....................................................... 140
Baud Rate Generator (BRG) ................................... 135
Associated Registers ....................................... 136
Auto-Baud Rate Detect .................................... 139
Baud Rate Error, Calculating ........................... 135
Baud Rates, Asynchronous Modes ................. 136
High Baud Rate Select (BRGH Bit) ................. 135
Power Managed Mode Operation .................... 135
Sampling .......................................................... 135
Serial Port Enable (SPEN Bit) ................................. 131
Synchronous Master Mode ...................................... 148
Associated Registers, Reception ..................... 151
Associated Registers, Transmit ....................... 149
Reception ........................................................ 150
Transmission ................................................... 148
Synchronous Slave Mode ........................................ 152
Associated Registers, Receive ........................ 153
Associated Registers, Transmit ....................... 152
Reception ........................................................ 153
Transmission ................................................... 152© 2007 Microchip Technology Inc. DS39605F-page 297
PIC18F1220/1320
F
Fail-Safe Clock Monitor .................................................... 171
Exiting Operation ..................................................... 183
Interrupts in Power Managed Modes ....................... 183
POR or Wake from Sleep ........................................ 184
WDT During Oscillator Failure ................................. 182
Fail-Safe Clock Monitor (FSCM) ...................................... 182
Fast Register Stack ............................................................ 44
Firmware Instructions ....................................................... 191
Flash Program Memory ...................................................... 57
Associated Registers ................................................. 65
Control Registers ....................................................... 58
Erase Sequence ........................................................ 62
Erasing ....................................................................... 62
Operation During Code-Protect ................................. 65
Reading ...................................................................... 61
Table Latch ................................................................ 60
Table Pointer .............................................................. 60
Boundaries Based on Operation ........................ 60
Table Pointer Boundaries .......................................... 60
Table Reads and Table Writes .................................. 57
Write Sequence ......................................................... 63
Writing to .................................................................... 63
Unexpected Termination .................................... 65
Write Verify ........................................................ 65
G
GOTO ............................................................................... 212
H
Hardware Multiplier ............................................................ 71
Introduction ................................................................ 71
Operation ................................................................... 71
Performance Comparison .......................................... 71
I
I/O Ports ............................................................................. 87
ID Locations ............................................................. 171, 188
INCF ................................................................................. 212
INCFSZ ............................................................................ 213
In-Circuit Debugger .......................................................... 188
In-Circuit Serial Programming (ICSP) ...................... 171, 188
Indirect Addressing ............................................................ 54
INDF and FSR Registers ........................................... 53
Operation ................................................................... 53
Indirect Addressing Operation ............................................ 54
Indirect File Operand .......................................................... 47
INFSNZ ............................................................................ 213
Initialization Conditions for All Registers ...................... 36–38
Instruction Cycle ................................................................. 45
Instruction Flow/Pipelining ................................................. 45
Instruction Set .................................................................. 191
ADDLW .................................................................... 197
ADDWF .................................................................... 197
ADDWFC ................................................................. 198
ANDLW .................................................................... 198
ANDWF .................................................................... 199
BC ............................................................................ 199
BCF .......................................................................... 200
BN ............................................................................ 200
BNC ......................................................................... 201
BNN ......................................................................... 201
BNOV ....................................................................... 202
BNZ .......................................................................... 202
BOV ......................................................................... 205
BRA ......................................................................... 203
BSF .......................................................................... 203
BTFSC ..................................................................... 204
BTFSS ..................................................................... 204
BTG ......................................................................... 205
BZ ............................................................................ 206
CALL ........................................................................ 206
CLRF ....................................................................... 207
CLRWDT ................................................................. 207
COMF ...................................................................... 208
CPFSEQ .................................................................. 208
CPFSGT .................................................................. 209
CPFSLT ................................................................... 209
DAW ........................................................................ 210
DCFSNZ .................................................................. 211
DECF ....................................................................... 210
DECFSZ .................................................................. 211
General Format ........................................................ 193
GOTO ...................................................................... 212
INCF ........................................................................ 212
INCFSZ .................................................................... 213
INFSNZ .................................................................... 213
IORLW ..................................................................... 214
IORWF ..................................................................... 214
LFSR ....................................................................... 215
MOVF ...................................................................... 215
MOVFF .................................................................... 216
MOVLB .................................................................... 216
MOVLW ................................................................... 217
MOVWF ................................................................... 217
MULLW .................................................................... 218
MULWF .................................................................... 218
NEGF ....................................................................... 219
NOP ......................................................................... 219
POP ......................................................................... 220
PUSH ....................................................................... 220
RCALL ..................................................................... 221
RESET ..................................................................... 221
RETFIE .................................................................... 222
RETLW .................................................................... 222
RETURN .................................................................. 223
RLCF ....................................................................... 223
RLNCF ..................................................................... 224
RRCF ....................................................................... 224
RRNCF .................................................................... 225
SETF ....................................................................... 225
SLEEP ..................................................................... 226
SUBFWB ................................................................. 226
SUBLW .................................................................... 227
SUBWF .................................................................... 227
SUBWFB ................................................................. 228
SWAPF .................................................................... 228
TBLRD ..................................................................... 229
TBLWT .................................................................... 230
TSTFSZ ................................................................... 231
XORLW ................................................................... 231
XORWF ................................................................... 232
Summary Table ....................................................... 194
INTCON Register
RBIF Bit ..................................................................... 90
INTCON Registers ............................................................. 75PIC18F1220/1320
DS39605F-page 298 © 2007 Microchip Technology Inc.
Internal Oscillator Block .....................................................14
Adjustment ................................................................. 14
INTIO Modes .............................................................. 14
INTRC Output Frequency .......................................... 14
OSCTUNE Register ...................................................14
Internal RC Oscillator
Use with WDT .......................................................... 180
Internet Address ............................................................... 302
Interrupt Sources .............................................................. 171
A/D Conversion Complete ........................................ 159
Capture Complete (CCP) ......................................... 116
Compare Complete (CCP) ....................................... 117
Interrupt-on-Change (RB7:RB4) ................................90
INTn Pin ..................................................................... 85
PORTB, Interrupt-on-Change .................................... 85
TMR0 ......................................................................... 85
TMR0 Overflow ........................................................ 101
TMR1 Overflow ........................................................ 103
TMR2 to PR2 Match .................................................110
TMR2 to PR2 Match (PWM) ............................ 109, 119
TMR3 Overflow ................................................ 111, 113
Interrupts ............................................................................ 73
Enable Bits
(CCP1IE Bit) .................................................... 116
Flag Bits
CCP1 Flag (CCP1IF Bit) .................................. 116
CCP1IF Flag (CCP1IF Bit) ............................... 117
Interrupt-on-Change (RB7:RB4)
Flag (RBIF Bit) ........................................... 90
Logic ........................................................................... 74
INTOSC Frequency Drift .................................................... 30
IORLW ............................................................................. 214
IORWF ............................................................................. 214
IPR Registers ..................................................................... 82
L
LFSR ................................................................................ 215
Low-Voltage Detect .......................................................... 165
Characteristics ......................................................... 253
Effects of a Reset ..................................................... 169
Operation ................................................................. 168
Current Consumption ....................................... 169
Reference Voltage Set Point ............................169
Operation During Sleep ............................................ 169
LVD. See Low-Voltage Detect. ........................................ 165
M
Memory Organization ......................................................... 41
Data Memory .............................................................. 47
Program Memory ....................................................... 41
Memory Programming Requirements ..............................252
Microchip Internet Web Site ............................................. 302
Migration from Baseline to Enhanced Devices ................ 292
Migration from High-End to Enhanced Devices ............... 293
Migration from Mid-Range to Enhanced Devices ............. 293
MOVF ............................................................................... 215
MOVFF ............................................................................. 216
MOVLB ............................................................................. 216
MOVLW ............................................................................ 217
MOVWF ........................................................................... 217
MPLAB ASM30 Assembler, Linker, Librarian .................. 234
MPLAB ICD 2 In-Circuit Debugger ................................... 235
MPLAB ICE 2000 High-Performance
Universal In-Circuit Emulator ................................... 235
MPLAB Integrated Development
Environment Software .............................................. 233
MPLAB PM3 Device Programmer ................................... 235
MPLAB REAL ICE In-Circuit Emulator System ................ 235
MPLINK Object Linker/MPLIB Object Librarian ............... 234
MULLW ............................................................................ 218
MULWF ............................................................................ 218
N
NEGF ............................................................................... 219
New Core Features
Multiple Oscillator Options and Features ..................... 5
nanoWatt Technology .................................................. 5
NOP ................................................................................. 219
O
Opcode Field Descriptions ............................................... 192
OPTION_REG Register
PSA Bit .................................................................... 101
T0CS Bit .................................................................. 101
T0PS2:T0PS0 Bits ................................................... 101
T0SE Bit ................................................................... 101
Oscillator Configuration ...................................................... 11
Crystal/Ceramic Resonator ........................................ 11
EC .............................................................................. 11
ECIO .......................................................................... 11
External Clock Input ................................................... 13
HS .............................................................................. 11
HSPLL ..................................................................11, 12
INTIO1 ....................................................................... 11
INTIO2 ....................................................................... 11
LP .............................................................................. 11
RC .........................................................................11, 13
RCIO .......................................................................... 11
XT .............................................................................. 11
Oscillator Selection .......................................................... 171
Oscillator Start-up Timer (OST) ............................18, 34, 171
Oscillator Switching ............................................................ 15
Oscillator Transitions ......................................................... 18
Oscillator, Timer1 ......................................................103, 113
Oscillator, Timer3 ............................................................. 111
Other Special Features ........................................................ 5
P
Packaging ........................................................................ 285
Details ...................................................................... 286
Marking Information ................................................. 285
PICSTART Plus Development Programmer .................... 236
PIE Registers ..................................................................... 80
Pin Functions
MCLR/Vpp/RA5 ........................................................... 8
OSC1/CLKI/RA7 .......................................................... 8
OSC2/CLKO/RA6 ........................................................ 8
RA0/AN0 ...................................................................... 8
RA1/AN1/LVDIN .......................................................... 8
RA2/AN2/Vref- ............................................................. 8
RA3/AN3/VREF+ ........................................................... 8
RA4/T0CKI ................................................................... 8
RB0/AN4/INT0 ............................................................. 9
RB1/AN5/TX/CK/INT1 ................................................. 9
RB2/P1B/INT2 ............................................................. 9
RB3/CCP1/P1A ........................................................... 9
RB4/AN6/RX/DT/KBI0 ................................................. 9
RB5/PGM/KBI1 ............................................................ 9
RB6/PGC/T1OSO/T13CKI/P1C/KBI2 .......................... 9
RB7/PGD/T1OSI/P1D/KBI3 ......................................... 9
Vdd .............................................................................. 9
Vss ............................................................................... 9© 2007 Microchip Technology Inc. DS39605F-page 299
PIC18F1220/1320
Pinout I/O Descriptions
PIC18F1220/1320 ........................................................ 8
PIR Registers ..................................................................... 78
PLL Lock Time-out ............................................................. 34
Pointer, FSR ....................................................................... 53
POP .................................................................................. 220
POR. See Power-on Reset.
PORTA
Associated Registers ................................................. 89
Functions ................................................................... 89
LATA Register ............................................................ 87
PORTA Register ........................................................ 87
TRISA Register .......................................................... 87
PORTB
Associated Registers ................................................. 98
Functions ................................................................... 98
LATB Register ............................................................ 90
PORTB Register ........................................................ 90
RB7:RB4 Interrupt-on-Change Flag
(RBIF Bit) ........................................................... 90
TRISB Register .......................................................... 90
Postscaler
Timer2 ...................................................................... 109
WDT
Assignment (PSA Bit) ...................................... 101
Rate Select (T0PS2:T0PS0 Bits) ..................... 101
Power Managed Modes ..................................................... 19
Comparison between Run and Idle Modes ................ 20
Entering ...................................................................... 20
Idle Modes ................................................................. 21
Multiple Sleep Commands ......................................... 20
Run Modes ................................................................. 26
Selecting .................................................................... 19
Sleep Mode ................................................................ 21
Summary (table) ........................................................ 19
Wake from .................................................................. 28
Power-on Reset (POR) .............................................. 34, 171
Power-up Delays ................................................................ 18
Power-up Timer (PWRT) .......................................18, 34, 171
Prescaler
Capture .................................................................... 117
Timer0 ...................................................................... 101
Assignment (PSA Bit) ...................................... 101
Rate Select (T0PS2:T0PS0 Bits) ..................... 101
Timer2 ...................................................................... 119
Product Identification System ........................................... 304
Program Counter
PCL Register .............................................................. 44
PCLATH Register ...................................................... 44
PCLATU Register ...................................................... 44
Program Memory
Instructions in ............................................................. 46
Interrupt Vector .......................................................... 41
Map and Stack for PIC18F1220 ................................. 41
Map and Stack for PIC18F1320 ................................. 41
Reset Vector .............................................................. 41
Program Verification and Code Protection ....................... 185
Associated Registers ............................................... 185
Configuration Register ............................................. 188
Data EEPROM ......................................................... 188
Program Memory ..................................................... 186
Programming, Device Instructions ................................... 191
PUSH ............................................................................... 220
PUSH and POP Instructions .............................................. 43
PWM (CCP Module)
CCPR1H:CCPR1L Registers ................................... 119
Duty Cycle ............................................................... 119
Example Frequencies/Resolutions .......................... 119
Period ...................................................................... 119
TMR2 to PR2 Match .........................................109, 119
PWM (ECCP Module) ...................................................... 119
Associated Registers ............................................... 130
Direction Change in Full-Bridge Output Mode ......... 124
Effects of a Reset .................................................... 129
Enhanced PWM Auto-Shutdown ............................. 126
Full-Bridge Application Example .............................. 124
Full-Bridge PWM Output (Active-High) Diagram ..... 123
Half-Bridge Output (Active-High) Diagram ............... 122
Half-Bridge Output Mode Applications Example ...... 122
Operation in Low-Power Modes .............................. 129
Output Configurations .............................................. 119
Output Relationships (Active-High) .......................... 120
Output Relationships (Active-Low) .......................... 121
Programmable Dead-Band Delay ............................ 126
PWM Direction Change (Active-High) Diagram ....... 125
PWM Direction Change at Near
100% Duty Cycle (Active-High) Diagram ......... 125
Setup for PWM Operation ........................................ 129
Start-up Considerations ........................................... 128
Q
Q Clock ............................................................................ 119
R
RAM. See Data Memory.
RCALL ............................................................................. 221
RCIO Oscillator .................................................................. 13
RCON Register
Bit Status During Initialization .................................... 35
RCSTA Register
SPEN Bit .................................................................. 131
Reader Response ............................................................ 303
Register File ....................................................................... 47
Register File Summary .................................................50–51
Registers
ADCON0 (A/D Control 0) ......................................... 155
ADCON1 (A/D Control 1) ......................................... 156
ADCON2 (A/D Control 2) ......................................... 157
BAUDCTL (Baud Rate Control) ............................... 134
CCP1CON (Enhanced CCP1 Control) .................... 115
CONFIG1H (Configuration 1 High) .......................... 172
CONFIG2H (Configuration 2 High) .......................... 174
CONFIG2L (Configuration 2 Low) ........................... 173
CONFIG3H (Configuration 3 High) .......................... 175
CONFIG4L (Configuration 4 Low) ........................... 175
CONFIG5H (Configuration 5 High) .......................... 176
CONFIG5L (Configuration 5 Low) ........................... 176
CONFIG6H (Configuration 6 High) .......................... 177
CONFIG6L (Configuration 6 Low) ........................... 177
CONFIG7H (Configuration 7 High) .......................... 178
CONFIG7L (Configuration 7 Low) ........................... 178
DEVID1 (Device ID 1) .............................................. 179
DEVID2 (Device ID 2) .............................................. 179
ECCPAS (ECCP Auto-Shutdown Control) .............. 127
EECON1 (Data EEPROM Control 1) ....................59, 68
INTCON (Interrupt Control) ........................................ 75
INTCON2 (Interrupt Control 2) ................................... 76
INTCON3 (Interrupt Control 3) ................................... 77
IPR1 (Peripheral Interrupt Priority 1) ......................... 82
IPR2 (Peripheral Interrupt Priority 2) ......................... 83
LVDCON (LVD Control) ........................................... 167
OSCCON (Oscillator Control) .................................... 17PIC18F1220/1320
DS39605F-page 300 © 2007 Microchip Technology Inc.
OSCTUNE (Oscillator Tuning) ................................... 15
PIE1 (Peripheral Interrupt Enable 1) .......................... 80
PIE2 (Peripheral Interrupt Enable 2) .......................... 81
PIR1 (Peripheral Interrupt Request (Flag) 1) ............. 78
PIR2 (Peripheral Interrupt Request (Flag) 2) ............. 79
PWM1CON (PWM Configuration) ............................126
RCON (Reset Control) ......................................... 56, 84
RCSTA (Receive Status and Control) ...................... 133
Status ......................................................................... 55
STKPTR (Stack Pointer) ............................................ 43
T0CON (Timer0 Control) ............................................ 99
T1CON (Timer 1 Control) ......................................... 103
T2CON (Timer 2 Control) ......................................... 109
T3CON (Timer3 Control) .......................................... 111
TXSTA (Transmit Status and Control) ..................... 132
WDTCON (Watchdog Timer Control) ....................... 180
RESET ............................................................................. 221
Reset .......................................................................... 33, 171
RETFIE ............................................................................ 222
RETLW ............................................................................. 222
RETURN .......................................................................... 223
Return Address Stack ........................................................ 42
and Associated Registers .......................................... 42
Return Stack Pointer (STKPTR) ........................................ 42
Revision History ............................................................... 291
RLCF ................................................................................ 223
RLNCF ............................................................................. 224
RRCF ............................................................................... 224
RRNCF ............................................................................. 225
S
SETF ................................................................................ 225
SLEEP .............................................................................. 226
Sleep
OSC1 and OSC2 Pin States ...................................... 18
Software Simulator (MPLAB SIM) .................................... 234
Special Event Trigger. See Compare
Special Features of the CPU ............................................ 171
Configuration Registers .................................... 172–178
Special Function Registers ................................................ 49
Map ............................................................................ 49
Stack Full/Underflow Resets .............................................. 43
SUBFWB .......................................................................... 226
SUBLW ............................................................................ 227
SUBWF ............................................................................ 227
SUBWFB .......................................................................... 228
SWAPF ............................................................................ 228
T
TABLAT Register ............................................................... 60
Table Pointer Operations (table) ........................................ 60
TBLPTR Register ............................................................... 60
TBLRD ............................................................................. 229
TBLWT ............................................................................. 230
Time-out Sequence ............................................................ 34
Timer0 ................................................................................ 99
16-Bit Mode Timer Reads and Writes ...................... 101
Associated Registers ...............................................101
Clock Source Edge Select (T0SE Bit) ...................... 101
Clock Source Select (T0CS Bit) ............................... 101
Operation ................................................................. 101
Overflow Interrupt ..................................................... 101
Prescaler. See Prescaler, Timer0.
Switching Prescaler Assignment ..............................101
Timer1 .............................................................................. 103
16-Bit Read/Write Mode .......................................... 106
Associated Registers ............................................... 108
Interrupt ................................................................... 106
Operation ................................................................. 104
Oscillator ...........................................................103, 105
Layout Considerations ..................................... 106
Overflow Interrupt .................................................... 103
Resetting, Using a Special Event Trigger
Output (CCP) ................................................... 106
Special Event Trigger (CCP) ................................... 117
TMR1H Register ...................................................... 103
TMR1L Register ....................................................... 103
Use as a Real-Time Clock ....................................... 107
Timer2 .............................................................................. 109
Associated Registers ............................................... 110
Operation ................................................................. 109
Output ...................................................................... 110
Postscaler. See Postscaler, Timer2.
PR2 Register ....................................................109, 119
Prescaler. See Prescaler, Timer2.
TMR2 Register ......................................................... 109
TMR2 to PR2 Match Interrupt ...................109, 110, 119
Timer3 .............................................................................. 111
Associated Registers ............................................... 113
Operation ................................................................. 112
Oscillator ...........................................................111, 113
Overflow Interrupt .............................................111, 113
Special Event Trigger (CCP) ................................... 113
TMR3H Register ...................................................... 111
TMR3L Register ....................................................... 111
Timing Diagrams
A/D Conversion ........................................................ 265
Asynchronous Reception ......................................... 144
Asynchronous Transmission .................................... 141
Asynchronous Transmission (Back to Back) ........... 142
Auto-Wake-up Bit (WUE) During
Normal Operation ............................................ 145
Auto-Wake-up Bit (WUE) During Sleep ................... 145
Brown-out Reset (BOR) ........................................... 260
Capture/Compare/PWM (All CCP Modules) ............ 262
CLKO and I/O .......................................................... 259
Clock/Instruction Cycle .............................................. 45
EUSART Synchronous Receive
(Master/Slave) ................................................. 264
EUSART SynchronousTransmission
(Master/Slave) ................................................. 263
External Clock (All Modes Except PLL) ................... 257
Fail-Safe Clock Monitor ........................................... 183
Low-Voltage Detect ................................................. 168
Low-Voltage Detect Characteristics ......................... 253
PWM Auto-Shutdown (PRSEN = 0,
Auto-Restart Disabled) .................................... 128
PWM Auto-Shutdown (PRSEN = 1,
Auto-Restart Enabled) ..................................... 128
Reset, Watchdog Timer (WDT), Oscillator Start-up
Timer (OST) and Power-up Timer (PWRT) ..... 260
Send Break Character Sequence ............................ 147
Slow Rise Time (MCLR Tied to VDD,
VDD Rise > TPWRT) ............................................ 40
Synchronous Reception
(Master Mode, SREN) ..................................... 150
Synchronous Transmission ..................................... 148
Synchronous Transmission (Through TXEN) .......... 149© 2007 Microchip Technology Inc. DS39605F-page 301
PIC18F1220/1320
Time-out Sequence on POR w/PLL Enabled
(MCLR Tied to VDD) ........................................... 40
Time-out Sequence on Power-up
(MCLR Not Tied to Vdd), Case 1 ....................... 39
Time-out Sequence on Power-up
(MCLR Not Tied to Vdd), Case 2 ....................... 39
Time-out Sequence on Power-up
(MCLR Tied to Vdd, Vdd Rise pwrt) ................... 39
Timer0 and Timer1 External Clock .......................... 261
Transition for Entry to SEC_IDLE Mode .................... 24
Transition for Entry to SEC_RUN Mode .................... 26
Transition for Entry to Sleep Mode ............................ 22
Transition for Two-Speed Start-up
(INTOSC to HSPLL) ......................................... 181
Transition for Wake from PRI_IDLE Mode ................. 23
Transition for Wake from RC_RUN Mode
(RC_RUN to PRI_RUN) ..................................... 25
Transition for Wake from SEC_RUN Mode
(HSPLL) ............................................................. 24
Transition for Wake from Sleep (HSPLL) ................... 22
Transition to PRI_IDLE Mode .................................... 23
Transition to RC_IDLE Mode ..................................... 25
Transition to RC_RUN Mode ..................................... 27
Timing Diagrams and Specifications ................................ 257
Capture/Compare/PWM Requirements
(All CCP Modules) ........................................... 263
CLKO and I/O Requirements ................................... 259
EUSART Synchronous Receive Requirements ....... 264
EUSART Synchronous
Transmission Requirements ............................ 263
External Clock Requirements .................................. 257
Internal RC Accuracy ............................................... 258
PLL Clock, HS/HSPLL Mode
(VDD = 4.2V to 5.5V) ........................................ 258
Reset, Watchdog Timer, Oscillator
Start-up Timer, Power-up Timer and
Brown-out Reset Requirements ....................... 261
Timer0 and Timer1 External Clock
Requirements ................................................... 262
Top-of-Stack Access .......................................................... 42
TSTFSZ ........................................................................... 231
Two-Speed Start-up ..................................................171, 181
Two-Word Instructions ....................................................... 46
Example Cases .......................................................... 46
TXSTA Register
BRGH Bit ................................................................. 135
W
Watchdog Timer (WDT) ............................................171, 180
Associated Registers ............................................... 181
Control Register ....................................................... 180
During Oscillator Failure .......................................... 182
Programming Considerations .................................. 180
WWW Address ................................................................ 302
WWW, On-Line Support ...................................................... 4
X
XORLW ............................................................................ 231
XORWF ........................................................................... 232PIC18F1220/1320
DS39605F-page 302 © 2007 Microchip Technology Inc.
NOTES:© 2007 Microchip Technology Inc. DS39605F-page 303
PIC18F1220/1320
THE MICROCHIP WEB SITE
Microchip provides online support via our WWW site at
www.microchip.com. This web site is used as a means
to make files and information easily available to
customers. Accessible by using your favorite Internet
browser, the web site contains the following
information:
• Product Support – Data sheets and errata,
application notes and sample programs, design
resources, user’s guides and hardware support
documents, latest software releases and archived
software
• General Technical Support – Frequently Asked
Questions (FAQ), technical support requests,
online discussion groups, Microchip consultant
program member listing
• Business of Microchip – Product selector and
ordering guides, latest Microchip press releases,
listing of seminars and events, listings of
Microchip sales offices, distributors and factory
representatives
CUSTOMER CHANGE NOTIFICATION
SERVICE
Microchip’s customer notification service helps keep
customers current on Microchip products. Subscribers
will receive e-mail notification whenever there are
changes, updates, revisions or errata related to a
specified product family or development tool of interest.
To register, access the Microchip web site at
www.microchip.com, click on Customer Change
Notification and follow the registration instructions.
CUSTOMER SUPPORT
Users of Microchip products can receive assistance
through several channels:
• Distributor or Representative
• Local Sales Office
• Field Application Engineer (FAE)
• Technical Support
• Development Systems Information Line
Customers should contact their distributor,
representative or field application engineer (FAE) for
support. Local sales offices are also available to help
customers. A listing of sales offices and locations is
included in the back of this document.
Technical support is available through the web site
at: http://support.microchip.comPIC18F1220/1320
DS39605F-page 304 © 2007 Microchip Technology Inc.
READER RESPONSE
It is our intention to provide you with the best documentation possible to ensure successful use of your Microchip product.
If you wish to provide your comments on organization, clarity, subject matter, and ways in which our documentation
can better serve you, please FAX your comments to the Technical Publications Manager at (480) 792-4150.
Please list the following information, and use this outline to provide us with your comments about this document.
To: Technical Publications Manager
RE: Reader Response
Total Pages Sent ________
From: Name
Company
Address
City / State / ZIP / Country
Telephone: (_______) _________ - _________
Application (optional):
Would you like a reply? Y N
Device: Literature Number:
Questions:
FAX: (______) _________ - _________
PIC18F1220/1320 DS39605F
1. What are the best features of this document?
2. How does this document meet your hardware and software development needs?
3. Do you find the organization of this document easy to follow? If not, why?
4. What additions to the document do you think would enhance the structure and subject?
5. What deletions from the document could be made without affecting the overall usefulness?
6. Is there any incorrect or misleading information (what and where)?
7. How would you improve this document?© 2007 Microchip Technology Inc. DS39605F-page 305
PIC18F1220/1320
PIC18F1220/1320 PRODUCT IDENTIFICATION SYSTEM
To order or obtain information, e.g., on pricing or delivery, refer to the factory or the listed sales office.
PART NO. − X /XX XXX
Temperature Package Pattern
Range
Device
Device PIC18F1220/1320(1),
PIC18F1220/1320T(2);
VDD range 4.2V to 5.5V
PIC18LF1220/1320(1),
PIC18LF1220/1320T(2);
VDD range 2.5V to 5.5V
Temperature
Range
I = -40°C to +85°C (Industrial)
E = -40°C to +125°C (Extended)
Package SO = SOIC SS = SSOP
P = PDIP ML = QFN
Pattern QTP, SQTP, Code or Special Requirements
(blank otherwise)
Examples:
a) PIC18LF1320-I/P 301 = Industrial
temp., PDIP package, Extended
VDD limits, QTP pattern #301.
b) PIC18LF1220-I/SO = Industrial
temp., SOIC package, Extended
VDD limits.
Note 1: F = Standard Voltage range
LF = Wide Voltage Range
2: T = in tape and reel – SOIC
package onlyDS39605F-page 306 © 2007 Microchip Technology Inc.
AMERICAS
Corporate Office
2355 West Chandler Blvd.
Chandler, AZ 85224-6199
Tel: 480-792-7200
Fax: 480-792-7277
Technical Support:
http://support.microchip.com
Web Address:
www.microchip.com
Atlanta
Duluth, GA
Tel: 678-957-9614
Fax: 678-957-1455
Boston
Westborough, MA
Tel: 774-760-0087
Fax: 774-760-0088
Chicago
Itasca, IL
Tel: 630-285-0071
Fax: 630-285-0075
Dallas
Addison, TX
Tel: 972-818-7423
Fax: 972-818-2924
Detroit
Farmington Hills, MI
Tel: 248-538-2250
Fax: 248-538-2260
Kokomo
Kokomo, IN
Tel: 765-864-8360
Fax: 765-864-8387
Los Angeles
Mission Viejo, CA
Tel: 949-462-9523
Fax: 949-462-9608
Santa Clara
Santa Clara, CA
Tel: 408-961-6444
Fax: 408-961-6445
Toronto
Mississauga, Ontario,
Canada
Tel: 905-673-0699
Fax: 905-673-6509
ASIA/PACIFIC
Asia Pacific Office
Suites 3707-14, 37th Floor
Tower 6, The Gateway
Habour City, Kowloon
Hong Kong
Tel: 852-2401-1200
Fax: 852-2401-3431
Australia - Sydney
Tel: 61-2-9868-6733
Fax: 61-2-9868-6755
China - Beijing
Tel: 86-10-8528-2100
Fax: 86-10-8528-2104
China - Chengdu
Tel: 86-28-8665-5511
Fax: 86-28-8665-7889
China - Fuzhou
Tel: 86-591-8750-3506
Fax: 86-591-8750-3521
China - Hong Kong SAR
Tel: 852-2401-1200
Fax: 852-2401-3431
China - Qingdao
Tel: 86-532-8502-7355
Fax: 86-532-8502-7205
China - Shanghai
Tel: 86-21-5407-5533
Fax: 86-21-5407-5066
China - Shenyang
Tel: 86-24-2334-2829
Fax: 86-24-2334-2393
China - Shenzhen
Tel: 86-755-8203-2660
Fax: 86-755-8203-1760
China - Shunde
Tel: 86-757-2839-5507
Fax: 86-757-2839-5571
China - Wuhan
Tel: 86-27-5980-5300
Fax: 86-27-5980-5118
China - Xian
Tel: 86-29-8833-7250
Fax: 86-29-8833-7256
ASIA/PACIFIC
India - Bangalore
Tel: 91-80-4182-8400
Fax: 91-80-4182-8422
India - New Delhi
Tel: 91-11-4160-8631
Fax: 91-11-4160-8632
India - Pune
Tel: 91-20-2566-1512
Fax: 91-20-2566-1513
Japan - Yokohama
Tel: 81-45-471- 6166
Fax: 81-45-471-6122
Korea - Gumi
Tel: 82-54-473-4301
Fax: 82-54-473-4302
Korea - Seoul
Tel: 82-2-554-7200
Fax: 82-2-558-5932 or
82-2-558-5934
Malaysia - Penang
Tel: 60-4-646-8870
Fax: 60-4-646-5086
Philippines - Manila
Tel: 63-2-634-9065
Fax: 63-2-634-9069
Singapore
Tel: 65-6334-8870
Fax: 65-6334-8850
Taiwan - Hsin Chu
Tel: 886-3-572-9526
Fax: 886-3-572-6459
Taiwan - Kaohsiung
Tel: 886-7-536-4818
Fax: 886-7-536-4803
Taiwan - Taipei
Tel: 886-2-2500-6610
Fax: 886-2-2508-0102
Thailand - Bangkok
Tel: 66-2-694-1351
Fax: 66-2-694-1350
EUROPE
Austria - Wels
Tel: 43-7242-2244-39
Fax: 43-7242-2244-393
Denmark - Copenhagen
Tel: 45-4450-2828
Fax: 45-4485-2829
France - Paris
Tel: 33-1-69-53-63-20
Fax: 33-1-69-30-90-79
Germany - Munich
Tel: 49-89-627-144-0
Fax: 49-89-627-144-44
Italy - Milan
Tel: 39-0331-742611
Fax: 39-0331-466781
Netherlands - Drunen
Tel: 31-416-690399
Fax: 31-416-690340
Spain - Madrid
Tel: 34-91-708-08-90
Fax: 34-91-708-08-91
UK - Wokingham
Tel: 44-118-921-5869
Fax: 44-118-921-5820
WORLDWIDE SALES AND SERVICE
12/08/06
2586QS–AVR–08/2013
Features
• High Performance, Low Power AVR® 8-Bit Microcontroller
• Advanced RISC Architecture
– 120 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
• Non-volatile Program and Data Memories
– 2/4/8K Bytes of In-System Programmable Program Memory Flash
• Endurance: 10,000 Write/Erase Cycles
– 128/256/512 Bytes In-System Programmable EEPROM
• Endurance: 100,000 Write/Erase Cycles
– 128/256/512 Bytes Internal SRAM
– Programming Lock for Self-Programming Flash Program and EEPROM Data Security
• Peripheral Features
– 8-bit Timer/Counter with Prescaler and Two PWM Channels
– 8-bit High Speed Timer/Counter with Separate Prescaler
• 2 High Frequency PWM Outputs with Separate Output Compare Registers
• Programmable Dead Time Generator
– USI – Universal Serial Interface with Start Condition Detector
– 10-bit ADC
• 4 Single Ended Channels
• 2 Differential ADC Channel Pairs with Programmable Gain (1x, 20x)
• Temperature Measurement
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
• Special Microcontroller Features
– debugWIRE On-chip Debug System
– In-System Programmable via SPI Port
– External and Internal Interrupt Sources
– Low Power Idle, ADC Noise Reduction, and Power-down Modes
– Enhanced Power-on Reset Circuit
– Programmable Brown-out Detection Circuit
– Internal Calibrated Oscillator
• I/O and Packages
– Six Programmable I/O Lines
– 8-pin PDIP, 8-pin SOIC, 20-pad QFN/MLF, and 8-pin TSSOP (only ATtiny45/V)
• Operating Voltage
– 1.8 - 5.5V for ATtiny25V/45V/85V
– 2.7 - 5.5V for ATtiny25/45/85
• Speed Grade
– ATtiny25V/45V/85V: 0 – 4 MHz @ 1.8 - 5.5V, 0 - 10 MHz @ 2.7 - 5.5V
– ATtiny25/45/85: 0 – 10 MHz @ 2.7 - 5.5V, 0 - 20 MHz @ 4.5 - 5.5V
• Industrial Temperature Range
• Low Power Consumption
– Active Mode:
• 1 MHz, 1.8V: 300 µA
– Power-down Mode:
• 0.1 µA at 1.8V
Atmel 8-bit AVR Microcontroller with 2/4/8K
Bytes In-System Programmable Flash
ATtiny25/V / ATtiny45/V / ATtiny85/V
Summary
Rev. 2586QS–AVR–08/2013ATtiny25/45/85 [DATASHEET] 2
2586QS–AVR–08/2013
1. Pin Configurations
Figure 1-1. Pinout ATtiny25/45/85
1.1 Pin Descriptions
1.1.1 VCC
Supply voltage.
1.1.2 GND
Ground.
1.1.3 Port B (PB5:PB0)
Port B is a 6-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers
have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are
externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
1
2
3
4
8
7
6
5
(PCINT5/RESET/ADC0/dW) PB5
(PCINT3/XTAL1/CLKI/OC1B/ADC3) PB3
(PCINT4/XTAL2/CLKO/OC1B/ADC2) PB4
GND
VCC
PB2 (SCK/USCK/SCL/ADC1/T0/INT0/PCINT2)
PB1 (MISO/DO/AIN1/OC0B/OC1A/PCINT1)
PB0 (MOSI/DI/SDA/AIN0/OC0A/OC1A/AREF/PCINT0)
PDIP/SOIC/TSSOP
1
2
3
4
5
QFN/MLF
15
14
13
12
11
20
19
18
17
16
6
7
8
9
10
DNC
DNC
GND
DNC
DNC
DNC
DNC
DNC
DNC
DNC
NOTE: Bottom pad should be soldered to ground.
DNC: Do Not Connect
NOTE: TSSOP only for ATtiny45/V
(PCINT5/RESET/ADC0/dW) PB5
(PCINT3/XTAL1/CLKI/OC1B/ADC3) PB3
DNC
DNC
(PCINT4/XTAL2/CLKO/OC1B/ADC2) PB4
VCC
PB2 (SCK/USCK/SCL/ADC1/T0/INT0/PCINT2)
DNC
PB1 (MISO/DO/AIN1/OC0B/OC1A/PCINT1)
PB0 (MOSI/DI/SDA/AIN0/OC0A/OC1A/AREF/PCINT0)ATtiny25/45/85 [DATASHEET] 3
2586QS–AVR–08/2013
Port B also serves the functions of various special features of the ATtiny25/45/85 as listed in “Alternate Functions
of Port B” on page 60.
On ATtiny25, the programmable I/O ports PB3 and PB4 (pins 2 and 3) are exchanged in ATtiny15 Compatibility
Mode for supporting the backward compatibility with ATtiny15.
1.1.4 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock
is not running and provided the reset pin has not been disabled. The minimum pulse length is given in Table 21-4
on page 165. Shorter pulses are not guaranteed to generate a reset.
The reset pin can also be used as a (weak) I/O pin.ATtiny25/45/85 [DATASHEET] 4
2586QS–AVR–08/2013
2. Overview
The ATtiny25/45/85 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By
executing powerful instructions in a single clock cycle, the ATtiny25/45/85 achieves throughputs approaching 1
MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.
2.1 Block Diagram
Figure 2-1. Block Diagram
The AVR core combines a rich instruction set with 32 general purpose working registers. All 32 registers are
directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one
single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving
throughputs up to ten times faster than conventional CISC microcontrollers.
PROGRAM
COUNTER
CALIBRATED
INTERNAL
OSCILLATOR
WATCHDOG
TIMER
STACK
POINTER
PROGRAM
FLASH SRAM
MCU CONTROL
REGISTER
GENERAL
PURPOSE
REGISTERS
INSTRUCTION
REGISTER
TIMER/
COUNTER0
SERIAL
UNIVERSAL
INTERFACE
TIMER/
COUNTER1
INSTRUCTION
DECODER
DATA DIR.
REG.PORT B
DATA REGISTER
PORT B
PROGRAMMING
LOGIC
TIMING AND
CONTROL
MCU STATUS
REGISTER
STATUS
REGISTER
ALU
PORT B DRIVERS
PB[0:5]
VCC
GND
CONTROL
LINES
8-BIT DATABUS
Z
ADC /
ANALOG COMPARATOR
INTERRUPT
UNIT
DATA
EEPROM OSCILLATORS
Y
X
RESETATtiny25/45/85 [DATASHEET] 5
2586QS–AVR–08/2013
The ATtiny25/45/85 provides the following features: 2/4/8K bytes of In-System Programmable Flash, 128/256/512
bytes EEPROM, 128/256/256 bytes SRAM, 6 general purpose I/O lines, 32 general purpose working registers, one
8-bit Timer/Counter with compare modes, one 8-bit high speed Timer/Counter, Universal Serial Interface, Internal
and External Interrupts, a 4-channel, 10-bit ADC, a programmable Watchdog Timer with internal Oscillator, and
three software selectable power saving modes. Idle mode stops the CPU while allowing the SRAM, Timer/Counter,
ADC, Analog Comparator, and Interrupt system to continue functioning. Power-down mode saves the register contents,
disabling all chip functions until the next Interrupt or Hardware Reset. ADC Noise Reduction mode stops the
CPU and all I/O modules except ADC, to minimize switching noise during ADC conversions.
The device is manufactured using Atmel’s high density non-volatile memory technology. The On-chip ISP Flash
allows the Program memory to be re-programmed In-System through an SPI serial interface, by a conventional
non-volatile memory programmer or by an On-chip boot code running on the AVR core.
The ATtiny25/45/85 AVR is supported with a full suite of program and system development tools including: C Compilers,
Macro Assemblers, Program Debugger/Simulators and Evaluation kits.ATtiny25/45/85 [DATASHEET] 6
2586QS–AVR–08/2013
3. About
3.1 Resources
A comprehensive set of development tools, application notes and datasheets are available for download on
http://www.atmel.com/avr.
3.2 Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These
code examples assume that the part specific header file is included before compilation. Be aware that not all C
compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent.
Please confirm with the C compiler documentation for more details.
For I/O Registers located in the extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI” instructions must
be replaced with instructions that allow access to extended I/O. Typically, this means “LDS” and “STS” combined
with “SBRS”, “SBRC”, “SBR”, and “CBR”. Note that not all AVR devices include an extended I/O map.
3.3 Capacitive Touch Sensing
Atmel QTouch Library provides a simple to use solution for touch sensitive interfaces on Atmel AVR microcontrollers.
The QTouch Library includes support for QTouch® and QMatrix® acquisition methods.
Touch sensing is easily added to any application by linking the QTouch Library and using the Application Programming
Interface (API) of the library to define the touch channels and sensors. The application then calls the API to
retrieve channel information and determine the state of the touch sensor.
The QTouch Library is free and can be downloaded from the Atmel website. For more information and details of
implementation, refer to the QTouch Library User Guide – also available from the Atmel website.
3.4 Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20
years at 85°C or 100 years at 25°C.ATtiny25/45/85 [DATASHEET] 7
2586QS–AVR–08/2013
4. Register Summary
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x3F SREG I T H S V N Z C page 8
0x3E SPH – – – – – – SP9 SP8 page 11
0x3D SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 page 11
0x3C Reserved –
0x3B GIMSK – INT0 PCIE – – – – – page 51
0x3A GIFR – INTF0 PCIF – – – – – page 52
0x39 TIMSK – OCIE1A OCIE1B OCIE0A OCIE0B TOIE1 TOIE0 – pages 81, 102
0x38 TIFR – OCF1A OCF1B OCF0A OCF0B TOV1 TOV0 – page 81
0x37 SPMCSR – – RSIG CTPB RFLB PGWRT PGERS SPMEN page 145
0x36 Reserved –
0x35 MCUCR BODS PUD SE SM1 SM0 BODSE ISC01 ISC00 pages 37, 51, 64
0x34 MCUSR – – – – WDRF BORF EXTRF PORF page 44,
0x33 TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00 page 79
0x32 TCNT0 Timer/Counter0 page 80
0x31 OSCCAL Oscillator Calibration Register page 31
0x30 TCCR1 CTC1 PWM1A COM1A1 COM1A0 CS13 CS12 CS11 CS10 pages 89, 100
0x2F TCNT1 Timer/Counter1 pages 91, 102
0x2E OCR1A Timer/Counter1 Output Compare Register A pages 91, 102
0x2D OCR1C Timer/Counter1 Output Compare Register C pages 91, 102
0x2C GTCCR TSM PWM1B COM1B1 COM1B0 FOC1B FOC1A PSR1 PSR0 pages 77, 90, 101
0x2B OCR1B Timer/Counter1 Output Compare Register B page 92
0x2A TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – WGM01 WGM00 page 77
0x29 OCR0A Timer/Counter0 – Output Compare Register A page 80
0x28 OCR0B Timer/Counter0 – Output Compare Register B page 81
0x27 PLLCSR LSM – – – – PCKE PLLE PLOCK pages 94, 103
0x26 CLKPR CLKPCE – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 page 32
0x25 DT1A DT1AH3 DT1AH2 DT1AH1 DT1AH0 DT1AL3 DT1AL2 DT1AL1 DT1AL0 page 107
0x24 DT1B DT1BH3 DT1BH2 DT1BH1 DT1BH0 DT1BL3 DT1BL2 DT1BL1 DT1BL0 page 107
0x23 DTPS1 - - - - - - DTPS11 DTPS10 page 106
0x22 DWDR DWDR[7:0] page 140
0x21 WDTCR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 page 45
0x20 PRR – PRTIM1 PRTIM0 PRUSI PRADC page 36
0x1F EEARH EEAR8 page 20
0x1E EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 page 21
0x1D EEDR EEPROM Data Register page 21
0x1C EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE page 21
0x1B Reserved –
0x1A Reserved –
0x19 Reserved –
0x18 PORTB – – PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 page 64
0x17 DDRB – – DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 page 64
0x16 PINB – – PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 page 64
0x15 PCMSK – – PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 page 52
0x14 DIDR0 – – ADC0D ADC2D ADC3D ADC1D AIN1D AIN0D pages 121, 138
0x13 GPIOR2 General Purpose I/O Register 2 page 10
0x12 GPIOR1 General Purpose I/O Register 1 page 10
0x11 GPIOR0 General Purpose I/O Register 0 page 10
0x10 USIBR USI Buffer Register page 115
0x0F USIDR USI Data Register page 115
0x0E USISR USISIF USIOIF USIPF USIDC USICNT3 USICNT2 USICNT1 USICNT0 page 115
0x0D USICR USISIE USIOIE USIWM1 USIWM0 USICS1 USICS0 USICLK USITC page 116
0x0C Reserved –
0x0B Reserved –
0x0A Reserved –
0x09 Reserved –
0x08 ACSR ACD ACBG ACO ACI ACIE – ACIS1 ACIS0 page 120
0x07 ADMUX REFS1 REFS0 ADLAR REFS2 MUX3 MUX2 MUX1 MUX0 page 134
0x06 ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 page 136
0x05 ADCH ADC Data Register High Byte page 137
0x04 ADCL ADC Data Register Low Byte page 137
0x03 ADCSRB BIN ACME IPR – – ADTS2 ADTS1 ADTS0 pages 120, 137
0x02 Reserved –
0x01 Reserved –
0x00 Reserved –ATtiny25/45/85 [DATASHEET] 8
2586QS–AVR–08/2013
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operation the specified bit, and can therefore be used on registers containing such Status Flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.ATtiny25/45/85 [DATASHEET] 9
2586QS–AVR–08/2013
5. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd Rd Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd Rd K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z,N,V 1
COM Rd One’s Complement Rd 0xFF Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd 0x00 Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd Rd (0xFF - K) Z,N,V 1
INC Rd Increment Rd Rd + 1 Z,N,V 1
DEC Rd Decrement Rd Rd 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd Rd Rd Z,N,V 1
CLR Rd Clear Register Rd Rd Rd Z,N,V 1
SER Rd Set Register Rd 0xFF None 1
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC Z None 2
RCALL k Relative Subroutine Call PC PC + k + 1 None 3
ICALL Indirect Call to (Z) PC Z None 3
RET Subroutine Return PC STACK None 4
RETI Interrupt Return PC STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd Rr C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) 0 None 2
LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z,C,N,V 1
ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z,C,N,V 1ATtiny25/45/85 [DATASHEET] 10
2586QS–AVR–08/2013
SWAP Rd Swap Nibbles Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) T None 1
SEC Set Carry C 1 C1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1 N1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1 Z1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1 I1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1 S1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Twos Complement Overflow. V 1 V1
CLV Clear Twos Complement Overflow V 0 V 1
SET Set T in SREG T 1 T1
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1 H1
CLH Clear Half Carry Flag in SREG H 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd K None 1
LD Rd, X Load Indirect Rd (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2
LD Rd, Y Load Indirect Rd (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2
LD Rd, Z Load Indirect Rd (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd (k) None 2
ST X, Rr Store Indirect (X) Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) Rr, X X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2
ST Y, Rr Store Indirect (Y) Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) Rr, Y Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) Rr None 2
ST Z, Rr Store Indirect (Z) Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2
STS k, Rr Store Direct to SRAM (k) Rr None 2
LPM Load Program Memory R0 (Z) None 3
LPM Rd, Z Load Program Memory Rd (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd (Z), Z Z+1 None 3
SPM Store Program Memory (z) R1:R0 None
IN Rd, P In Port Rd P None 1
OUT P, Rr Out Port P Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 2
POP Rd Pop Register from Stack Rd STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/Timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #ClocksATtiny25/45/85 [DATASHEET] 11
2586QS–AVR–08/2013
6. Ordering Information
Notes: 1. For speed vs. supply voltage, see section 21.3 “Speed” on page 163.
2. All Pb-free, halide-free, fully green, and comply with European directive for Restriction of Hazardous Substances (RoHS).
3. Code indicators: H = NiPdAu lead finish, U/N = matte tin, R = tape & reel.
4. Can also be supplied in wafer form. Contact your local Atmel sales office for ordering information and minimum quantities.
5. For characteristics, see “Appendix A – Specification at 105C”.
6. For characteristics, see “Appendix B – Specification at 125C”.
6.1 ATtiny25
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
10 1.8 – 5.5
Industrial
(-40C to +85C) (4)
8P3 ATtiny25V-10PU
8S2
ATtiny25V-10SU
ATtiny25V-10SUR
ATtiny25V-10SH
ATtiny25V-10SHR
S8S1
ATtiny25V-10SSU
ATtiny25V-10SSUR
ATtiny25V-10SSH
ATtiny25V-10SSHR
20M1 ATtiny25V-10MU
ATtiny25V-10MUR
Industrial
(-40C to +105C) (5)
8S2 ATtiny25V-10SN
ATtiny25V-10SNR
S8S1 ATtiny25V-10SSN
ATtiny25V-10SSNR
Industrial (-40C to +125C) (6) 20M1 ATtiny25V-10MF
ATtiny25V-10MFR
20 2.7 – 5.5
Industrial
(-40C to +85C) (4)
8P3 ATtiny25-20PU
8S2
ATtiny25-20SU
ATtiny25-20SUR
ATtiny25-20SH
ATtiny25-20SHR
S8S1
ATtiny25-20SSU
ATtiny25-20SSUR
ATtiny25-20SSH
ATtiny25-20SSHR
20M1 ATtiny25-20MU
ATtiny25-20MUR
Industrial
(-40C to +105C) (5)
8S2 ATtiny25-20SN
ATtiny25-20SNR
S8S1 ATtiny25-20SSN
ATtiny25-20SSNR
Industrial (-40C to +125C) (6) 20M1 ATtiny25-20MF
ATtiny25-20MFR
Package Types
8P3 8-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
8S2 8-lead, 0.208" Wide, Plastic Gull-Wing Small Outline (EIAJ SOIC)
S8S1 8-lead, 0.150" Wide, Plastic Gull-Wing Small Outline (JEDEC SOIC)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)ATtiny25/45/85 [DATASHEET] 12
2586QS–AVR–08/2013
Notes: 1. For speed vs. supply voltage, see section 21.3 “Speed” on page 163.
2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– U: matte tin
– R: tape & reel
4. These devices can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
6.2 ATtiny45
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
10 1.8 – 5.5 Industrial
(-40C to +85C) (4)
8P3 ATtiny45V-10PU
8S2
ATtiny45V-10SU
ATtiny45V-10SUR
ATtiny45V-10SH
ATtiny45V-10SHR
8X ATtiny45V-10XU
ATtiny45V-10XUR
20M1 ATtiny45V-10MU
ATtiny45V-10MUR
20 2.7 – 5.5 Industrial
(-40C to +85C) (4)
8P3 ATtiny45-20PU
8S2
ATtiny45-20SU
ATtiny45-20SUR
ATtiny45-20SH
ATtiny45-20SHR
8X ATtiny45-20XU
ATtiny45-20XUR
20M1 ATtiny45-20MU
ATtiny45-20MUR
Package Types
8P3 8-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
8S2 8-lead, 0.208" Wide, Plastic Gull-Wing Small Outline (EIAJ SOIC)
8X 8-lead, 4.4 mm Wide, Plastic Thin Shrink Small Outline Package (TSSOP)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)ATtiny25/45/85 [DATASHEET] 13
2586QS–AVR–08/2013
Notes: 1. For speed vs. supply voltage, see section 21.3 “Speed” on page 163.
2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– U: matte tin
– R: tape & reel
4. These devices can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
6.3 ATtiny85
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
10 1.8 – 5.5 Industrial
(-40C to +85C) (4)
8P3 ATtiny85V-10PU
8S2
ATtiny85V-10SU
ATtiny85V-10SUR
ATtiny85V-10SH
ATtiny85V-10SHR
20M1 ATtiny85V-10MU
ATtiny85V-10MUR
20 2.7 – 5.5 Industrial
(-40C to +85C) (4)
8P3 ATtiny85-20PU
8S2
ATtiny85-20SU
ATtiny85-20SUR
ATtiny85-20SH
ATtiny85-20SHR
20M1 ATtiny85-20MU
ATtiny85-20MUR
Package Types
8P3 8-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
8S2 8-lead, 0.208" Wide, Plastic Gull-Wing Small Outline (EIAJ SOIC)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)ATtiny25/45/85 [DATASHEET] 14
2586QS–AVR–08/2013
7. Packaging Information
7.1 8P3
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
8P3, 8-lead, 0.300" Wide Body, Plastic Dual
In-line Package (PDIP)
01/09/02
8P3 B
D
D1
E
E1
e
b2 L
b
A2 A
1
N
eA
c
b3
4 PLCS
Top View
Side View
End View
COMMON DIMENSIONS
(Unit of Measure = inches)
SYMBOL MIN NOM MAX NOTE
Notes: 1. This drawing is for general information only; refer to JEDEC Drawing MS-001, Variation BA for additional information.
2. Dimensions A and L are measured with the package seated in JEDEC seating plane Gauge GS-3.
3. D, D1 and E1 dimensions do not include mold Flash or protrusions. Mold Flash or protrusions shall not exceed 0.010 inch.
4. E and eA measured with the leads constrained to be perpendicular to datum.
5. Pointed or rounded lead tips are preferred to ease insertion.
6. b2 and b3 maximum dimensions do not include Dambar protrusions. Dambar protrusions shall not exceed 0.010 (0.25 mm).
A 0.210 2
A2 0.115 0.130 0.195
b 0.014 0.018 0.022 5
b2 0.045 0.060 0.070 6
b3 0.030 0.039 0.045 6
c 0.008 0.010 0.014
D 0.355 0.365 0.400 3
D1 0.005 3
E 0.300 0.310 0.325 4
E1 0.240 0.250 0.280 3
e 0.100 BSC
eA 0.300 BSC 4
L 0.115 0.130 0.150 2ATtiny25/45/85 [DATASHEET] 15
2586QS–AVR–08/2013
7.2 8S2
TITLE GPC DRAWING NO. REV.
Package Drawing Contact:
packagedrawings@atmel.com STN F 8S2
8S2, 8-lead, 0.208” Body, Plastic Small
Outline Package (EIAJ)
4/15/08
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
Notes: 1. This drawing is for general information only; refer to EIAJ Drawing EDR-7320 for additional information.
2. Mismatch of the upper and lower dies and resin burrs aren't included.
3. Determines the true geometric position.
4. Values b,C apply to plated terminal. The standard thickness of the plating layer shall measure between 0.007 to .021 mm.
A 1.70 2.16
A1 0.05 0.25
b 0.35 0.48 4
C 0.15 0.35 4
D 5.13 5.35
E1 5.18 5.40 2
E 7.70 8.26
L 0.51 0.85
θ 0° 8°
e 1.27 BSC 3
θ
1
N
E
TOP VIEW TOP VIEW
C
E1
END VIEW END VIEW
A
b
L
A1
e
D
SIDE VIEW SIDE VIEWATtiny25/45/85 [DATASHEET] 16
2586QS–AVR–08/2013
7.3 S8S1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
S8S1, 8-lead, 0.150" Wide Body, Plastic Gull Wing Small
Outline (JEDEC SOIC)
7/28/03
S8S1 A
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
Notes: 1. This drawing is for general information only; refer to JEDEC Drawing MS-012 for proper dimensions, tolerances, datums,etc.
E 5.79 6.20
E1 3.81 3.99
A 1.35 1.75
A1 0.1 0.25
D 4.80 4.98
C 0.17 0.25
b 0.31 0.51
L 0.4 1.27
e 1.27 BSC
0o
8o
Top View
Side View
End View
1
N
C
A
A1
b
L
e
D
E1 EATtiny25/45/85 [DATASHEET] 17
2586QS–AVR–08/2013
7.4 8X
TITLE DRAWING NO.
R
REV.
Note: These drawings are for general information only. Refer to JEDEC Drawing MO-153AC.
2325 Orchard Parkway
San Jose, CA 95131
4/14/05
8X, 8-lead, 4.4 mm Body Width, Plastic Thin Shrink
Small Outline Package (TSSOP) 8X A
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A 1.05 1.10 1.20
A1 0.05 0.10 0.15
b 0.25 – 0.30
C – 0.127 –
D 2.90 3.05 3.10
E1 4.30 4.40 4.50
E 6.20 6.40 6.60
e 0.65 TYP
L 0.50 0.60 0.70
Ø 0o – 8o
C
A
b
L
A1
D
Side View
Top View
End View
E
1
E1
e
ØATtiny25/45/85 [DATASHEET] 18
2586QS–AVR–08/2013
7.5 20M1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
20M1, 20-pad, 4 x 4 x 0.8 mm Body, Lead Pitch 0.50 mm, 20M1 B
10/27/04
2.6 mm Exposed Pad, Micro Lead Frame Package (MLF)
A 0.70 0.75 0.80
A1 – 0.01 0.05
A2 0.20 REF
b 0.18 0.23 0.30
D 4.00 BSC
D2 2.45 2.60 2.75
E 4.00 BSC
E2 2.45 2.60 2.75
e 0.50 BSC
L 0.35 0.40 0.55
SIDE VIEW
Pin 1 ID
Pin #1
Notch
(0.20 R)
BOTTOM VIEW
TOP VIEW
Note: Reference JEDEC Standard MO-220, Fig. 1 (SAW Singulation) WGGD-5.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D
E
e
A2
A1
A
D2
E2
0.08 C
L
1
2
3
b
1
2
3ATtiny25/45/85 [DATASHEET] 19
2586QS–AVR–08/2013
8. Errata
8.1 Errata ATtiny25
The revision letter in this section refers to the revision of the ATtiny25 device.
8.1.1 Rev D – F
No known errata.
8.1.2 Rev B – C
• EEPROM read may fail at low supply voltage / low clock frequency
1. EEPROM read may fail at low supply voltage / low clock frequency
Trying to read EEPROM at low clock frequencies and/or low supply voltage may result in invalid data.
Problem Fix/Workaround
Do not use the EEPROM when clock frequency is below 1MHz and supply voltage is below 2V. If operating frequency
can not be raised above 1MHz then supply voltage should be more than 2V. Similarly, if supply voltage
can not be raised above 2V then operating frequency should be more than 1MHz.
This feature is known to be temperature dependent but it has not been characterised. Guidelines are given for
room temperature, only.
8.1.3 Rev A
Not sampled.
8.2 Errata ATtiny45
The revision letter in this section refers to the revision of the ATtiny45 device.
8.2.1 Rev F – G
No known errata
8.2.2 Rev D – E
• EEPROM read may fail at low supply voltage / low clock frequency
1. EEPROM read may fail at low supply voltage / low clock frequency
Trying to read EEPROM at low clock frequencies and/or low supply voltage may result in invalid data.
Problem Fix/Workaround
Do not use the EEPROM when clock frequency is below 1MHz and supply voltage is below 2V. If operating frequency
can not be raised above 1MHz then supply voltage should be more than 2V. Similarly, if supply voltage
can not be raised above 2V then operating frequency should be more than 1MHz.
This feature is known to be temperature dependent but it has not been characterised. Guidelines are given for
room temperature, only.ATtiny25/45/85 [DATASHEET] 20
2586QS–AVR–08/2013
8.2.3 Rev B – C
• PLL not locking
• EEPROM read from application code does not work in Lock Bit Mode 3
• EEPROM read may fail at low supply voltage / low clock frequency
• Timer Counter 1 PWM output generation on OC1B- XOC1B does not work correctly
1. PLL not locking
When at frequencies below 6.0 MHz, the PLL will not lock
Problem fix / Workaround
When using the PLL, run at 6.0 MHz or higher.
2. EEPROM read from application code does not work in Lock Bit Mode 3
When the Memory Lock Bits LB2 and LB1 are programmed to mode 3, EEPROM read does not work from the
application code.
Problem Fix/Work around
Do not set Lock Bit Protection Mode 3 when the application code needs to read from EEPROM.
3. EEPROM read may fail at low supply voltage / low clock frequency
Trying to read EEPROM at low clock frequencies and/or low supply voltage may result in invalid data.
Problem Fix/Workaround
Do not use the EEPROM when clock frequency is below 1MHz and supply voltage is below 2V. If operating frequency
can not be raised above 1MHz then supply voltage should be more than 2V. Similarly, if supply voltage
can not be raised above 2V then operating frequency should be more than 1MHz.
This feature is known to be temperature dependent but it has not been characterised. Guidelines are given for
room temperature, only.
4. Timer Counter 1 PWM output generation on OC1B – XOC1B does not work correctly
Timer Counter1 PWM output OC1B-XOC1B does not work correctly. Only in the case when the control bits,
COM1B1 and COM1B0 are in the same mode as COM1A1 and COM1A0, respectively, the OC1B-XOC1B output
works correctly.
Problem Fix/Work around
The only workaround is to use same control setting on COM1A[1:0] and COM1B[1:0] control bits, see table 14-
4 in the data sheet. The problem has been fixed for Tiny45 rev D.
8.2.4 Rev A
• Too high power down power consumption
• DebugWIRE looses communication when single stepping into interrupts
• PLL not locking
• EEPROM read from application code does not work in Lock Bit Mode 3
• EEPROM read may fail at low supply voltage / low clock frequency
1. Too high power down power consumption
Three situations will lead to a too high power down power consumption. These are:
– An external clock is selected by fuses, but the I/O PORT is still enabled as an output.
– The EEPROM is read before entering power down.
– VCC is 4.5 volts or higher.
Problem fix / WorkaroundATtiny25/45/85 [DATASHEET] 21
2586QS–AVR–08/2013
– When using external clock, avoid setting the clock pin as Output.
– Do not read the EEPROM if power down power consumption is important.
– Use VCC lower than 4.5 Volts.
2. DebugWIRE looses communication when single stepping into interrupts
When receiving an interrupt during single stepping, debugwire will loose
communication.
Problem fix / Workaround
– When singlestepping, disable interrupts.
– When debugging interrupts, use breakpoints within the interrupt routine, and run into the interrupt.
3. PLL not locking
When at frequencies below 6.0 MHz, the PLL will not lock
Problem fix / Workaround
When using the PLL, run at 6.0 MHz or higher.
4. EEPROM read from application code does not work in Lock Bit Mode 3
When the Memory Lock Bits LB2 and LB1 are programmed to mode 3, EEPROM read does not work from the
application code.
Problem Fix/Work around
Do not set Lock Bit Protection Mode 3 when the application code needs to read from EEPROM.
5. EEPROM read may fail at low supply voltage / low clock frequency
Trying to read EEPROM at low clock frequencies and/or low supply voltage may result in invalid data.
Problem Fix/Workaround
Do not use the EEPROM when clock frequency is below 1MHz and supply voltage is below 2V. If operating frequency
can not be raised above 1MHz then supply voltage should be more than 2V. Similarly, if supply voltage
can not be raised above 2V then operating frequency should be more than 1MHz.
This feature is known to be temperature dependent but it has not been characterized. Guidelines are given for
room temperature, only.ATtiny25/45/85 [DATASHEET] 22
2586QS–AVR–08/2013
8.3 Errata ATtiny85
The revision letter in this section refers to the revision of the ATtiny85 device.
8.3.1 Rev B – C
No known errata.
8.3.2 Rev A
• EEPROM read may fail at low supply voltage / low clock frequency
1. EEPROM read may fail at low supply voltage / low clock frequency
Trying to read EEPROM at low clock frequencies and/or low supply voltage may result in invalid data.
Problem Fix/Workaround
Do not use the EEPROM when clock frequency is below 1MHz and supply voltage is below 2V. If operating frequency
can not be raised above 1MHz then supply voltage should be more than 2V. Similarly, if supply voltage
can not be raised above 2V then operating frequency should be more than 1MHz.
This feature is known to be temperature dependent but it has not been characterised. Guidelines are given for
room temperature, only.ATtiny25/45/85 [DATASHEET] 23
2586QS–AVR–08/2013
9. Datasheet Revision History
9.1 Rev. 2586Q-08/13
9.2 Rev. 2586P-06/13
9.3 Rev. 2586O-02/13
Updated ordering codes on page 11, page 12, and page 13.
9.4 Rev. 2586N-04/11
1. Added:
– Section “Capacitive Touch Sensing” on page 6.
2. Updated:
– Document template.
– Removed “Preliminary” on front page. All devices now final and in production.
– Section “Limitations” on page 36.
– Program example on page 49.
– Section “Overview” on page 122.
– Table 17-4 on page 135.
– Section “Limitations of debugWIRE” on page 140.
– Section “Serial Programming Algorithm” on page 151.
– Table 21-7 on page 166.
– EEPROM errata on pages 19, 19, 20, 21, and 22
– Ordering information on pages 11, 12, and 13.
9.5 Rev. 2586M-07/10
1. Clarified Section 6.4 “Clock Output Buffer” on page 31.
2. Added Ordering Codes -SN and -SNR for ATtiny25 extended temperature.
9.6 Rev. 2586L-06/10
1. Added:
– TSSOP for ATtiny45 in “Features” on page 1, Pinout Figure 1-1 on page 2, Ordering Information in
Section 6.2 “ATtiny45” on page 12, and Packaging Information in Section 7.4 “8X” on page 17
– Table 6-11, “Capacitance of Low-Frequency Crystal Oscillator,” on page 29
– Figure 22-36 on page 191 and Figure 22-37 on page 191, Typical Characteristics plots for Bandgap
Voltage vs. VCC and Temperature
– Extended temperature in Section 6.1 “ATtiny25” on page 11, Ordering Information
1. “Bit 3 – FOC1B: Force Output Compare Match 1B” description in “GTCCR – General Timer/Counter1 Control
Register” on page 90 updated: PB3 in “compare match output pin PB3 (OC1B)” corrected to PB4.
1. Updated description of “EEARH – EEPROM Address Register” and “EEARL – EEPROM Address Register” on page
20.ATtiny25/45/85 [DATASHEET] 24
2586QS–AVR–08/2013
– Tape & reel part numbers in Ordering Information, in Section 6.1 “ATtiny25” on page 11 and Section
6.2 “ATtiny45” on page 12
2. Updated:
– “Features” on page 1, removed Preliminary from ATtiny25
– Section 8.4.2 “Code Example” on page 44
– “PCMSK – Pin Change Mask Register” on page 52, Bit Descriptions
– “TCCR1 – Timer/Counter1 Control Register” on page 89 and “GTCCR – General Timer/Counter1
Control Register” on page 90, COM bit descriptions clarified
– Section 20.3.2 “Calibration Bytes” on page 150, frequencies (8 MHz, 6.4 MHz)
– Table 20-11, “Minimum Wait Delay Before Writing the Next Flash or EEPROM Location,” on page 153,
value for tWD_ERASE
– Table 20-16, “High-voltage Serial Programming Instruction Set for ATtiny25/45/85,” on page 158
– Table 21-1, “DC Characteristics. TA = -40C to +85C,” on page 161, notes adjusted
– Table 21-11, “Serial Programming Characteristics, TA = -40C to +85C, VCC = 1.8 - 5.5V (Unless
Otherwise Noted),” on page 170, added tSLIV
– Bit syntax throughout the datasheet, e.g. from CS02:0 to CS0[2:0].
9.7 Rev. 2586K-01/08
1. Updated Document Template.
2. Added Sections:
– “Data Retention” on page 6
– “Low Level Interrupt” on page 49
– “Device Signature Imprint Table” on page 149
3. Updated Sections:
– “Internal PLL for Fast Peripheral Clock Generation - clkPCK” on page 24
– “System Clock and Clock Options” on page 23
– “Internal PLL in ATtiny15 Compatibility Mode” on page 24
– “Sleep Modes” on page 34
– “Software BOD Disable” on page 35
– “External Interrupts” on page 49
– “Timer/Counter1 in PWM Mode” on page 97
– “USI – Universal Serial Interface” on page 108
– “Temperature Measurement” on page 133
– “Reading Lock, Fuse and Signature Data from Software” on page 143
– “Program And Data Memory Lock Bits” on page 147
– “Fuse Bytes” on page 148
– “Signature Bytes” on page 150
– “Calibration Bytes” on page 150
– “System and Reset Characteristics” on page 165
4. Added Figures:
– “Reset Pin Output Voltage vs. Sink Current (VCC = 3V)” on page 184
– “Reset Pin Output Voltage vs. Sink Current (VCC = 5V)” on page 185
– “Reset Pin Output Voltage vs. Source Current (VCC = 3V)” on page 185ATtiny25/45/85 [DATASHEET] 25
2586QS–AVR–08/2013
– “Reset Pin Output Voltage vs. Source Current (VCC = 5V)” on page 186
5. Updated Figure:
– “Reset Logic” on page 39
6. Updated Tables:
– “Start-up Times for Internal Calibrated RC Oscillator Clock” on page 28
– “Start-up Times for Internal Calibrated RC Oscillator Clock (in ATtiny15 Mode)” on page 28
– “Start-up Times for the 128 kHz Internal Oscillator” on page 28
– “Compare Mode Select in PWM Mode” on page 86
– “Compare Mode Select in PWM Mode” on page 98
– “DC Characteristics. TA = -40C to +85C” on page 161
– “Calibration Accuracy of Internal RC Oscillator” on page 164
– “ADC Characteristics” on page 167
7. Updated Code Example in Section:
– “Write” on page 17
8. Updated Bit Descriptions in:
– “MCUCR – MCU Control Register” on page 37
– “Bits 7:6 – COM0A[1:0]: Compare Match Output A Mode” on page 77
– “Bits 5:4 – COM0B[1:0]: Compare Match Output B Mode” on page 77
– “Bits 2:0 – ADTS[2:0]: ADC Auto Trigger Source” on page 138
– “SPMCSR – Store Program Memory Control and Status Register” on page 145.
9. Updated description of feature “EEPROM read may fail at low supply voltage / low clock frequency” in
Sections:
– “Errata ATtiny25” on page 19
– “Errata ATtiny45” on page 19
– “Errata ATtiny85” on page 22
10. Updated Package Description in Sections:
– “ATtiny25” on page 11
– “ATtiny45” on page 12
– “ATtiny85” on page 13
11. Updated Package Drawing:
– “S8S1” on page 16
12. Updated Order Codes for:
– “ATtiny25” on page 11
9.8 Rev. 2586J-12/06
1. Updated “Low Power Consumption” on page 1.
2. Updated description of instruction length in “Architectural Overview” .
3. Updated Flash size in “In-System Re-programmable Flash Program Memory” on
page 15.
4. Updated cross-references in sections “Atomic Byte Programming” , “Erase” and
“Write” , starting on page 17.
5. Updated “Atomic Byte Programming” on page 17.ATtiny25/45/85 [DATASHEET] 26
2586QS–AVR–08/2013
6. Updated “Internal PLL for Fast Peripheral Clock Generation - clkPCK” on page 24.
7. Replaced single clocking system figure with two: Figure 6-2 and Figure 6-3.
8. Updated Table 6-1 on page 25, Table 6-13 on page 30 and Table 6-6 on page 27.
9. Updated “Calibrated Internal Oscillator” on page 27.
10. Updated Table 6-5 on page 26.
11. Updated “OSCCAL – Oscillator Calibration Register” on page 31.
12. Updated “CLKPR – Clock Prescale Register” on page 32.
13. Updated “Power-down Mode” on page 35.
14. Updated “Bit 0” in “PRR – Power Reduction Register” on page 38.
15. Added footnote to Table 8-3 on page 46.
16. Updated Table 10-5 on page 63.
17. Deleted “Bits 7, 2” in “MCUCR – MCU Control Register” on page 64.
18. Updated and moved section “Timer/Counter0 Prescaler and Clock Sources”, now
located on page 66.
19. Updated “Timer/Counter1 Initialization for Asynchronous Mode” on page 86.
20. Updated bit description in “PLLCSR – PLL Control and Status Register” on page 94
and “PLLCSR – PLL Control and Status Register” on page 103.
21. Added recommended maximum frequency in“Prescaling and Conversion Timing” on
page 125.
22. Updated Figure 17-8 on page 129 .
23. Updated “Temperature Measurement” on page 133.
24. Updated Table 17-3 on page 134.
25. Updated bit R/W descriptions in:
“TIMSK – Timer/Counter Interrupt Mask Register” on page 81,
“TIFR – Timer/Counter Interrupt Flag Register” on page 81,
“TIMSK – Timer/Counter Interrupt Mask Register” on page 92,
“TIFR – Timer/Counter Interrupt Flag Register” on page 93,
“PLLCSR – PLL Control and Status Register” on page 94,
“TIMSK – Timer/Counter Interrupt Mask Register” on page 102,
“TIFR – Timer/Counter Interrupt Flag Register” on page 103,
“PLLCSR – PLL Control and Status Register” on page 103 and
“DIDR0 – Digital Input Disable Register 0” on page 138.
26. Added limitation to “Limitations of debugWIRE” on page 140.
27. Updated “DC Characteristics” on page 161.
28. Updated Table 21-7 on page 166.
29. Updated Figure 21-6 on page 171.
30. Updated Table 21-12 on page 171.
31. Updated Table 22-1 on page 177.
32. Updated Table 22-2 on page 177.
33. Updated Table 22-30, Table 22-31 and Table 22-32, starting on page 188.
34. Updated Table 22-33, Table 22-34 and Table 22-35, starting on page 189.
35. Updated Table 22-39 on page 192.
36. Updated Table 22-46, Table 22-47, Table 22-48 and Table 22-49.ATtiny25/45/85 [DATASHEET] 27
2586QS–AVR–08/2013
9.9 Rev. 2586I-09/06
9.10 Rev. 2586H-06/06
9.11 Rev. 2586G-05/06
9.12 Rev. 2586F-04/06
1. All Characterization data moved to “Electrical Characteristics” on page 161.
2. All Register Descriptions are gathered up in seperate sections in the end of each
chapter.
3. Updated Table 11-3 on page 78, Table 11-5 on page 79, Table 11-6 on page 80 and
Table 20-4 on page 148.
4. Updated “Calibrated Internal Oscillator” on page 27.
5. Updated Note in Table 7-1 on page 34.
6. Updated “System Control and Reset” on page 39.
7. Updated Register Description in “I/O Ports” on page 53.
8. Updated Features in “USI – Universal Serial Interface” on page 108.
9. Updated Code Example in “SPI Master Operation Example” on page 110 and “SPI
Slave Operation Example” on page 111.
10. Updated “Analog Comparator Multiplexed Input” on page 119.
11. Updated Figure 17-1 on page 123.
12. Updated “Signature Bytes” on page 150.
13. Updated “Electrical Characteristics” on page 161.
1. Updated “Calibrated Internal Oscillator” on page 27.
2. Updated Table 6.5.1 on page 31.
3. Added Table 21-2 on page 164.
1. Updated “Internal PLL for Fast Peripheral Clock Generation - clkPCK” on page 24.
2. Updated “Default Clock Source” on page 30.
3. Updated “Low-Frequency Crystal Oscillator” on page 29.
4. Updated “Calibrated Internal Oscillator” on page 27.
5. Updated “Clock Output Buffer” on page 31.
6. Updated “Power Management and Sleep Modes” on page 34.
7. Added “Software BOD Disable” on page 35.
8. Updated Figure 16-1 on page 119.
9. Updated “Bit 6 – ACBG: Analog Comparator Bandgap Select” on page 120.
10. Added note for Table 17-2 on page 125.
11. Updated “Register Summary” on page 7.
1. Updated “Digital Input Enable and Sleep Modes” on page 57.
2. Updated Table 20-16 on page 158.
3. Updated “Ordering Information” on page 11.ATtiny25/45/85 [DATASHEET] 28
2586QS–AVR–08/2013
9.13 Rev. 2586E-03/06
9.14 Rev. 2586D-02/06
9.15 Rev. 2586C-06/05
9.16 Rev. 2586B-05/05
9.17 Rev. 2586A-02/05
Initial revision.
1. Updated Features in “Analog to Digital Converter” on page 122.
2. Updated Operation in “Analog to Digital Converter” on page 122.
3. Updated Table 17-2 on page 133.
4. Updated Table 17-3 on page 134.
5. Updated “Errata” on page 19.
1. Updated Table 6-13 on page 30, Table 6-10 on page 29, Table 6-3 on page 26,
Table 6-9 on page 28, Table 6-5 on page 26, Table 9-1 on page 48,Table 17-4 on
page 135, Table 20-16 on page 158, Table 21-8 on page 167.
2. Updated “Timer/Counter1 in PWM Mode” on page 86.
3. Updated text “Bit 2 – TOV1: Timer/Counter1 Overflow Flag” on page 93.
4. Updated values in “DC Characteristics” on page 161.
5. Updated “Register Summary” on page 7.
6. Updated “Ordering Information” on page 11.
7. Updated Rev B and C in “Errata ATtiny45” on page 19.
8. All references to power-save mode are removed.
9. Updated Register Adresses.
1. Updated “Features” on page 1.
2. Updated Figure 1-1 on page 2.
3. Updated Code Examples on page 18 and page 19.
4. Moved “Temperature Measurement” to Section 17.12 page 133.
5. Updated “Register Summary” on page 7.
6. Updated “Ordering Information” on page 11.
1. CLKI added, instances of EEMWE/EEWE renamed EEMPE/EEPE, removed some
TBD.
Removed “Preliminary Description” from “Temperature Measurement” on page 133.
2. Updated “Features” on page 1.
3. Updated Figure 1-1 on page 2 and Figure 8-1 on page 39.
4. Updated Table 7-2 on page 38, Table 10-4 on page 63, Table 10-5 on page 63
5. Updated “Serial Programming Instruction set” on page 153.
6. Updated SPH register in “Instruction Set Summary” on page 9.
7. Updated “DC Characteristics” on page 161.
8. Updated “Ordering Information” on page 11.
9. Updated “Errata” on page 19.ATtiny25/45/85 [DATASHEET] 29
2586QS–AVR–08/2013Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 2586QS–AVR–08/2013
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, AVR®, tinyAVR® and others are registered trademarks or trademarks of Atmel
Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
© 2008 Microchip Technology Inc. DS39631E
PIC18F2420/2520/4420/4520
Data Sheet
28/40/44-Pin Enhanced Flash
Microcontrollers with 10-Bit A/D
and nanoWatt TechnologyDS39631E-page ii © 2008 Microchip Technology Inc.
Information contained in this publication regarding device
applications and the like is provided only for your convenience
and may be superseded by updates. It is your responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro,
PICSTART, rfPIC, SmartShunt and UNI/O are registered
trademarks of Microchip Technology Incorporated in the
U.S.A. and other countries.
FilterLab, Linear Active Thermistor, MXDEV, MXLAB,
SEEVAL, SmartSensor and The Embedded Control Solutions
Company are registered trademarks of Microchip Technology
Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN,
ECONOMONITOR, FanSense, In-Circuit Serial
Programming, ICSP, ICEPIC, Mindi, MiWi, MPASM, MPLAB
Certified logo, MPLIB, MPLINK, mTouch, PICkit, PICDEM,
PICDEM.net, PICtail, PIC32 logo, PowerCal, PowerInfo,
PowerMate, PowerTool, REAL ICE, rfLAB, Select Mode, Total
Endurance, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2008, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
Printed on recycled paper.
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona; Gresham, Oregon and design centers in California
and India. The Company’s quality system processes and procedures
are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping
devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchip’s quality system for the design
and manufacture of development systems is ISO 9001:2000 certified.© 2008 Microchip Technology Inc. DS39631E-page 1
PIC18F2420/2520/4420/4520
Power Management Features:
• Run: CPU on, Peripherals on
• Idle: CPU off, Peripherals on
• Sleep: CPU off, Peripherals off
• Ultra Low 50nA Input Leakage
• Run mode Currents Down to 11 μA Typical
• Idle mode Currents Down to 2.5 μA Typical
• Sleep mode Current Down to 100 nA Typical
• Timer1 Oscillator: 900 nA, 32 kHz, 2V
• Watchdog Timer: 1.4 μA, 2V Typical
• Two-Speed Oscillator Start-up
Flexible Oscillator Structure:
• Four Crystal modes, up to 40 MHz
• 4x Phase Lock Loop (PLL) – Available for Crystal
and Internal Oscillators
• Two External RC modes, up to 4 MHz
• Two External Clock modes, up to 40 MHz
• Internal Oscillator Block:
- Fast wake from Sleep and Idle, 1 μs typical
- 8 use-selectable frequencies, from 31 kHz to
8 MHz
- Provides a complete range of clock speeds
from 31 kHz to 32 MHz when used with PLL
- User-tunable to compensate for frequency drift
• Secondary Oscillator using Timer1 @ 32 kHz
• Fail-Safe Clock Monitor:
- Allows for safe shutdown if peripheral clock stops
Peripheral Highlights:
• High-Current Sink/Source 25 mA/25 mA
• Three Programmable External Interrupts
• Four Input Change Interrupts
• Up to 2 Capture/Compare/PWM (CCP) modules,
one with Auto-Shutdown (28-pin devices)
• Enhanced Capture/Compare/PWM (ECCP)
module (40/44-pin devices only):
- One, two or four PWM outputs
- Selectable polarity
- Programmable dead time
- Auto-shutdown and auto-restart
Peripheral Highlights (Continued):
• Master Synchronous Serial Port (MSSP) module
Supporting 3-Wire SPI (all 4 modes) and I2C™
Master and Slave modes
• Enhanced Addressable USART module:
- Supports RS-485, RS-232 and LIN/J2602
- RS-232 operation using internal oscillator
block (no external crystal required)
- Auto-wake-up on Start bit
- Auto-Baud Detect
• 10-Bit, up to 13-Channel Analog-to-Digital (A/D)
Converter module:
- Auto-acquisition capability
- Conversion available during Sleep
• Dual Analog Comparators with Input Multiplexing
• Programmable 16-Level High/Low-Voltage
Detection (HLVD) module:
- Supports interrupt on High/Low-Voltage Detection
Special Microcontroller Features:
• C Compiler Optimized Architecture:
- Optional extended instruction set designed to
optimize re-entrant code
• 100,000 Erase/Write Cycle Enhanced Flash
Program Memory Typical
• 1,000,000 Erase/Write Cycle Data EEPROM
Memory Typical
• Flash/Data EEPROM Retention: 100 Years Typical
• Self-Programmable under Software Control
• Priority Levels for Interrupts
• 8 x 8 Single-Cycle Hardware Multiplier
• Extended Watchdog Timer (WDT):
- Programmable period from 4 ms to 131s
• Single-Supply 5V In-Circuit Serial
Programming™ (ICSP™) via Two Pins
• In-Circuit Debug (ICD) via Two Pins
• Wide Operating Voltage Range: 2.0V to 5.5V
• Programmable Brown-out Reset (BOR) with
Software Enable Option
-
Device
Program Memory Data Memory
I/O 10-Bit
A/D (ch)
CCP/
ECCP
(PWM)
MSSP
EUSART
Comp. Timers
8/16-Bit Flash
(bytes)
# Single-Word
Instructions
SRAM
(bytes)
EEPROM
(bytes) SPI Master
I
2C™
PIC18F2420 16K 8192 768 256 25 10 2/0 Y Y 1 2 1/3
PIC18F2520 32K 16384 1536 256 25 10 2/0 Y Y 1 2 1/3
PIC18F4420 16K 8192 768 256 36 13 1/1 Y Y 1 2 1/3
PIC18F4520 32K 16384 1536 256 36 13 1/1 Y Y 1 2 1/3
28/40/44-Pin Enhanced Flash Microcontrollers with
10-Bit A/D and nanoWatt TechnologyPIC18F2420/2520/4420/4520
DS39631E-page 2 © 2008 Microchip Technology Inc.
Pin Diagrams
PIC18F2520
10
11
2
3
4
5
6
1
8
7
9
12
13
14 15
16
17
18
19
20
23
24
25
26
27
28
22
21
MCLR/VPP/RE3
RA0/AN0
RA1/AN1
RA2/AN2/VREF-/CVREF
RA3/AN3/VREF+
RA4/T0CKI/C1OUT
RA5/AN4/SS/HLVDIN/C2OUT
VSS
OSC1/CLKI/RA7
OSC2/CLKO/RA6
RC0/T1OSO/T13CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1
RC3/SCK/SCL
RB7/KBI3/PGD
RB6//KBI2/PGC
RB5/KBI1/PGM
RB4/KBI0/AN11
RB3/AN9/CCP2(1)
RB2/INT2/AN8
RB1/INT1/AN10
RB0/INT0/FLT0/AN12
VDD
VSS
RC7/RX/DT
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
28-Pin SPDIP, SOIC
PIC18F2420
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
10 11
2
3
6
1
18
19
20
21
22
12 13 14
15
8
7
16
17
2827 2625 2423
9
PIC18F2420 RC0/T1OSO/T13CKI
5
4
RB7/KBI3/PGD
RB6/KBI2/PGC
RB5/KBI1/PGM
RB4KBI0/AN11
RB3/AN9/CCP2(1)
RB2/INT2/AN8
RB1/INT1/AN10
RB0/INT0/FLT0/AN12
VDD
VSS
RC7/RX/DT
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
MCLR/VPP/RE3
RA1/AN1
RA0/AN0
RA2/AN2/VREF-/CVREF
RA3/AN3/VREF+
RA4/T0CKI/C1OUT
RA5/AN4/SS/HLVDIN/C2OUT
VSS
OSC1/CLKI/RA7
OSC2/CLKO/RA6
RC1/T1OSI/CCP2(1)
RC2/CCP1
RC3/SCK/SCL
PIC18F2520
28-Pin QFN
RB7/KBI3/PGD
RB6/KBI2/PGC
RB5/KBI1/PGM
RB4/KBI0/AN11
RB3/AN9/CCP2(1)
RB2/INT2/AN8
RB1/INT1/AN10
RB0/INT0/FLT0/AN12
VDD
VSS
RD7/PSP7/P1D
RD6/PSP6/P1C
RD5/PSP5/P1B
RD4/PSP4
RC7/RX/DT
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
MCLR/VPP/RE3
RA0/AN0
RA1/AN1
RA2/AN2/VREF-/CVREF
RA3/AN3/VREF+
RA4/T0CKI/C1OUT
RA5/AN4/SS/HLVDIN/C2OUT
RE0/RD/AN5
RE1/WR/AN6
RE2/CS/AN7
VDD
VSS
OSC1/CLKI/RA7
OSC2/CLKO/RA6
RC0/T1OSO/T13CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1/P1A
RC3/SCK/SCL
RD0/PSP0
RD1/PSP1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
40
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
PIC18F4520
40-Pin PDIP
PIC18F4420© 2008 Microchip Technology Inc. DS39631E-page 3
PIC18F2420/2520/4420/4520
Pin Diagrams (Cont.’d)
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
10
11
2
3
4
5
6
1
12
13
14
15
18
19
20
21
22
38
8
7
44
43
42
41
40
39
16
17
29
30
31
32
33
23
24
25
26
27
28
36
35
34
9
PIC18F442037
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA0/AN0
RA1/AN1
MCLR/VPP/RE3
RB3/AN9/CCP2(1)
RB4/KBI0/AN11
RB5/KBI1/PGM
RB6/KBI2/PGC
RB7/KBI3/PGD
NC
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1/P1A
RC1/T1OSI/CCP2(1)
RC0/T1OSO/T13CKI
OSC2/CLKO/RA6
OSC1/CLKI/RA7
VSS
VSS
VDD
VDD
RE2/CS/AN7
RE1/WR/AN6
RE0/RD/AN5
RA5/AN4/SS/HLVDIN/C2OUT
RA4/T0CKI/C1OUT
RC7/RX/DT
RD4/PSP4
RD5/PSP5/P1B
RD6/PSP6/P1C
RD7/PSP7/P1D
VSS
VDD
VDD
RB0/INT0/FLT0/AN12
RB1/INT1/AN10
RB2/INT2/AN8
44-pin QFN
PIC18F4520
10
11
2
3
4
5
6
1
12
13
14
15
18
19
20
21
22
38
8
7
44
43
42
41
40
39
16
17
29
30
31
32
33
23
24
25
26
27
28
36
35
34
9
PIC18F442037
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA0/AN0
RA1/AN1
MCLR/VPP/RE3
NC
RB4/KBI0/AN11
RB5/KBI1/PGM
RB6/KBI2/PGC
RB7/KBI3/PGD
NC
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1/P1A
RC1/T1OSI/CCP2(1)
NC
NC
RC0/T1OSO/T13CKI
OSC2/CLKO/RA6
OSC1/CLKI/RA7
VSS
VDD
RE2/CS/AN7
RE1/WR/AN6
RE0/RD/AN5
RA5/AN4/SS/HLVDIN/C2OUT
RA4/T0CKI/C1OUT
RC7/RX/DT
RD4/PSP4
RD5/PSP5/P1B
RD6/PSP6/P1C
RD7/PSP7/P1D
VSS
VDD
RB0/INT0/FLT0/AN12
RB1/INT1/AN10
RB2/INT2/AN8
RB3/AN9/CCP2(1)
44-pin TQFP
PIC18F4520PIC18F2420/2520/4420/4520
DS39631E-page 4 © 2008 Microchip Technology Inc.
Table of Contents
1.0 Device Overview .......................................................................................................................................................................... 7
2.0 Oscillator Configurations ............................................................................................................................................................ 23
3.0 Power-Managed Modes ............................................................................................................................................................. 33
4.0 Reset .......................................................................................................................................................................................... 41
5.0 Memory Organization ................................................................................................................................................................. 53
6.0 Flash Program Memory.............................................................................................................................................................. 73
7.0 Data EEPROM Memory ............................................................................................................................................................. 83
8.0 8 x 8 Hardware Multiplier............................................................................................................................................................ 89
9.0 Interrupts .................................................................................................................................................................................... 91
10.0 I/O Ports ................................................................................................................................................................................... 105
11.0 Timer0 Module ......................................................................................................................................................................... 123
12.0 Timer1 Module ......................................................................................................................................................................... 127
13.0 Timer2 Module ......................................................................................................................................................................... 133
14.0 Timer3 Module ......................................................................................................................................................................... 135
15.0 Capture/Compare/PWM (CCP) Modules ................................................................................................................................. 139
16.0 Enhanced Capture/Compare/PWM (ECCP) Module................................................................................................................ 147
17.0 Master Synchronous Serial Port (MSSP) Module .................................................................................................................... 161
18.0 Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) ............................................................... 201
19.0 10-Bit Analog-to-Digital Converter (A/D) Module ..................................................................................................................... 223
20.0 Comparator Module.................................................................................................................................................................. 233
21.0 Comparator Voltage Reference Module................................................................................................................................... 239
22.0 High/Low-Voltage Detect (HLVD)............................................................................................................................................. 243
23.0 Special Features of the CPU.................................................................................................................................................... 249
24.0 Instruction Set Summary .......................................................................................................................................................... 267
25.0 Development Support............................................................................................................................................................... 317
26.0 Electrical Characteristics .......................................................................................................................................................... 321
27.0 DC and AC Characteristics Graphs and Tables....................................................................................................................... 361
28.0 Packaging Information.............................................................................................................................................................. 383
Appendix A: Revision History............................................................................................................................................................. 395
Appendix B: Device Differences......................................................................................................................................................... 395
Appendix C: Migration from Mid-Range to Enhanced Devices .......................................................................................................... 396
Appendix D: Migration from High-End to Enhanced Devices............................................................................................................. 396
Index .................................................................................................................................................................................................. 397
The Microchip Web Site ..................................................................................................................................................................... 407
Customer Change Notification Service .............................................................................................................................................. 407
Customer Support.............................................................................................................................................................................. 407
Reader Response .............................................................................................................................................................................. 408
PIC18F2420/2520/4420/4520 Product Identification System ............................................................................................................ 409© 2008 Microchip Technology Inc. DS39631E-page 5
PIC18F2420/2520/4420/4520
TO OUR VALUED CUSTOMERS
It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip
products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined and
enhanced as new volumes and updates are introduced.
If you have any questions or comments regarding this publication, please contact the Marketing Communications Department via
E-mail at docerrors@microchip.com or fax the Reader Response Form in the back of this data sheet to (480) 792-4150. We
welcome your feedback.
Most Current Data Sheet
To obtain the most up-to-date version of this data sheet, please register at our Worldwide Web site at:
http://www.microchip.com
You can determine the version of a data sheet by examining its literature number found on the bottom outside corner of any page.
The last character of the literature number is the version number, (e.g., DS30000A is version A of document DS30000).
Errata
An errata sheet, describing minor operational differences from the data sheet and recommended workarounds, may exist for current
devices. As device/documentation issues become known to us, we will publish an errata sheet. The errata will specify the revision
of silicon and revision of document to which it applies.
To determine if an errata sheet exists for a particular device, please check with one of the following:
• Microchip’s Worldwide Web site; http://www.microchip.com
• Your local Microchip sales office (see last page)
When contacting a sales office, please specify which device, revision of silicon and data sheet (include literature number) you are
using.
Customer Notification System
Register on our web site at www.microchip.com to receive the most current information on all of our products.PIC18F2420/2520/4420/4520
DS39631E-page 6 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 7
PIC18F2420/2520/4420/4520
1.0 DEVICE OVERVIEW
This document contains device-specific information for
the following devices:
This family offers the advantages of all PIC18
microcontrollers – namely, high computational performance
at an economical price – with the addition of
high-endurance, Enhanced Flash program memory.
On top of these features, the PIC18F2420/2520/4420/
4520 family introduces design enhancements that
make these microcontrollers a logical choice for many
high-performance, power sensitive applications.
1.1 New Core Features
1.1.1 nanoWatt TECHNOLOGY
All of the devices in the PIC18F2420/2520/4420/4520
family incorporate a range of features that can significantly
reduce power consumption during operation.
Key items include:
• Alternate Run Modes: By clocking the controller
from the Timer1 source or the internal oscillator
block, power consumption during code execution
can be reduced by as much as 90%.
• Multiple Idle Modes: The controller can also run
with its CPU core disabled but the peripherals still
active. In these states, power consumption can be
reduced even further, to as little as 4% of normal
operation requirements.
• On-the-Fly Mode Switching: The powermanaged
modes are invoked by user code during
operation, allowing the user to incorporate
power-saving ideas into their application’s
software design.
• Low Consumption in Key Modules: The
power requirements for both Timer1 and the
Watchdog Timer are minimized. See
Section 26.0 “Electrical Characteristics”
for values.
1.1.2 MULTIPLE OSCILLATOR OPTIONS
AND FEATURES
All of the devices in the PIC18F2420/2520/4420/4520
family offer ten different oscillator options, allowing
users a wide range of choices in developing application
hardware. These include:
• Four Crystal modes, using crystals or ceramic
resonators
• Two External Clock modes, offering the option of
using two pins (oscillator input and a divide-by-4
clock output) or one pin (oscillator input, with the
second pin reassigned as general I/O)
• Two External RC Oscillator modes with the same
pin options as the External Clock modes
• An internal oscillator block which provides an
8 MHz clock and an INTRC source
(approximately 31 kHz), as well as a range of
6 user-selectable clock frequencies, between
125 kHz to 4 MHz, for a total of 8 clock
frequencies. This option frees the two oscillator
pins for use as additional general purpose I/O.
• A Phase Lock Loop (PLL) frequency multiplier,
available to both the High-Speed Crystal and Internal
Oscillator modes, which allows clock speeds of
up to 40 MHz. Used with the internal oscillator, the
PLL gives users a complete selection of clock
speeds, from 31 kHz to 32 MHz – all without using
an external crystal or clock circuit.
Besides its availability as a clock source, the internal
oscillator block provides a stable reference source that
gives the family additional features for robust
operation:
• Fail-Safe Clock Monitor: This option constantly
monitors the main clock source against a reference
signal provided by the internal oscillator. If a
clock failure occurs, the controller is switched to
the internal oscillator block, allowing for continued
low-speed operation or a safe application
shutdown.
• Two-Speed Start-up: This option allows the
internal oscillator to serve as the clock source
from Power-on Reset, or wake-up from Sleep
mode, until the primary clock source is available.
• PIC18F2420 • PIC18LF2420
• PIC18F2520 • PIC18LF2520
• PIC18F4420 • PIC18LF4420
• PIC18F4520 • PIC18LF4520PIC18F2420/2520/4420/4520
DS39631E-page 8 © 2008 Microchip Technology Inc.
1.2 Other Special Features
• Memory Endurance: The Enhanced Flash cells
for both program memory and data EEPROM are
rated to last for many thousands of erase/write
cycles – up to 100,000 for program memory and
1,000,000 for EEPROM. Data retention without
refresh is conservatively estimated to be greater
than 40 years.
• Self-Programmability: These devices can write
to their own program memory spaces under
internal software control. By using a bootloader
routine located in the protected Boot Block at the
top of program memory, it becomes possible to
create an application that can update itself in the
field.
• Extended Instruction Set: The PIC18F2420/
2520/4420/4520 family introduces an optional
extension to the PIC18 instruction set, which adds
8 new instructions and an Indexed Addressing
mode. This extension, enabled as a device configuration
option, has been specifically designed
to optimize re-entrant application code originally
developed in high-level languages, such as C.
• Enhanced CCP Module: In PWM mode, this
module provides 1, 2 or 4 modulated outputs for
controlling half-bridge and full-bridge drivers.
Other features include auto-shutdown, for disabling
PWM outputs on interrupt, or other select
conditions, and auto-restart to reactivate outputs
once the condition has cleared.
• Enhanced Addressable USART: This serial
communication module is capable of standard
RS-232 operation and provides support for the LIN
bus protocol. Other enhancements include
automatic baud rate detection and a 16-bit Baud
Rate Generator for improved resolution. When the
microcontroller is using the internal oscillator
block, the EUSART provides stable operation for
applications that talk to the outside world without
using an external crystal (or its accompanying
power requirement).
• 10-Bit A/D Converter: This module incorporates
programmable acquisition time, allowing for a
channel to be selected and a conversion to be
initiated without waiting for a sampling period and
thus, reducing code overhead.
• Extended Watchdog Timer (WDT): This
enhanced version incorporates a 16-bit prescaler,
allowing an extended time-out range that is stable
across operating voltage and temperature. See
Section 26.0 “Electrical Characteristics” for
time-out periods.
1.3 Details on Individual Family
Members
Devices in the PIC18F2420/2520/4420/4520 family are
available in 28-pin and 40/44-pin packages. Block
diagrams for the two groups are shown in Figure 1-1
and Figure 1-2.
The devices are differentiated from each other in five
ways:
1. Flash program memory (16 Kbytes for
PIC18F2420/4420 devices and 32 Kbytes for
PIC18F2520/4520 devices).
2. A/D channels (10 for 28-pin devices, 13 for
40/44-pin devices).
3. I/O ports (3 bidirectional ports on 28-pin devices,
5 bidirectional ports on 40/44-pin devices).
4. CCP and Enhanced CCP implementation
(28-pin devices have 2 standard CCP
modules, 40/44-pin devices have one standard
CCP module and one ECCP module).
5. Parallel Slave Port (present only on 40/44-pin
devices).
All other features for devices in this family are identical.
These are summarized in Table 1-1.
The pinouts for all devices are listed in Table 1-2 and
Table 1-3.
Like all Microchip PIC18 devices, members of the
PIC18F2420/2520/4420/4520 family are available as
both standard and low-voltage devices. Standard
devices with Enhanced Flash memory, designated with
an “F” in the part number (such as PIC18F2420),
accommodate an operating VDD range of 4.2V to 5.5V.
Low-voltage parts, designated by “LF” (such as
PIC18LF2420), function over an extended VDD range
of 2.0V to 5.5V. © 2008 Microchip Technology Inc. DS39631E-page 9
PIC18F2420/2520/4420/4520
TABLE 1-1: DEVICE FEATURES
Features PIC18F2420 PIC18F2520 PIC18F4420 PIC18F4520
Operating Frequency DC – 40 MHz DC – 40 MHz DC – 40 MHz DC – 40 MHz
Program Memory (Bytes) 16384 32768 16384 32768
Program Memory
(Instructions)
8192 16384 8192 16384
Data Memory (Bytes) 768 1536 768 1536
Data EEPROM Memory (Bytes) 256 256 256 256
Interrupt Sources 19 19 20 20
I/O Ports Ports A, B, C, (E) Ports A, B, C, (E) Ports A, B, C, D, E Ports A, B, C, D, E
Timers 4 4 4 4
Capture/Compare/PWM Modules 2 2 1 1
Enhanced
Capture/Compare/PWM Modules
0011
Serial Communications MSSP,
Enhanced USART
MSSP,
Enhanced USART
MSSP,
Enhanced USART
MSSP,
Enhanced USART
Parallel Communications (PSP) No No Yes Yes
10-Bit Analog-to-Digital Module 10 Input Channels 10 Input Channels 13 Input Channels 13 Input Channels
Resets (and Delays) POR, BOR,
RESET Instruction,
Stack Full, Stack
Underflow (PWRT, OST),
MCLR (optional), WDT
POR, BOR,
RESET Instruction,
Stack Full, Stack
Underflow (PWRT, OST),
MCLR (optional), WDT
POR, BOR,
RESET Instruction,
Stack Full, Stack
Underflow (PWRT, OST),
MCLR (optional), WDT
POR, BOR,
RESET Instruction,
Stack Full, Stack
Underflow (PWRT, OST),
MCLR (optional), WDT
Programmable
High/Low-Voltage Detect
Yes Yes Yes Yes
Programmable Brown-out Reset Yes Yes Yes Yes
Instruction Set 75 Instructions;
83 with Extended
Instruction Set Enabled
75 Instructions;
83 with Extended
Instruction Set Enabled
75 Instructions;
83 with Extended
Instruction Set Enabled
75 Instructions;
83 with Extended
Instruction Set Enabled
Packages 28-Pin SPDIP
28-Pin SOIC
28-Pin QFN
28-Pin SPDIP
28-Pin SOIC
28-Pin QFN
40-Pin PDIP
44-Pin QFN
44-Pin TQFP
40-Pin PDIP
44-Pin QFN
44-Pin TQFPPIC18F2420/2520/4420/4520
DS39631E-page 10 © 2008 Microchip Technology Inc.
FIGURE 1-1: PIC18F2420/2520 (28-PIN) BLOCK DIAGRAM
Instruction
Decode and
Control
PORTA
PORTB
PORTC
RA4/T0CKI/C1OUT
RA5/AN4/SS/HLVDIN/C2OUT
RB0/INT0/FLT0/AN12
RC0/T1OSO/T13CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1
RC3/SCK/SCL
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
RC7/RX/DT
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA1/AN1
RA0/AN0
RB1/INT1/AN10
Data Latch
Data Memory
( 3.9 Kbytes )
Address Latch
Data Address<12>
12
BSR Access FSR0
FSR1
FSR2
inc/dec
logic
Address
4 12 4
PCH PCL
PCLATH
8
31-Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
8
BITOP
8 8
ALU<8>
Address Latch
Program Memory
(16/32 Kbytes)
Data Latch
20
8
8
Table Pointer<21>
inc/dec logic
21
8
Data Bus<8>
Table Latch
8
IR
12
3
ROM Latch
RB2/INT2/AN8
RB3/AN9/CCP2(1)
PCLATU
PCU
OSC2/CLKO(3)/RA6
Note 1: CCP2 is multiplexed with RC1 when Configuration bit, CCP2MX, is set, or RB3 when CCP2MX is not set.
2: RE3 is only available when MCLR functionality is disabled.
3: OSC1/CLKI and OSC2/CLKO are only available in select oscillator modes and when these pins are not being used as digital I/O.
Refer to Section 2.0 “Oscillator Configurations” for additional information.
RB4/KBI0/AN11
RB5/KBI1/PGM
RB6/KBI2/PGC
RB7/KBI3/PGD
Comparator MSSP EUSART 10-Bit
ADC
Timer0 Timer1 Timer2 Timer3
CCP2
HLVD
CCP1
BOR Data
EEPROM
W
Instruction Bus <16>
STKPTR Bank
8
State Machine
Control Signals
Decode
8
8 Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
OSC1(3)
OSC2(3)
VDD,
Brown-out
Reset
Internal
Oscillator
Fail-Safe
Clock Monitor
Precision
Reference
Band Gap
VSS
MCLR(2)
Block
INTRC
Oscillator
8 MHz
Oscillator
Single-Supply
Programming
In-Circuit
Debugger
T1OSO
OSC1/CLKI(3)/RA7
T1OSI
PORTE
MCLR/VPP/RE3(2)© 2008 Microchip Technology Inc. DS39631E-page 11
PIC18F2420/2520/4420/4520
FIGURE 1-2: PIC18F4420/4520 (40/44-PIN) BLOCK DIAGRAM
Instruction
Decode and
Control
Data Latch
Data Memory
( 3.9 Kbytes )
Address Latch
Data Address<12>
12
BSR Access FSR0
FSR1
FSR2
inc/dec
logic
Address
4 12 4
PCH PCL
PCLATH
8
31-Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
8
BITOP
8 8
ALU<8>
Address Latch
Program Memory
(16/32 Kbytes)
Data Latch
20
8
8
Table Pointer<21>
inc/dec logic
21
8
Data Bus<8>
Table Latch
8
IR
12
3
ROM Latch
PORTD
RD0/PSP0
PCLATU
PCU
PORTE
MCLR/VPP/RE3(2)
RE2/CS/AN7
RE0/RD/AN5
RE1/WR/AN6
Note 1: CCP2 is multiplexed with RC1 when Configuration bit, CCP2MX, is set, or RB3 when CCP2MX is not set.
2: RE3 is only available when MCLR functionality is disabled.
3: OSC1/CLKI and OSC2/CLKO are only available in select oscillator modes and when these pins are not being used as digital I/O.
Refer to Section 2.0 “Oscillator Configurations” for additional information.
:RD4/PSP4
Comparator MSSP EUSART 10-Bit
ADC
Timer0 Timer1 Timer2 Timer3
CCP2
HLVD
ECCP1
BOR Data
EEPROM
W
Instruction Bus <16>
STKPTR Bank
8
State Machine
Control Signals
Decode
8
8 Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
OSC1(3)
OSC2(3)
VDD,
Brown-out
Reset
Internal
Oscillator
Fail-Safe
Clock Monitor
Precision
Reference
Band Gap
VSS
MCLR(2)
Block
INTRC
Oscillator
8 MHz
Oscillator
Single-Supply
Programming
In-Circuit
Debugger
T1OSI
T1OSO
RD5/PSP5/P1B
RD6/PSP6/P1C
RD7/PSP7/P1D
PORTA
PORTB
PORTC
RA4/T0CKI/C1OUT
RA5/AN4/SS/HLVDIN/C2OUT
RB0/INT0/FLT0/AN12
RC0/T1OSO/T13CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1/P1A
RC3/SCK/SCL
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
RC7/RX/DT
RA3/AN3/VREF+
RA2/AN2/VREF-/CVREF
RA1/AN1
RA0/AN0
RB1/INT1/AN10
RB2/INT2/AN8
RB3/AN9/CCP2(1)
OSC2/CLKO(3)/RA6
RB4/KBI0/AN11
RB5/KBI1/PGM
RB6/KBI2/PGC
RB7/KBI3/PGD
OSC1/CLKI(3)/RA7PIC18F2420/2520/4420/4520
DS39631E-page 12 © 2008 Microchip Technology Inc.
TABLE 1-2: PIC18F2420/2520 PINOUT I/O DESCRIPTIONS
Pin Name
Pin Number
Pin
Type
Buffer
Type SPDIP, Description
SOIC QFN
MCLR/VPP/RE3
MCLR
VPP
RE3
1 26
I
P
I
ST
ST
Master Clear (input) or programming voltage (input).
Master Clear (Reset) input. This pin is an active-low
Reset to the device.
Programming voltage input.
Digital input.
OSC1/CLKI/RA7
OSC1
CLKI
RA7
9 6
I
I
I/O
ST
CMOS
TTL
Oscillator crystal or external clock input.
Oscillator crystal input or external clock source input.
ST buffer when configured in RC mode; CMOS otherwise.
External clock source input. Always associated with pin
function, OSC1. (See related OSC1/CLKI, OSC2/CLKO
pins.)
General purpose I/O pin.
OSC2/CLKO/RA6
OSC2
CLKO
RA6
10 7
O
O
I/O
—
—
TTL
Oscillator crystal or clock output.
Oscillator crystal output. Connects to crystal or
resonator in Crystal Oscillator mode.
In RC mode, OSC2 pin outputs CLKO which has 1/4 the
frequency of OSC1 and denotes the instruction cycle rate.
General purpose I/O pin.
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. © 2008 Microchip Technology Inc. DS39631E-page 13
PIC18F2420/2520/4420/4520
PORTA is a bidirectional I/O port.
RA0/AN0
RA0
AN0
2 27
I/O
I
TTL
Analog
Digital I/O.
Analog input 0.
RA1/AN1
RA1
AN1
3 28
I/O
I
TTL
Analog
Digital I/O.
Analog input 1.
RA2/AN2/VREF-/CVREF
RA2
AN2
VREFCVREF
4 1
I/O
I
I
O
TTL
Analog
Analog
Analog
Digital I/O.
Analog input 2.
A/D reference voltage (low) input.
Comparator reference voltage output.
RA3/AN3/VREF+
RA3
AN3
VREF+
5 2
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 3.
A/D reference voltage (high) input.
RA4/T0CKI/C1OUT
RA4
T0CKI
C1OUT
6 3
I/O
I
O
ST
ST
—
Digital I/O.
Timer0 external clock input.
Comparator 1 output.
RA5/AN4/SS/HLVDIN/
C2OUT
RA5
AN4
SS
HLVDIN
C2OUT
7 4
I/O
I
I
I
O
TTL
Analog
TTL
Analog
—
Digital I/O.
Analog input 4.
SPI slave select input.
High/Low-Voltage Detect input.
Comparator 2 output.
RA6 See the OSC2/CLKO/RA6 pin.
RA7 See the OSC1/CLKI/RA7 pin.
TABLE 1-2: PIC18F2420/2520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number
Pin
Type
Buffer
Type SPDIP, Description
SOIC QFN
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. PIC18F2420/2520/4420/4520
DS39631E-page 14 © 2008 Microchip Technology Inc.
PORTB is a bidirectional I/O port. PORTB can be software
programmed for internal weak pull-ups on all inputs.
RB0/INT0/FLT0/AN12
RB0
INT0
FLT0
AN12
21 18
I/O
I
I
I
TTL
ST
ST
Analog
Digital I/O.
External interrupt 0.
PWM Fault input for CCP1.
Analog input 12.
RB1/INT1/AN10
RB1
INT1
AN10
22 19
I/O
I
I
TTL
ST
Analog
Digital I/O.
External interrupt 1.
Analog input 10.
RB2/INT2/AN8
RB2
INT2
AN8
23 20
I/O
I
I
TTL
ST
Analog
Digital I/O.
External interrupt 2.
Analog input 8.
RB3/AN9/CCP2
RB3
AN9
CCP2(1)
24 21
I/O
I
I/O
TTL
Analog
ST
Digital I/O.
Analog input 9.
Capture 2 input/Compare 2 output/PWM2 output.
RB4/KBI0/AN11
RB4
KBI0
AN11
25 22
I/O
I
I
TTL
TTL
Analog
Digital I/O.
Interrupt-on-change pin.
Analog input 11.
RB5/KBI1/PGM
RB5
KBI1
PGM
26 23
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
Low-Voltage ICSP™ Programming enable pin.
RB6/KBI2/PGC
RB6
KBI2
PGC
27 24
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming clock pin.
RB7/KBI3/PGD
RB7
KBI3
PGD
28 25
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming data pin.
TABLE 1-2: PIC18F2420/2520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number
Pin
Type
Buffer
Type SPDIP, Description
SOIC QFN
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. © 2008 Microchip Technology Inc. DS39631E-page 15
PIC18F2420/2520/4420/4520
PORTC is a bidirectional I/O port.
RC0/T1OSO/T13CKI
RC0
T1OSO
T13CKI
11 8
I/O
O
I
ST
—
ST
Digital I/O.
Timer1 oscillator output.
Timer1/Timer3 external clock input.
RC1/T1OSI/CCP2
RC1
T1OSI
CCP2(2)
12 9
I/O
I
I/O
ST
Analog
ST
Digital I/O.
Timer1 oscillator input.
Capture 2 input/Compare 2 output/PWM2 output.
RC2/CCP1
RC2
CCP1
13 10
I/O
I/O
ST
ST
Digital I/O.
Capture 1 input/Compare 1 output/PWM1 output.
RC3/SCK/SCL
RC3
SCK
SCL
14 11
I/O
I/O
I/O
ST
ST
ST
Digital I/O.
Synchronous serial clock input/output for SPI mode.
Synchronous serial clock input/output for I2C™ mode.
RC4/SDI/SDA
RC4
SDI
SDA
15 12
I/O
I
I/O
ST
ST
ST
Digital I/O.
SPI data in.
I
2C data I/O.
RC5/SDO
RC5
SDO
16 13
I/O
O
ST
—
Digital I/O.
SPI data out.
RC6/TX/CK
RC6
TX
CK
17 14
I/O
O
I/O
ST
—
ST
Digital I/O.
EUSART asynchronous transmit.
EUSART synchronous clock (see related RX/DT).
RC7/RX/DT
RC7
RX
DT
18 15
I/O
I
I/O
ST
ST
ST
Digital I/O.
EUSART asynchronous receive.
EUSART synchronous data (see related TX/CK).
RE3 — — — — See MCLR/VPP/RE3 pin.
VSS 8, 19 5, 16 P — Ground reference for logic and I/O pins.
VDD 20 17 P — Positive supply for logic and I/O pins.
TABLE 1-2: PIC18F2420/2520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number
Pin
Type
Buffer
Type SPDIP, Description
SOIC QFN
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. PIC18F2420/2520/4420/4520
DS39631E-page 16 © 2008 Microchip Technology Inc.
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
MCLR/VPP/RE3
MCLR
VPP
RE3
1 18 18
I
P
I
ST
ST
Master Clear (input) or programming voltage (input).
Master Clear (Reset) input. This pin is an active-low
Reset to the device.
Programming voltage input.
Digital input.
OSC1/CLKI/RA7
OSC1
CLKI
RA7
13 32 30
I
I
I/O
ST
CMOS
TTL
Oscillator crystal or external clock input.
Oscillator crystal input or external clock source input.
ST buffer when configured in RC mode;
analog otherwise.
External clock source input. Always associated with
pin function, OSC1. (See related OSC1/CLKI,
OSC2/CLKO pins.)
General purpose I/O pin.
OSC2/CLKO/RA6
OSC2
CLKO
RA6
14 33 31
O
O
I/O
—
—
TTL
Oscillator crystal or clock output.
Oscillator crystal output. Connects to crystal
or resonator in Crystal Oscillator mode.
In RC mode, OSC2 pin outputs CLKO which
has 1/4 the frequency of OSC1 and denotes
the instruction cycle rate.
General purpose I/O pin.
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. © 2008 Microchip Technology Inc. DS39631E-page 17
PIC18F2420/2520/4420/4520
PORTA is a bidirectional I/O port.
RA0/AN0
RA0
AN0
2 19 19
I/O
I
TTL
Analog
Digital I/O.
Analog input 0.
RA1/AN1
RA1
AN1
3 20 20
I/O
I
TTL
Analog
Digital I/O.
Analog input 1.
RA2/AN2/VREF-/CVREF
RA2
AN2
VREFCVREF
4 21 21
I/O
I
I
O
TTL
Analog
Analog
Analog
Digital I/O.
Analog input 2.
A/D reference voltage (low) input.
Comparator reference voltage output.
RA3/AN3/VREF+
RA3
AN3
VREF+
5 22 22
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 3.
A/D reference voltage (high) input.
RA4/T0CKI/C1OUT
RA4
T0CKI
C1OUT
6 23 23
I/O
I
O
ST
ST
—
Digital I/O.
Timer0 external clock input.
Comparator 1 output.
RA5/AN4/SS/HLVDIN/
C2OUT
RA5
AN4
SS
HLVDIN
C2OUT
7 24 24
I/O
I
I
I
O
TTL
Analog
TTL
Analog
—
Digital I/O.
Analog input 4.
SPI slave select input.
High/Low-Voltage Detect input.
Comparator 2 output.
RA6 See the OSC2/CLKO/RA6 pin.
RA7 See the OSC1/CLKI/RA7 pin.
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. PIC18F2420/2520/4420/4520
DS39631E-page 18 © 2008 Microchip Technology Inc.
PORTB is a bidirectional I/O port. PORTB can be
software programmed for internal weak pull-ups on all
inputs.
RB0/INT0/FLT0/AN12
RB0
INT0
FLT0
AN12
33 9 8
I/O
I
I
I
TTL
ST
ST
Analog
Digital I/O.
External interrupt 0.
PWM Fault input for Enhanced CCP1.
Analog input 12.
RB1/INT1/AN10
RB1
INT1
AN10
34 10 9
I/O
I
I
TTL
ST
Analog
Digital I/O.
External interrupt 1.
Analog input 10.
RB2/INT2/AN8
RB2
INT2
AN8
35 11 10
I/O
I
I
TTL
ST
Analog
Digital I/O.
External interrupt 2.
Analog input 8.
RB3/AN9/CCP2
RB3
AN9
CCP2(1)
36 12 11
I/O
I
I/O
TTL
Analog
ST
Digital I/O.
Analog input 9.
Capture 2 input/Compare 2 output/PWM2 output.
RB4/KBI0/AN11
RB4
KBI0
AN11
37 14 14
I/O
I
I
TTL
TTL
Analog
Digital I/O.
Interrupt-on-change pin.
Analog input 11.
RB5/KBI1/PGM
RB5
KBI1
PGM
38 15 15
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
Low-Voltage ICSP™ Programming enable pin.
RB6/KBI2/PGC
RB6
KBI2
PGC
39 16 16
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming
clock pin.
RB7/KBI3/PGD
RB7
KBI3
PGD
40 17 17
I/O
I
I/O
TTL
TTL
ST
Digital I/O.
Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming
data pin.
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. © 2008 Microchip Technology Inc. DS39631E-page 19
PIC18F2420/2520/4420/4520
PORTC is a bidirectional I/O port.
RC0/T1OSO/T13CKI
RC0
T1OSO
T13CKI
15 34 32
I/O
O
I
ST
—
ST
Digital I/O.
Timer1 oscillator output.
Timer1/Timer3 external clock input.
RC1/T1OSI/CCP2
RC1
T1OSI
CCP2(2)
16 35 35
I/O
I
I/O
ST
CMOS
ST
Digital I/O.
Timer1 oscillator input.
Capture 2 input/Compare 2 output/PWM2 output.
RC2/CCP1/P1A
RC2
CCP1
P1A
17 36 36
I/O
I/O
O
ST
ST
—
Digital I/O.
Capture 1 input/Compare 1 output/PWM1 output.
Enhanced CCP1 output.
RC3/SCK/SCL
RC3
SCK
SCL
18 37 37
I/O
I/O
I/O
ST
ST
ST
Digital I/O.
Synchronous serial clock input/output for
SPI mode.
Synchronous serial clock input/output for I2C™ mode.
RC4/SDI/SDA
RC4
SDI
SDA
23 42 42
I/O
I
I/O
ST
ST
ST
Digital I/O.
SPI data in.
I
2C data I/O.
RC5/SDO
RC5
SDO
24 43 43
I/O
O
ST
—
Digital I/O.
SPI data out.
RC6/TX/CK
RC6
TX
CK
25 44 44
I/O
O
I/O
ST
—
ST
Digital I/O.
EUSART asynchronous transmit.
EUSART synchronous clock (see related RX/DT).
RC7/RX/DT
RC7
RX
DT
26 1 1
I/O
I
I/O
ST
ST
ST
Digital I/O.
EUSART asynchronous receive.
EUSART synchronous data (see related TX/CK).
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. PIC18F2420/2520/4420/4520
DS39631E-page 20 © 2008 Microchip Technology Inc.
PORTD is a bidirectional I/O port or a Parallel Slave
Port (PSP) for interfacing to a microprocessor port.
These pins have TTL input buffers when PSP module
is enabled.
RD0/PSP0
RD0
PSP0
19 38 38
I/O
I/O
ST
TTL
Digital I/O.
Parallel Slave Port data.
RD1/PSP1
RD1
PSP1
20 39 39
I/O
I/O
ST
TTL
Digital I/O.
Parallel Slave Port data.
RD2/PSP2
RD2
PSP2
21 40 40
I/O
I/O
ST
TTL
Digital I/O.
Parallel Slave Port data.
RD3/PSP3
RD3
PSP3
22 41 41
I/O
I/O
ST
TTL
Digital I/O.
Parallel Slave Port data.
RD4/PSP4
RD4
PSP4
27 2 2
I/O
I/O
ST
TTL
Digital I/O.
Parallel Slave Port data.
RD5/PSP5/P1B
RD5
PSP5
P1B
28 3 3
I/O
I/O
O
ST
TTL
—
Digital I/O.
Parallel Slave Port data.
Enhanced CCP1 output.
RD6/PSP6/P1C
RD6
PSP6
P1C
29 4 4
I/O
I/O
O
ST
TTL
—
Digital I/O.
Parallel Slave Port data.
Enhanced CCP1 output.
RD7/PSP7/P1D
RD7
PSP7
P1D
30 5 5
I/O
I/O
O
ST
TTL
—
Digital I/O.
Parallel Slave Port data.
Enhanced CCP1 output.
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. © 2008 Microchip Technology Inc. DS39631E-page 21
PIC18F2420/2520/4420/4520
PORTE is a bidirectional I/O port.
RE0/RD/AN5
RE0
RD
AN5
8 25 25
I/O
I
I
ST
TTL
Analog
Digital I/O.
Read control for Parallel Slave Port
(see also WR and CS pins).
Analog input 5.
RE1/WR/AN6
RE1
WR
AN6
9 26 26
I/O
I
I
ST
TTL
Analog
Digital I/O.
Write control for Parallel Slave Port
(see CS and RD pins).
Analog input 6.
RE2/CS/AN7
RE2
CS
AN7
10 27 27
I/O
I
I
ST
TTL
Analog
Digital I/O.
Chip Select control for Parallel Slave Port
(see related RD and WR).
Analog input 7.
RE3 — — — — — See MCLR/VPP/RE3 pin.
VSS 12, 31 6, 30,
31
6, 29 P — Ground reference for logic and I/O pins.
VDD 11, 32 7, 8,
28, 29
7, 28 P — Positive supply for logic and I/O pins.
NC — 13 12, 13,
33, 34
— — No Connect.
TABLE 1-3: PIC18F4420/4520 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description PDIP QFN TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
Note 1: Default assignment for CCP2 when Configuration bit, CCP2MX, is set.
2: Alternate assignment for CCP2 when Configuration bit, CCP2MX, is cleared. PIC18F2420/2520/4420/4520
DS39631E-page 22 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 23
PIC18F2420/2520/4420/4520
2.0 OSCILLATOR
CONFIGURATIONS
2.1 Oscillator Types
PIC18F2420/2520/4420/4520 devices can be operated
in ten different oscillator modes. The user can program
the Configuration bits, FOSC<3:0>, in Configuration
Register 1H to select one of these ten modes:
1. LP Low-Power Crystal
2. XT Crystal/Resonator
3. HS High-Speed Crystal/Resonator
4. HSPLL High-Speed Crystal/Resonator
with PLL Enabled
5. RC External Resistor/Capacitor with
FOSC/4 Output on RA6
6. RCIO External Resistor/Capacitor with I/O
on RA6
7. INTIO1 Internal Oscillator with FOSC/4 Output
on RA6 and I/O on RA7
8. INTIO2 Internal Oscillator with I/O on RA6
and RA7
9. EC External Clock with FOSC/4 Output
10. ECIO External Clock with I/O on RA6
2.2 Crystal Oscillator/Ceramic
Resonators
In XT, LP, HS or HSPLL Oscillator modes, a crystal or
ceramic resonator is connected to the OSC1 and
OSC2 pins to establish oscillation. Figure 2-1 shows
the pin connections.
The oscillator design requires the use of a parallel cut
crystal.
FIGURE 2-1: CRYSTAL/CERAMIC
RESONATOR OPERATION
(XT, LP, HS OR HSPLL
CONFIGURATION)
TABLE 2-1: CAPACITOR SELECTION FOR
CERAMIC RESONATORS
Note: Use of a series cut crystal may give a frequency
out of the crystal manufacturer’s
specifications.
Typical Capacitor Values Used:
Mode Freq OSC1 OSC2
XT 3.58 MHz
4.19 MHz
4 MHz
4 MHz
15 pF
15 pF
30 pF
50 pF
15 pF
15 pF
30 pF
50 pF
Capacitor values are for design guidance only.
Different capacitor values may be required to produce
acceptable oscillator operation. The user should test
the performance of the oscillator over the expected
VDD and temperature range for the application.
See the notes following Table 2-2 for additional
information.
Note: When using resonators with frequencies
above 3.5 MHz, the use of HS mode,
rather than XT mode, is recommended.
HS mode may be used at any VDD for
which the controller is rated. If HS is
selected, it is possible that the gain of the
oscillator will overdrive the resonator.
Therefore, a series resistor should be
placed between the OSC2 pin and the
resonator. As a good starting point, the
recommended value of RS is 330Ω.
Note 1: See Table 2-1 and Table 2-2 for initial values of
C1 and C2.
2: A series resistor (RS) may be required for AT
strip cut crystals.
3: RF varies with the oscillator mode chosen.
C1(1)
C2(1)
XTAL
OSC2
OSC1
RF(3)
Sleep
To
Logic
PIC18FXXXX
RS(2)
InternalPIC18F2420/2520/4420/4520
DS39631E-page 24 © 2008 Microchip Technology Inc.
TABLE 2-2: CAPACITOR SELECTION FOR
CRYSTAL OSCILLATOR
An external clock source may also be connected to the
OSC1 pin in the HS mode, as shown in Figure 2-2.
FIGURE 2-2: EXTERNAL CLOCK INPUT
OPERATION (HS OSC
CONFIGURATION)
2.3 External Clock Input
The EC and ECIO Oscillator modes require an external
clock source to be connected to the OSC1 pin. There is
no oscillator start-up time required after a Power-on
Reset or after an exit from Sleep mode.
In the EC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes or to synchronize other
logic. Figure 2-3 shows the pin connections for the EC
Oscillator mode.
FIGURE 2-3: EXTERNAL CLOCK
INPUT OPERATION
(EC CONFIGURATION)
The ECIO Oscillator mode functions like the EC mode,
except that the OSC2 pin becomes an additional general
purpose I/O pin. The I/O pin becomes bit 6 of
PORTA (RA6). Figure 2-4 shows the pin connections
for the ECIO Oscillator mode.
FIGURE 2-4: EXTERNAL CLOCK
INPUT OPERATION
(ECIO CONFIGURATION)
Osc Type Crystal
Freq
Typical Capacitor Values
Tested:
C1 C2
LP 32 kHz 30 pF 30 pF
XT 1 MHz
4 MHz
15 pF
15 pF
15 pF
15 pF
HS 4 MHz
10 MHz
20 MHz
25 MHz
25 MHz
15 pF
15 pF
15 pF
0 pF
15 pF
15 pF
15 pF
15 pF
5 pF
15 pF
Capacitor values are for design guidance only.
These capacitors were tested with the crystals listed
below for basic start-up and operation. These values
are not optimized.
Different capacitor values may be required to produce
acceptable oscillator operation. The user should test
the performance of the oscillator over the expected
VDD and temperature range for the application.
See the notes following this table for additional
information.
Crystals Used:
32 kHz 4 MHz
25 MHz 10 MHz
1 MHz 20 MHz
Note 1: Higher capacitance increases the stability
of the oscillator but also increases the
start-up time.
2: When operating below 3V VDD, or when
using certain ceramic resonators at any
voltage, it may be necessary to use the
HS mode or switch to a crystal oscillator.
3: Since each resonator/crystal has its own
characteristics, the user should consult
the resonator/crystal manufacturer for
appropriate values of external
components.
4: Rs may be required to avoid overdriving
crystals with low drive level specification.
5: Always verify oscillator performance over
the VDD and temperature range that is
expected for the application.
OSC1
Open OSC2
Clock from
Ext. System PIC18FXXXX
(HS Mode)
OSC1/CLKI
FOSC/4 OSC2/CLKO
Clock from
Ext. System PIC18FXXXX
OSC1/CLKI
RA6 I/O (OSC2)
Clock from
Ext. System PIC18FXXXX© 2008 Microchip Technology Inc. DS39631E-page 25
PIC18F2420/2520/4420/4520
2.4 RC Oscillator
For timing insensitive applications, the “RC” and
“RCIO” device options offer additional cost savings.
The actual oscillator frequency is a function of several
factors:
• supply voltage
• values of the external resistor (REXT) and
capacitor (CEXT)
• operating temperature
Given the same device, operating voltage and temperature
and component values, there will also be unit-to-unit
frequency variations. These are due to factors such as:
• normal manufacturing variation
• difference in lead frame capacitance between
package types (especially for low CEXT values)
• variations within the tolerance of limits of REXT
and CEXT
In the RC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes or to synchronize other
logic. Figure 2-5 shows how the R/C combination is
connected.
FIGURE 2-5: RC OSCILLATOR MODE
The RCIO Oscillator mode (Figure 2-6) functions like
the RC mode, except that the OSC2 pin becomes an
additional general purpose I/O pin. The I/O pin
becomes bit 6 of PORTA (RA6).
FIGURE 2-6: RCIO OSCILLATOR MODE
2.5 PLL Frequency Multiplier
A Phase Locked Loop (PLL) circuit is provided as an
option for users who wish to use a lower frequency
oscillator circuit or to clock the device up to its highest
rated frequency from a crystal oscillator. This may be
useful for customers who are concerned with EMI due
to high-frequency crystals or users who require higher
clock speeds from an internal oscillator.
2.5.1 HSPLL OSCILLATOR MODE
The HSPLL mode makes use of the HS Oscillator
mode for frequencies up to 10 MHz. A PLL then multiplies
the oscillator output frequency by 4 to produce an
internal clock frequency up to 40 MHz. The PLLEN bit
is not available in this oscillator mode.
The PLL is only available to the crystal oscillator when
the FOSC<3:0> Configuration bits are programmed for
HSPLL mode (= 0110).
FIGURE 2-7: PLL BLOCK DIAGRAM (HS
MODE)
2.5.2 PLL AND INTOSC
The PLL is also available to the internal oscillator block
in selected oscillator modes. In this configuration, the
PLL is enabled in software and generates a clock output
of up to 32 MHz. The operation of INTOSC with the
PLL is described in Section 2.6.4 “PLL in INTOSC
Modes”.
OSC2/CLKO
CEXT
REXT
PIC18FXXXX
OSC1
FOSC/4
Internal
Clock
VDD
VSS
Recommended values: 3 kΩ ≤ REXT ≤ 100 kΩ
CEXT > 20 pF
CEXT
REXT
PIC18FXXXX
OSC1 Internal
Clock
VDD
VSS
Recommended values: 3 kΩ ≤ REXT ≤ 100 kΩ
CEXT > 20 pF
RA6 I/O (OSC2)
MUX
VCO
Loop
Filter
Crystal
Osc
OSC2
OSC1
PLL Enable
FIN
FOUT
SYSCLK
Phase
Comparator
HS Oscillator Enable
÷4
(from Configuration Register 1H)
HS ModePIC18F2420/2520/4420/4520
DS39631E-page 26 © 2008 Microchip Technology Inc.
2.6 Internal Oscillator Block
The PIC18F2420/2520/4420/4520 devices include an
internal oscillator block which generates two different
clock signals; either can be used as the microcontroller’s
clock source. This may eliminate the need
for external oscillator circuits on the OSC1 and/or
OSC2 pins.
The main output (INTOSC) is an 8 MHz clock source
which can be used to directly drive the device clock. It
also drives a postscaler which can provide a range of
clock frequencies from 31 kHz to 4 MHz. The INTOSC
output is enabled when a clock frequency from 125 kHz
to 8 MHz is selected.
The other clock source is the internal RC oscillator
(INTRC), which provides a nominal 31 kHz output.
INTRC is enabled if it is selected as the device clock
source; it is also enabled automatically when any of the
following are enabled:
• Power-up Timer
• Fail-Safe Clock Monitor
• Watchdog Timer
• Two-Speed Start-up
These features are discussed in greater detail in
Section 23.0 “Special Features of the CPU”.
The clock source frequency (INTOSC direct, INTRC
direct or INTOSC postscaler) is selected by configuring
the IRCF bits of the OSCCON register (page 30).
2.6.1 INTIO MODES
Using the internal oscillator as the clock source eliminates
the need for up to two external oscillator pins,
which can then be used for digital I/O. Two distinct
configurations are available:
• In INTIO1 mode, the OSC2 pin outputs FOSC/4,
while OSC1 functions as RA7 for digital input and
output.
• In INTIO2 mode, OSC1 functions as RA7 and
OSC2 functions as RA6, both for digital input and
output.
2.6.2 INTOSC OUTPUT FREQUENCY
The internal oscillator block is calibrated at the factory
to produce an INTOSC output frequency of 8.0 MHz.
The INTRC oscillator operates independently of the
INTOSC source. Any changes in INTOSC across
voltage and temperature are not necessarily reflected
by changes in INTRC and vice versa.
2.6.3 OSCTUNE REGISTER
The internal oscillator’s output has been calibrated at
the factory but can be adjusted in the user’s application.
This is done by writing to the OSCTUNE register
(Register 2-1).
When the OSCTUNE register is modified, the INTOSC
frequency will begin shifting to the new frequency. The
INTRC clock will reach the new frequency within
8 clock cycles (approximately 8 * 32 μs = 256 μs). The
INTOSC clock will stabilize within 1 ms. Code execution
continues during this shift. There is no indication
that the shift has occurred.
The OSCTUNE register also implements the INTSRC
and PLLEN bits, which control certain features of the
internal oscillator block. The INTSRC bit allows users
to select which internal oscillator provides the clock
source when the 31 kHz frequency option is selected.
This is covered in greater detail in Section 2.7.1
“Oscillator Control Register”.
The PLLEN bit controls the operation of the frequency
multiplier, PLL, in internal oscillator modes.
2.6.4 PLL IN INTOSC MODES
The 4x frequency multiplier can be used with the internal
oscillator block to produce faster device clock
speeds than are normally possible with an internal
oscillator. When enabled, the PLL produces a clock
speed of up to 32 MHz.
Unlike HSPLL mode, the PLL is controlled through
software. The control bit, PLLEN (OSCTUNE<6>), is
used to enable or disable its operation.
The PLL is available when the device is configured to
use the internal oscillator block as its primary clock
source (FOSC<3:0> = 1001 or 1000). Additionally, the
PLL will only function when the selected output frequency
is either 4 MHz or 8 MHz (OSCCON<6:4> = 111
or 110). If both of these conditions are not met, the PLL
is disabled.
The PLLEN control bit is only functional in those internal
oscillator modes where the PLL is available. In all
other modes, it is forced to ‘0’ and is effectively
unavailable.
2.6.5 INTOSC FREQUENCY DRIFT
The factory calibrates the internal oscillator block
output (INTOSC) for 8 MHz. However, this frequency
may drift as VDD or temperature changes, which can
affect the controller operation in a variety of ways. It is
possible to adjust the INTOSC frequency by modifying
the value in the OSCTUNE register. This has no effect
on the INTRC clock source frequency.
Tuning the INTOSC source requires knowing when to
make the adjustment, in which direction it should be
made, and in some cases, how large a change is
needed. Three compensation techniques are discussed
in Section 2.6.5.1 “Compensating with the
EUSART”, Section 2.6.5.2 “Compensating with the
Timers” and Section 2.6.5.3 “Compensating with the
CCP Module in Capture Mode”, but other techniques
may be used.© 2008 Microchip Technology Inc. DS39631E-page 27
PIC18F2420/2520/4420/4520
2.6.5.1 Compensating with the EUSART
An adjustment may be required when the EUSART
begins to generate framing errors or receives data with
errors while in Asynchronous mode. Framing errors
indicate that the device clock frequency is too high. To
adjust for this, decrement the value in OSCTUNE to
reduce the clock frequency. On the other hand, errors
in data may suggest that the clock speed is too low. To
compensate, increment OSCTUNE to increase the
clock frequency.
2.6.5.2 Compensating with the Timers
This technique compares device clock speed to some
reference clock. Two timers may be used; one timer is
clocked by the peripheral clock, while the other is
clocked by a fixed reference source, such as the
Timer1 oscillator.
Both timers are cleared, but the timer clocked by the
reference generates interrupts. When an interrupt
occurs, the internally clocked timer is read and both
timers are cleared. If the internally clocked timer value
is greater than expected, then the internal oscillator
block is running too fast. To adjust for this, decrement
the OSCTUNE register.
2.6.5.3 Compensating with the CCP Module
in Capture Mode
A CCP module can use free-running Timer1 (or
Timer3), clocked by the internal oscillator block and an
external event with a known period (i.e., AC power frequency).
The time of the first event is captured in the
CCPRxH:CCPRxL registers and is recorded for use
later. When the second event causes a capture, the
time of the first event is subtracted from the time of the
second event. Since the period of the external event is
known, the time difference between events can be
calculated.
If the measured time is much greater than the calculated
time, the internal oscillator block is running too
fast; to compensate, decrement the OSCTUNE register.
If the measured time is much less than the calculated
time, the internal oscillator block is running too slow; to
compensate, increment the OSCTUNE register.
REGISTER 2-1: OSCTUNE: OSCILLATOR TUNING REGISTER
R/W-0 R/W-0(1) U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
INTSRC PLLEN(1) — TUN4 TUN3 TUN2 TUN1 TUN0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 INTSRC: Internal Oscillator Low-Frequency Source Select bit
1 = 31.25 kHz device clock derived from 8 MHz INTOSC source (divide-by-256 enabled)
0 = 31 kHz device clock derived directly from INTRC internal oscillator
bit 6 PLLEN: Frequency Multiplier PLL for INTOSC Enable bit(1)
1 = PLL enabled for INTOSC (4 MHz and 8 MHz only)
0 = PLL disabled
bit 5 Unimplemented: Read as ‘0’
bit 4-0 TUN<4:0>: Frequency Tuning bits
011111 = Maximum frequency
• •
• •
000001
000000 = Center frequency. Oscillator module is running at the calibrated frequency.
111111
• •
• •
100000 = Minimum frequency
Note 1: Available only in certain oscillator configurations; otherwise, this bit is unavailable and reads as ‘0’. See
Section 2.6.4 “PLL in INTOSC Modes” for details.PIC18F2420/2520/4420/4520
DS39631E-page 28 © 2008 Microchip Technology Inc.
2.7 Clock Sources and Oscillator
Switching
Like previous PIC18 devices, the PIC18F2420/2520/
4420/4520 family includes a feature that allows the
device clock source to be switched from the main oscillator
to an alternate low-frequency clock source.
PIC18F2420/2520/4420/4520 devices offer two alternate
clock sources. When an alternate clock source is enabled,
the various power-managed operating modes are
available.
Essentially, there are three clock sources for these
devices:
• Primary oscillators
• Secondary oscillators
• Internal oscillator block
The primary oscillators include the External Crystal
and Resonator modes, the External RC modes, the
External Clock modes and the internal oscillator block.
The particular mode is defined by the FOSC<3:0> Configuration
bits. The details of these modes are covered
earlier in this chapter.
The secondary oscillators are those external sources
not connected to the OSC1 or OSC2 pins. These
sources may continue to operate even after the
controller is placed in a power-managed mode.
PIC18F2420/2520/4420/4520 devices offer the Timer1
oscillator as a secondary oscillator. This oscillator, in all
power-managed modes, is often the time base for
functions such as a Real-Time Clock (RTC).
Most often, a 32.768 kHz watch crystal is connected
between the RC0/T1OSO/T13CKI and RC1/T1OSI
pins. Like the LP Oscillator mode circuit, loading
capacitors are also connected from each pin to ground.
The Timer1 oscillator is discussed in greater detail in
Section 12.3 “Timer1 Oscillator”.
In addition to being a primary clock source, the internal
oscillator block is available as a power-managed
mode clock source. The INTRC source is also used as
the clock source for several special features, such as
the WDT and Fail-Safe Clock Monitor.
The clock sources for the PIC18F2420/2520/4420/4520
devices are shown in Figure 2-8. See Section 23.0
“Special Features of the CPU” for Configuration
register details.
FIGURE 2-8: PIC18F2420/2520/4420/4520 CLOCK DIAGRAM
4 x PLL
FOSC<3:0>
Secondary Oscillator
T1OSCEN
Enable
Oscillator
T1OSO
T1OSI
Clock Source Option
for Other Modules
OSC1
OSC2
Sleep HSPLL, INTOSC/PLL
LP, XT, HS, RC, EC
T1OSC
CPU
Peripherals
IDLEN
Postscaler
MUX
MUX
8 MHz
4 MHz
2 MHz
1 MHz
500 kHz
125 kHz
250 kHz
OSCCON<6:4>
111
110
101
100
011
010
001
000 31 kHz
INTRC
Source
Internal
Oscillator
Block
WDT, PWRT, FSCM
8 MHz
Internal Oscillator
(INTOSC)
OSCCON<6:4>
Clock
Control
OSCCON<1:0>
Source
8 MHz
31 kHz (INTRC)
OSCTUNE<6>
0
1
OSCTUNE<7>
and Two-Speed Start-up
Primary Oscillator
PIC18F2420/2520/4420/4520© 2008 Microchip Technology Inc. DS39631E-page 29
PIC18F2420/2520/4420/4520
2.7.1 OSCILLATOR CONTROL REGISTER
The OSCCON register (Register 2-2) controls several
aspects of the device clock’s operation, both in full-power
operation and in power-managed modes.
The System Clock Select bits, SCS<1:0>, select the
clock source. The available clock sources are the
primary clock (defined by the FOSC<3:0> Configuration
bits), the secondary clock (Timer1 oscillator) and
the internal oscillator block. The clock source changes
immediately after one or more of the bits is written to,
following a brief clock transition interval. The SCS bits
are cleared on all forms of Reset.
The Internal Oscillator Frequency Select bits
(IRCF<2:0>) select the frequency output of the internal
oscillator block to drive the device clock. The choices
are the INTRC source, the INTOSC source (8 MHz) or
one of the frequencies derived from the INTOSC postscaler
(31.25 kHz to 4 MHz). If the internal oscillator
block is supplying the device clock, changing the states
of these bits will have an immediate change on the
internal oscillator’s output. On device Resets, the
default output frequency of the internal oscillator block
is set at 1 MHz.
When a nominal output frequency of 31 kHz is selected
(IRCF<2:0> = 000), users may choose which internal
oscillator acts as the source. This is done with the
INTSRC bit in the OSCTUNE register (OSCTUNE<7>).
Setting this bit selects INTOSC as a 31.25 kHz clock
source by enabling the divide-by-256 output of the
INTOSC postscaler. Clearing INTSRC selects INTRC
(nominally 31 kHz) as the clock source.
This option allows users to select the tunable and more
precise INTOSC as a clock source, while maintaining
power savings with a very low clock speed. Regardless
of the setting of INTSRC, INTRC always remains the
clock source for features such as the Watchdog Timer
and the Fail-Safe Clock Monitor.
The OSTS, IOFS and T1RUN bits indicate which clock
source is currently providing the device clock. The
OSTS bit indicates that the Oscillator Start-up Timer
(OST) has timed out and the primary clock is providing
the device clock in primary clock modes. The IOFS bit
indicates when the internal oscillator block has stabilized
and is providing the device clock in RC Clock
modes. The T1RUN bit (T1CON<6>) indicates when
the Timer1 oscillator is providing the device clock in
secondary clock modes. In power-managed modes,
only one of these three bits will be set at any time. If
none of these bits are set, the INTRC is providing the
clock or the internal oscillator block has just started and
is not yet stable.
The IDLEN bit determines if the device goes into Sleep
mode or one of the Idle modes when the SLEEP
instruction is executed.
The use of the flag and control bits in the OSCCON
register is discussed in more detail in Section 3.0
“Power-Managed Modes”.
2.7.2 OSCILLATOR TRANSITIONS
PIC18F2420/2520/4420/4520 devices contain circuitry
to prevent clock “glitches” when switching between
clock sources. A short pause in the device clock occurs
during the clock switch. The length of this pause is the
sum of two cycles of the old clock source and three to
four cycles of the new clock source. This formula
assumes that the new clock source is stable.
Clock transitions are discussed in greater detail in
Section 3.1.2 “Entering Power-Managed Modes”.
Note 1: The Timer1 oscillator must be enabled to
select the secondary clock source. The
Timer1 oscillator is enabled by setting the
T1OSCEN bit in the Timer1 Control register
(T1CON<3>). If the Timer1 oscillator
is not enabled, then any attempt to select
a secondary clock source will be ignored.
2: It is recommended that the Timer1
oscillator be operating and stable before
selecting the secondary clock source or a
very long delay may occur while the
Timer1 oscillator starts. PIC18F2420/2520/4420/4520
DS39631E-page 30 © 2008 Microchip Technology Inc.
REGISTER 2-2: OSCCON: OSCILLATOR CONTROL REGISTER
R/W-0 R/W-1 R/W-0 R/W-0 R(1) R-0 R/W-0 R/W-0
IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 IDLEN: Idle Enable bit
1 = Device enters an Idle mode on SLEEP instruction
0 = Device enters Sleep mode on SLEEP instruction
bit 6-4 IRCF<2:0>: Internal Oscillator Frequency Select bits
111 = 8 MHz (INTOSC drives clock directly)
110 = 4 MHz
101 = 2 MHz
100 = 1 MHz(3)
011 = 500 kHz
010 = 250 kHz
001 = 125 kHz
000 = 31 kHz (from either INTOSC/256 or INTRC directly)(2)
bit 3 OSTS: Oscillator Start-up Timer Time-out Status bit(1)
1 = Oscillator Start-up Timer (OST) time-out has expired; primary oscillator is running
0 = Oscillator Start-up Timer (OST) time-out is running; primary oscillator is not ready
bit 2 IOFS: INTOSC Frequency Stable bit
1 = INTOSC frequency is stable
0 = INTOSC frequency is not stable
bit 1-0 SCS<1:0>: System Clock Select bits
1x = Internal oscillator block
01 = Secondary (Timer1) oscillator
00 = Primary oscillator
Note 1: Reset state depends on state of the IESO Configuration bit.
2: Source selected by the INTSRC bit (OSCTUNE<7>), see text.
3: Default output frequency of INTOSC on Reset.© 2008 Microchip Technology Inc. DS39631E-page 31
PIC18F2420/2520/4420/4520
2.8 Effects of Power-Managed Modes
on the Various Clock Sources
When PRI_IDLE mode is selected, the designated primary
oscillator continues to run without interruption.
For all other power-managed modes, the oscillator
using the OSC1 pin is disabled. The OSC1 pin (and
OSC2 pin, if used by the oscillator) will stop oscillating.
In secondary clock modes (SEC_RUN and
SEC_IDLE), the Timer1 oscillator is operating and providing
the device clock. The Timer1 oscillator may also
run in all power-managed modes if required to clock
Timer1 or Timer3.
In internal oscillator modes (RC_RUN and RC_IDLE),
the internal oscillator block provides the device clock
source. The 31 kHz INTRC output can be used directly
to provide the clock and may be enabled to support
various special features, regardless of the powermanaged
mode (see Section 23.2 “Watchdog Timer
(WDT)”, Section 23.3 “Two-Speed Start-up” and
Section 23.4 “Fail-Safe Clock Monitor” for more
information on WDT, Fail-Safe Clock Monitor and TwoSpeed
Start-up). The INTOSC output at 8 MHz may be
used directly to clock the device or may be divided
down by the postscaler. The INTOSC output is disabled
if the clock is provided directly from the INTRC output.
If Sleep mode is selected, all clock sources are
stopped. Since all the transistor switching currents
have been stopped, Sleep mode achieves the lowest
current consumption of the device (only leakage
currents).
Enabling any on-chip feature that will operate during
Sleep will increase the current consumed during Sleep.
The INTRC is required to support WDT operation. The
Timer1 oscillator may be operating to support a RealTime
Clock. Other features may be operating that do
not require a device clock source (i.e., MSSP slave,
PSP, INTx pins and others). Peripherals that may add
significant current consumption are listed in
Section 26.2 “DC Characteristics”.
2.9 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 is stable under normal
circumstances and the primary clock is operating
and stable. For additional information on power-up
delays, see Section 4.5 “Device Reset Timers”.
The first timer is the Power-up Timer (PWRT), which
provides a fixed delay on power-up (parameter 33,
Table 26-10). It is enabled by clearing (= 0) the
PWRTEN Configuration bit.
The second timer is the Oscillator Start-up Timer
(OST), intended to keep the chip in Reset until the
crystal oscillator is stable (LP, XT and HS modes). The
OST does this by counting 1024 oscillator cycles
before allowing the oscillator to clock the device.
When the HSPLL Oscillator mode is selected, the
device is kept in Reset for an additional 2 ms, following
the HS mode OST delay, so the PLL can lock to the
incoming clock frequency.
There is a delay of interval, TCSD (parameter 38,
Table 26-10), following POR, while the controller
becomes ready to execute instructions. This delay runs
concurrently with any other delays. This may be the
only delay that occurs when any of the EC, RC or INTIO
modes are used as the primary clock source.
TABLE 2-3: OSC1 AND OSC2 PIN STATES IN SLEEP MODE
OSC Mode OSC1 Pin OSC2 Pin
RC, INTIO1 Floating, external resistor should pull high At logic low (clock/4 output)
RCIO Floating, external resistor should pull high Configured as PORTA, bit 6
INTIO2 Configured as PORTA, bit 7 Configured as PORTA, bit 6
ECIO Floating, pulled by external clock Configured as PORTA, bit 6
EC Floating, pulled by external clock At logic low (clock/4 output)
LP, XT and HS Feedback inverter disabled at quiescent
voltage level
Feedback inverter disabled at quiescent
voltage level
Note: See Table 4-2 in Section 4.0 “Reset” for time-outs due to Sleep and MCLR Reset.PIC18F2420/2520/4420/4520
DS39631E-page 32 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. Advance Information DS39631E-page 33
PIC18F2420/2520/4420/4520
3.0 POWER-MANAGED MODES
PIC18F2420/2520/4420/4520 devices offer a total of
seven operating modes for more efficient powermanagement.
These modes provide a variety of
options for selective power conservation in applications
where resources may be limited (i.e., battery-powered
devices).
There are three categories of power-managed modes:
• Run modes
• Idle modes
• Sleep mode
These categories define which portions of the device
are clocked and sometimes, what speed. The Run and
Idle modes may use any of the three available clock
sources (primary, secondary or internal oscillator
block); the Sleep mode does not use a clock source.
The power-managed modes include several powersaving
features offered on previous PIC® devices. One
is the clock switching feature, offered in other PIC18
devices, allowing the controller to use the Timer1
oscillator in place of the primary oscillator. Also
included is the Sleep mode, offered by all PIC devices,
where all device clocks are stopped.
3.1 Selecting Power-Managed Modes
Selecting a power-managed mode requires two
decisions: if the CPU is to be clocked or not and the
selection of a clock source. The IDLEN bit
(OSCCON<7>) controls CPU clocking, while the
SCS<1:0> bits (OSCCON<1:0>) select the clock
source. The individual modes, bit settings, clock sources
and affected modules are summarized in Table 3-1.
3.1.1 CLOCK SOURCES
The SCS<1:0> bits allow the selection of one of three
clock sources for power-managed modes. They are:
• the primary clock, as defined by the FOSC<3:0>
Configuration bits
• the secondary clock (the Timer1 oscillator)
• the internal oscillator block (for RC modes)
3.1.2 ENTERING POWER-MANAGED
MODES
Switching from one power-managed mode to another
begins by loading the OSCCON register. The
SCS<1:0> bits select the clock source and determine
which Run or Idle mode is to be used. Changing these
bits causes an immediate switch to the new clock
source, assuming that it is running. The switch may
also be subject to clock transition delays. These are
discussed in Section 3.1.3 “Clock Transitions and
Status Indicators” and subsequent sections.
Entry to the power-managed Idle or Sleep modes is
triggered by the execution of a SLEEP instruction. The
actual mode that results depends on the status of the
IDLEN bit.
Depending on the current mode and the mode being
switched to, a change to a power-managed mode does
not always require setting all of these bits. Many
transitions may be done by changing the oscillator select
bits, or changing the IDLEN bit, prior to issuing a SLEEP
instruction. If the IDLEN bit is already configured
correctly, it may only be necessary to perform a SLEEP
instruction to switch to the desired mode.
TABLE 3-1: POWER-MANAGED MODES
Mode
OSCCON<7,1:0> Bits Module Clocking
Available Clock and Oscillator Source
IDLEN(1) SCS<1:0> CPU Peripherals
Sleep 0 N/A Off Off None – All clocks are disabled
PRI_RUN N/A 00 Clocked Clocked Primary – LP, XT, HS, HSPLL, RC, EC and
Internal Oscillator Block(2).
This is the normal full-power execution mode.
SEC_RUN N/A 01 Clocked Clocked Secondary – Timer1 Oscillator
RC_RUN N/A 1x Clocked Clocked Internal Oscillator Block(2)
PRI_IDLE 1 00 Off Clocked Primary – LP, XT, HS, HSPLL, RC, EC
SEC_IDLE 1 01 Off Clocked Secondary – Timer1 Oscillator
RC_IDLE 1 1x Off Clocked Internal Oscillator Block(2)
Note 1: IDLEN reflects its value when the SLEEP instruction is executed.
2: Includes INTOSC and INTOSC postscaler, as well as the INTRC source.PIC18F2420/2520/4420/4520
DS39631E-page 34 Advance Information © 2008 Microchip Technology Inc.
3.1.3 CLOCK TRANSITIONS AND STATUS
INDICATORS
The length of the transition between clock sources is
the sum of two cycles of the old clock source and three
to four cycles of the new clock source. This formula
assumes that the new clock source is stable.
Three bits indicate the current clock source and its
status. They are:
• OSTS (OSCCON<3>)
• IOFS (OSCCON<2>)
• T1RUN (T1CON<6>)
In general, only one of these bits will be set while in a
given power-managed mode. When the OSTS bit is
set, the primary clock is providing the device clock.
When the IOFS bit is set, the INTOSC output is
providing a stable 8 MHz clock source to a divider that
actually drives the device clock. When the T1RUN bit is
set, the Timer1 oscillator is providing the clock. If none
of these bits are set, then either the INTRC clock
source is clocking the device or the INTOSC source is
not yet stable.
If the internal oscillator block is configured as the
primary clock source by the FOSC<3:0> Configuration
bits, then both the OSTS and IOFS bits may be set
when in PRI_RUN or PRI_IDLE modes. This indicates
that the primary clock (INTOSC output) is generating a
stable 8 MHz output. Entering another power-managed
RC mode at the same frequency would clear the OSTS
bit.
3.1.4 MULTIPLE SLEEP COMMANDS
The power-managed mode that is invoked with the
SLEEP instruction is determined by the setting of the
IDLEN bit at the time the instruction is executed. If
another SLEEP instruction is executed, the device will
enter the power-managed mode specified by IDLEN at
that time. If IDLEN has changed, the device will enter
the new power-managed mode specified by the new
setting.
3.2 Run Modes
In the Run modes, clocks to both the core and
peripherals are active. The difference between these
modes is the clock source.
3.2.1 PRI_RUN MODE
The PRI_RUN mode is the normal, full-power execution
mode of the microcontroller. This is also the default
mode upon a device Reset unless Two-Speed Start-up
is enabled (see Section 23.3 “Two-Speed Start-up”
for details). In this mode, the OSTS bit is set. The IOFS
bit may be set if the internal oscillator block is the
primary clock source (see Section 2.7.1 “Oscillator
Control Register”).
3.2.2 SEC_RUN MODE
The SEC_RUN mode is the compatible mode to the
“clock switching” feature offered in other PIC18
devices. In this mode, the CPU and peripherals are
clocked from the Timer1 oscillator. This gives users the
option of lower power consumption while still using a
high-accuracy clock source.
SEC_RUN mode is entered by setting the SCS<1:0>
bits to ‘01’. The device clock source is switched to the
Timer1 oscillator (see Figure 3-1), the primary oscillator
is shut down, the T1RUN bit (T1CON<6>) is set and
the OSTS bit is cleared.
On transitions from SEC_RUN mode to PRI_RUN
mode, the peripherals and CPU continue to be clocked
from the Timer1 oscillator while the primary clock is
started. When the primary clock becomes ready, a
clock switch back to the primary clock occurs (see
Figure 3-2). When the clock switch is complete, the
T1RUN bit is cleared, the OSTS bit is set and the
primary clock is providing the clock. The IDLEN and
SCS bits are not affected by the wake-up; the Timer1
oscillator continues to run.
Note 1: Caution should be used when modifying a
single IRCF bit. If VDD is less than 3V, it is
possible to select a higher clock speed
than is supported by the low VDD.
Improper device operation may result if
the VDD/FOSC specifications are violated.
2: Executing a SLEEP instruction does not
necessarily place the device into Sleep
mode. It acts as the trigger to place the
controller into either the Sleep mode or
one of the Idle modes, depending on the
setting of the IDLEN bit.
Note: The Timer1 oscillator should already be
running prior to entering SEC_RUN mode.
If the T1OSCEN bit is not set when the
SCS<1:0> bits are set to ‘01’, entry to
SEC_RUN mode will not occur. If the
Timer1 oscillator is enabled, but not yet
running, device clocks will be delayed until
the oscillator has started. In such situations,
initial oscillator operation is far from
stable and unpredictable operation may
result.© 2008 Microchip Technology Inc. Advance Information DS39631E-page 35
PIC18F2420/2520/4420/4520
FIGURE 3-1: TRANSITION TIMING FOR ENTRY TO SEC_RUN MODE
FIGURE 3-2: TRANSITION TIMING FROM SEC_RUN MODE TO PRI_RUN MODE (HSPLL)
3.2.3 RC_RUN MODE
In RC_RUN mode, the CPU and peripherals are
clocked from the internal oscillator block using the
INTOSC multiplexer. In this mode, the primary clock is
shut down. When using the INTRC source, this mode
provides the best power conservation of all the Run
modes while still executing code. It works well for user
applications which are not highly timing sensitive or do
not require high-speed clocks at all times.
If the primary clock source is the internal oscillator
block (either INTRC or INTOSC), there are no distinguishable
differences between PRI_RUN and
RC_RUN modes during execution. However, a clock
switch delay will occur during entry to and exit from
RC_RUN mode. Therefore, if the primary clock source
is the internal oscillator block, the use of RC_RUN
mode is not recommended.
This mode is entered by setting the SCS1 bit to ‘1’.
Although it is ignored, it is recommended that the SCS0
bit also be cleared; this is to maintain software compatibility
with future devices. When the clock source is
switched to the INTOSC multiplexer (see Figure 3-3),
the primary oscillator is shut down and the OSTS bit is
cleared. The IRCF bits may be modified at any time to
immediately change the clock speed.
Q2 Q3 Q4
OSC1
Peripheral
Program
Q1
T1OSI
Q1
Counter
Clock
CPU
Clock
PC PC + 2
1 2 3 n-1 n
Clock Transition(1)
Q2 Q3 Q4 Q1 Q2 Q3
PC + 4
Note 1: Clock transition typically occurs within 2-4 TOSC.
Q1 Q3 Q4
OSC1
Peripheral
Program PC
T1OSI
PLL Clock
Q1
PC + 4
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 2
Clock
Counter
Q2 Q2 Q3
Note1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
2: Clock transition typically occurs within 2-4 TOSC.
SCS<1:0> bits Changed
TPLL(1)
1 2 n-1 n
Clock
OSTS bit Set
Transition(2)
TOST(1)
Note: Caution should be used when modifying a
single IRCF bit. If VDD is less than 3V, it is
possible to select a higher clock speed
than is supported by the low VDD.
Improper device operation may result if
the VDD/FOSC specifications are violated.PIC18F2420/2520/4420/4520
DS39631E-page 36 Advance Information © 2008 Microchip Technology Inc.
If the IRCF bits and the INTSRC bit are all clear, the
INTOSC output is not enabled and the IOFS bit will
remain clear; there will be no indication of the current
clock source. The INTRC source is providing the
device clocks.
If the IRCF bits are changed from all clear (thus,
enabling the INTOSC output), or if INTSRC is set, the
IOFS bit becomes set after the INTOSC output
becomes stable. Clocks to the device continue while
the INTOSC source stabilizes after an interval of
TIOBST.
If the IRCF bits were previously at a non-zero value, or
if INTSRC was set before setting SCS1 and the
INTOSC source was already stable, the IOFS bit will
remain set.
On transitions from RC_RUN mode to PRI_RUN mode,
the device continues to be clocked from the INTOSC
multiplexer while the primary clock is started. When the
primary clock becomes ready, a clock switch to the primary
clock occurs (see Figure 3-4). When the clock
switch is complete, the IOFS bit is cleared, the OSTS
bit is set and the primary clock is providing the device
clock. The IDLEN and SCS bits are not affected by the
switch. The INTRC source will continue to run if either
the WDT or the Fail-Safe Clock Monitor is enabled.
FIGURE 3-3: TRANSITION TIMING TO RC_RUN MODE
FIGURE 3-4: TRANSITION TIMING FROM RC_RUN MODE TO PRI_RUN MODE
Q2 Q3 Q4
OSC1
Peripheral
Program
Q1
INTRC
Q1
Counter
Clock
CPU
Clock
PC PC + 2
1 2 3 n-1 n
Clock Transition(1)
Q2 Q3 Q4 Q1 Q2 Q3
PC + 4
Note 1: Clock transition typically occurs within 2-4 TOSC.
Q1 Q3 Q4
OSC1
Peripheral
Program PC
INTOSC
PLL Clock
Q1
PC + 4
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 2
Clock
Counter
Q2 Q2 Q3
Note1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
2: Clock transition typically occurs within 2-4 TOSC.
SCS<1:0> bits Changed
TPLL(1)
1 2 n-1 n
Clock
OSTS bit Set
Transition(2)
Multiplexer
TOST(1)© 2008 Microchip Technology Inc. Advance Information DS39631E-page 37
PIC18F2420/2520/4420/4520
3.3 Sleep Mode
The power-managed Sleep mode in the PIC18F2420/
2520/4420/4520 devices is identical to the legacy
Sleep mode offered in all other PIC devices. It is
entered by clearing the IDLEN bit (the default state on
device Reset) and executing the SLEEP instruction.
This shuts down the selected oscillator (Figure 3-5). All
clock source status bits are cleared.
Entering the Sleep mode from any other mode does not
require a clock switch. This is because no clocks are
needed once the controller has entered Sleep. If the
WDT is selected, the INTRC source will continue to
operate. If the Timer1 oscillator is enabled, it will also
continue to run.
When a wake event occurs in Sleep mode (by interrupt,
Reset or WDT time-out), the device will not be clocked
until the clock source selected by the SCS<1:0> bits
becomes ready (see Figure 3-6), or it will be clocked
from the internal oscillator block if either the Two-Speed
Start-up or the Fail-Safe Clock Monitor are enabled
(see Section 23.0 “Special Features of the CPU”). In
either case, the OSTS bit is set when the primary clock
is providing the device clocks. The IDLEN and SCS bits
are not affected by the wake-up.
3.4 Idle Modes
The Idle modes allow the controller’s CPU to be
selectively shut down while the peripherals continue to
operate. Selecting a particular Idle mode allows users
to further manage power consumption.
If the IDLEN bit is set to ‘1’ when a SLEEP instruction is
executed, the peripherals will be clocked from the clock
source selected using the SCS<1:0> bits; however, the
CPU will not be clocked. The clock source status bits are
not affected. Setting IDLEN and executing a SLEEP
instruction provides a quick method of switching from a
given Run mode to its corresponding Idle mode.
If the WDT is selected, the INTRC source will continue
to operate. If the Timer1 oscillator is enabled, it will also
continue to run.
Since the CPU is not executing instructions, the only
exits from any of the Idle modes are by interrupt, WDT
time-out or a Reset. When a wake event occurs, CPU
execution is delayed by an interval of TCSD
(parameter 38, Table 26-10) while it becomes ready to
execute code. When the CPU begins executing code,
it resumes with the same clock source for the current
Idle mode. For example, when waking from RC_IDLE
mode, the internal oscillator block will clock the CPU
and peripherals (in other words, RC_RUN mode). The
IDLEN and SCS bits are not affected by the wake-up.
While in any Idle mode or the Sleep mode, a WDT
time-out will result in a WDT wake-up to the Run mode
currently specified by the SCS1:SCS0 bits.
FIGURE 3-5: TRANSITION TIMING FOR ENTRY TO SLEEP MODE
FIGURE 3-6: TRANSITION TIMING FOR WAKE FROM SLEEP (HSPLL)
Q2 Q3 Q4
OSC1
Peripheral
Sleep
Program
Q1 Q1
Counter
Clock
CPU
Clock
PC PC + 2
Q3 Q4 Q1 Q2
OSC1
Peripheral
Program PC
PLL Clock
Q3 Q4
Output
CPU Clock
Q1 Q2 Q3 Q4 Q1 Q2
Clock
Counter PC + 4 PC + 6
Q1 Q2 Q3 Q4
Wake Event
Note1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
TOST(1) TPLL(1)
OSTS bit Set
PC + 2PIC18F2420/2520/4420/4520
DS39631E-page 38 Advance Information © 2008 Microchip Technology Inc.
3.4.1 PRI_IDLE MODE
This mode is unique among the three low-power Idle
modes in that it does not disable the primary device
clock. For timing-sensitive applications, this allows for
the fastest resumption of device operation with its more
accurate primary clock source, since the clock source
does not have to “warm-up” or transition from another
oscillator.
PRI_IDLE mode is entered from PRI_RUN mode by
setting the IDLEN bit and executing a SLEEP instruction.
If the device is in another Run mode, set IDLEN
first, then clear the SCS bits and execute SLEEP.
Although the CPU is disabled, the peripherals continue
to be clocked from the primary clock source specified
by the FOSC<3:0> Configuration bits. The OSTS bit
remains set (see Figure 3-7).
When a wake event occurs, the CPU is clocked from the
primary clock source. A delay of interval TCSD is
required between the wake event and when code
execution starts. This is required to allow the CPU to
become ready to execute instructions. After the wakeup,
the OSTS bit remains set. The IDLEN and SCS bits
are not affected by the wake-up (see Figure 3-8).
3.4.2 SEC_IDLE MODE
In SEC_IDLE mode, the CPU is disabled but the
peripherals continue to be clocked from the Timer1
oscillator. This mode is entered from SEC_RUN by
setting the IDLEN bit and executing a SLEEP instruction.
If the device is in another Run mode, set the
IDLEN bit first, then set the SCS<1:0> bits to ‘01’ and
execute SLEEP. When the clock source is switched to
the Timer1 oscillator, the primary oscillator is shut
down, the OSTS bit is cleared and the T1RUN bit is set.
When a wake event occurs, the peripherals continue to
be clocked from the Timer1 oscillator. After an interval
of TCSD, following the wake event, the CPU begins executing
code being clocked by the Timer1 oscillator. The
IDLEN and SCS bits are not affected by the wake-up;
the Timer1 oscillator continues to run (see Figure 3-8).
FIGURE 3-7: TRANSITION TIMING FOR ENTRY TO IDLE MODE
FIGURE 3-8: TRANSITION TIMING FOR WAKE FROM IDLE TO RUN MODE
Note: The Timer1 oscillator should already be
running prior to entering SEC_IDLE mode.
If the T1OSCEN bit is not set when the
SLEEP instruction is executed, the SLEEP
instruction will be ignored and entry to
SEC_IDLE mode will not occur. If the
Timer1 oscillator is enabled but not yet
running, peripheral clocks will be delayed
until the oscillator has started. In such
situations, initial oscillator operation is far
from stable and unpredictable operation
may result.
Q1
Peripheral
Program PC PC + 2
OSC1
Q3 Q4 Q1
CPU Clock
Clock
Counter
Q2
OSC1
Peripheral
Program PC
CPU Clock
Q1 Q3 Q4
Clock
Counter
Q2
Wake Event
TCSD© 2008 Microchip Technology Inc. Advance Information DS39631E-page 39
PIC18F2420/2520/4420/4520
3.4.3 RC_IDLE MODE
In RC_IDLE mode, the CPU is disabled but the peripherals
continue to be clocked from the internal oscillator
block using the INTOSC multiplexer. This mode allows
for controllable power conservation during Idle periods.
From RC_RUN, this mode is entered by setting the
IDLEN bit and executing a SLEEP instruction. If the
device is in another Run mode, first set IDLEN, then set
the SCS1 bit and execute SLEEP. Although its value is
ignored, it is recommended that SCS0 also be cleared;
this is to maintain software compatibility with future
devices. The INTOSC multiplexer may be used to
select a higher clock frequency by modifying the IRCF
bits before executing the SLEEP instruction. When the
clock source is switched to the INTOSC multiplexer, the
primary oscillator is shut down and the OSTS bit is
cleared.
If the IRCF bits are set to any non-zero value, or the
INTSRC bit is set, the INTOSC output is enabled. The
IOFS bit becomes set, after the INTOSC output
becomes stable, after an interval of TIOBST
(parameter 39, Table 26-10). Clocks to the peripherals
continue while the INTOSC source stabilizes. If the
IRCF bits were previously at a non-zero value, or
INTSRC was set before the SLEEP instruction was executed
and the INTOSC source was already stable, the
IOFS bit will remain set. If the IRCF bits and INTSRC
are all clear, the INTOSC output will not be enabled, the
IOFS bit will remain clear and there will be no indication
of the current clock source.
When a wake event occurs, the peripherals continue to
be clocked from the INTOSC multiplexer. After a delay of
TCSD following the wake event, the CPU begins
executing code being clocked by the INTOSC multiplexer.
The IDLEN and SCS bits are not affected by the
wake-up. The INTRC source will continue to run if either
the WDT or the Fail-Safe Clock Monitor is enabled.
3.5 Exiting Idle and Sleep Modes
An exit from Sleep mode or any of the Idle modes is
triggered by an interrupt, a Reset or a WDT time-out.
This section discusses the triggers that cause exits
from power-managed modes. The clocking subsystem
actions are discussed in each of the power-managed
modes (see Section 3.2 “Run Modes”, Section 3.3
“Sleep Mode” and Section 3.4 “Idle Modes”).
3.5.1 EXIT BY INTERRUPT
Any of the available interrupt sources can cause the
device to exit from an Idle mode or the Sleep mode to
a Run mode. To enable this functionality, an interrupt
source must be enabled by setting its enable bit in one
of the INTCON or PIE registers. The exit sequence is
initiated when the corresponding interrupt flag bit is set.
On all exits from Idle or Sleep modes by interrupt, code
execution branches to the interrupt vector if the GIE/
GIEH bit (INTCON<7>) is set. Otherwise, code execution
continues or resumes without branching (see
Section 9.0 “Interrupts”).
A fixed delay of interval TCSD following the wake event
is required when leaving Sleep and Idle modes. This
delay is required for the CPU to prepare for execution.
Instruction execution resumes on the first clock cycle
following this delay.
3.5.2 EXIT BY WDT TIME-OUT
A WDT time-out will cause different actions depending
on which power-managed mode the device is in when
the time-out occurs.
If the device is not executing code (all Idle modes and
Sleep mode), the time-out will result in an exit from the
power-managed mode (see Section 3.2 “Run
Modes” and Section 3.3 “Sleep Mode”). If the device
is executing code (all Run modes), the time-out will
result in a WDT Reset (see Section 23.2 “Watchdog
Timer (WDT)”).
The WDT timer and postscaler are cleared by
executing a SLEEP or CLRWDT instruction, the loss of a
currently selected clock source (if the Fail-Safe Clock
Monitor is enabled) and modifying the IRCF bits in the
OSCCON register if the internal oscillator block is the
device clock source.
3.5.3 EXIT BY RESET
Normally, the device is held in Reset by the Oscillator
Start-up Timer (OST) until the primary clock becomes
ready. At that time, the OSTS bit is set and the device
begins executing code. If the internal oscillator block is
the new clock source, the IOFS bit is set instead.
The exit delay time from Reset to the start of code
execution depends on both the clock sources before
and after the wake-up and the type of oscillator if the
new clock source is the primary clock. Exit delays are
summarized in Table 3-2.
Code execution can begin before the primary clock
becomes ready. If either the Two-Speed Start-up (see
Section 23.3 “Two-Speed Start-up”) or Fail-Safe
Clock Monitor (see Section 23.4 “Fail-Safe Clock
Monitor”) is enabled, the device may begin execution
as soon as the Reset source has cleared. Execution is
clocked by the INTOSC multiplexer driven by the internal
oscillator block. Execution is clocked by the internal
oscillator block until either the primary clock becomes
ready or a power-managed mode is entered before the
primary clock becomes ready; the primary clock is then
shut down.PIC18F2420/2520/4420/4520
DS39631E-page 40 Advance Information © 2008 Microchip Technology Inc.
3.5.4 EXIT WITHOUT AN OSCILLATOR
START-UP DELAY
Certain exits from power-managed modes do not
invoke the OST at all. There are two cases:
• PRI_IDLE mode, where the primary clock source
is not stopped and
• the primary clock source is not any of the LP, XT,
HS or HSPLL modes.
In these instances, the primary clock source either
does not require an oscillator start-up delay, since it is
already running (PRI_IDLE), or normally does not
require an oscillator start-up delay (RC, EC and INTIO
Oscillator modes). However, a fixed delay of interval
TCSD following the wake event is still required when
leaving Sleep and Idle modes to allow the CPU to
prepare for execution. Instruction execution resumes
on the first clock cycle following this delay.
TABLE 3-2: EXIT DELAY ON WAKE-UP BY RESET FROM SLEEP MODE OR ANY IDLE MODE
(BY CLOCK SOURCES)
Clock Source
Before Wake-up
Clock Source
After Wake-up Exit Delay Clock Ready Status
Bit (OSCCON)
Primary Device Clock
(PRI_IDLE mode)
LP, XT, HS
TCSD
HSPLL (1) OSTS
EC, RC
INTOSC(2) IOFS
T1OSC or INTRC(1)
LP, XT, HS TOST(3)
HSPLL TOST + trc OSTS (3)
EC, RC TCSD(1)
INTOSC(2) TCSD(1) IOFS
INTOSC(2)
LP, XT, HS TOST(3)
HSPLL TOST + trc OSTS (3)
EC, RC TCSD(1)
INTOSC(2) TCSD(1) IOFS
None
(Sleep mode)
LP, XT, HS TOST(3)
HSPLL TOST + trc OSTS (3)
EC, RC TCSD(1)
INTOSC(2) TCSD(1) IOFS
Note 1: TCSD (parameter 38) is a required delay when waking from Sleep and all Idle modes and runs concurrently
with any other required delays (see Section 3.4 “Idle Modes”). On Reset, INTOSC defaults to 1 MHz.
2: Includes both the INTOSC 8 MHz source and postscaler derived frequencies.
3: TOST is the Oscillator Start-up Timer (parameter 32). trc is the PLL lock-out timer (parameter F12); it is also
designated as TPLL.© 2008 Microchip Technology Inc. DS39631E-page 41
PIC18F2420/2520/4420/4520
4.0 RESET
The PIC18F2420/2520/4420/4520 devices differentiate
between various kinds of Reset:
a) Power-on Reset (POR)
b) MCLR Reset during normal operation
c) MCLR Reset during power-managed modes
d) Watchdog Timer (WDT) Reset (during
execution)
e) Programmable Brown-out Reset (BOR)
f) RESET Instruction
g) Stack Full Reset
h) Stack Underflow Reset
This section discusses Resets generated by MCLR,
POR and BOR and covers the operation of the various
start-up timers. Stack Reset events are covered in
Section 5.1.2.4 “Stack Full and Underflow Resets”.
WDT Resets are covered in Section 23.2 “Watchdog
Timer (WDT)”.
A simplified block diagram of the On-Chip Reset Circuit
is shown in Figure 4-1.
4.1 RCON Register
Device Reset events are tracked through the RCON
register (Register 4-1). The lower five bits of the register
indicate that a specific Reset event has occurred. In
most cases, these bits can only be cleared by the event
and must be set by the application after the event. The
state of these flag bits, taken together, can be read to
indicate the type of Reset that just occurred. This is
described in more detail in Section 4.6 “Reset State
of Registers”.
The RCON register also has control bits for setting
interrupt priority (IPEN) and software control of the
BOR (SBOREN). Interrupt priority is discussed in
Section 9.0 “Interrupts”. BOR is covered in
Section 4.4 “Brown-out Reset (BOR)”.
FIGURE 4-1: SIMPLIFIED BLOCK DIAGRAM OF ON-CHIP RESET CIRCUIT
External Reset
MCLR
VDD
OSC1
WDT
Time-out
VDD Rise
Detect
OST/PWRT
INTRC(1)
POR Pulse
OST
10-Bit Ripple Counter
PWRT
11-Bit Ripple Counter
Enable OST(2)
Enable PWRT
Note 1: This is the INTRC source from the internal oscillator block and is separate from the RC oscillator of the CLKI pin.
2: See Table 4-2 for time-out situations.
Brown-out
Reset
BOREN
RESET
Instruction
Stack
Pointer
Stack Full/Underflow Reset
Sleep
( )_IDLE
1024 Cycles
65.5 ms 32 μs
MCLRE
S
R Q
Chip_ResetPIC18F2420/2520/4420/4520
DS39631E-page 42 © 2008 Microchip Technology Inc.
REGISTER 4-1: RCON: RESET CONTROL REGISTER
R/W-0 R/W-1(1) U-0 R/W-1 R-1 R-1 R/W-0(2) R/W-0
IPEN SBOREN — RI TO PD POR BOR
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6 SBOREN: BOR Software Enable bit(1)
If BOREN1:BOREN0 = 01:
1 = BOR is enabled
0 = BOR is disabled
If BOREN1:BOREN0 = 00, 10 or 11:
Bit is disabled and read as ‘0’.
bit 5 Unimplemented: Read as ‘0’
bit 4 RI: RESET Instruction Flag bit
1 = The RESET instruction was not executed (set by firmware only)
0 = The RESET instruction was executed causing a device Reset (must be set in software after a
Brown-out Reset occurs)
bit 3 TO: Watchdog Time-out Flag bit
1 = Set by power-up, CLRWDT instruction or SLEEP instruction
0 = A WDT time-out occurred
bit 2 PD: Power-Down Detection Flag bit
1 = Set by power-up or by the CLRWDT instruction
0 = Set by execution of the SLEEP instruction
bit 1 POR: Power-on Reset Status bit
1 = A Power-on Reset has not occurred (set by firmware only)
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 = A Brown-out Reset has not occurred (set by firmware only)
0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset occurs)
Note 1: If SBOREN is enabled, its Reset state is ‘1’; otherwise, it is ‘0’.
2: The actual Reset value of POR is determined by the type of device Reset. See the notes following this
register and Section 4.6 “Reset State of Registers” for additional information.
Note 1: 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.
2: Brown-out Reset is said to have occurred when BOR is ‘0’ and POR is ‘1’ (assuming that POR was set to
‘1’ by software immediately after a Power-on Reset).© 2008 Microchip Technology Inc. DS39631E-page 43
PIC18F2420/2520/4420/4520
4.2 Master Clear (MCLR)
The MCLR pin provides a method for triggering an
external Reset of the device. A Reset is generated by
holding the pin low. These devices have a noise filter in
the MCLR Reset path which detects and ignores small
pulses.
The MCLR pin is not driven low by any internal Resets,
including the WDT.
In PIC18F2420/2520/4420/4520 devices, the MCLR
input can be disabled with the MCLRE Configuration
bit. When MCLR is disabled, the pin becomes a digital
input. See Section 10.5 “PORTE, TRISE and LATE
Registers” for more information.
4.3 Power-on Reset (POR)
A Power-on Reset pulse is generated on-chip
whenever VDD rises above a certain threshold. This
allows the device to start in the initialized state when
VDD is adequate for operation.
To take advantage of the POR circuitry, tie the MCLR
pin through a resistor (1 kΩ to 10 kΩ) to VDD. This will
eliminate external RC components usually needed to
create a Power-on Reset delay. A minimum rise rate for
VDD is specified (parameter D004). For a slow rise
time, see Figure 4-2.
When the device starts normal operation (i.e., exits the
Reset condition), device operating parameters (voltage,
frequency, temperature, etc.) must be met to
ensure operation. If these conditions are not met, the
device must be held in Reset until the operating
conditions are met.
POR events are captured by the POR bit (RCON<1>).
The state of the bit is set to ‘0’ whenever a POR occurs;
it does not change for any other Reset event. POR is
not reset to ‘1’ by any hardware event. To capture
multiple events, the user manually resets the bit to ‘1’
in software following any POR.
FIGURE 4-2: EXTERNAL POWER-ON
RESET CIRCUIT (FOR
SLOW VDD POWER-UP)
Note 1: External Power-on Reset circuit is required
only if the VDD power-up slope is too slow.
The diode D helps discharge the capacitor
quickly when VDD powers down.
2: R < 40 kΩ is recommended to make sure that
the voltage drop across R does not violate
the device’s electrical specification.
3: R1 ≥ 1 kΩ will limit any current flowing into
MCLR from external capacitor C, in the event
of MCLR/VPP pin breakdown, due to
Electrostatic Discharge (ESD) or Electrical
Overstress (EOS).
C
R1
D R
VDD
MCLR
PIC18FXXXX
VDDPIC18F2420/2520/4420/4520
DS39631E-page 44 © 2008 Microchip Technology Inc.
4.4 Brown-out Reset (BOR)
PIC18F2420/2520/4420/4520 devices implement a
BOR circuit that provides the user with a number of
configuration and power-saving options. The BOR is
controlled by the BORV<1:0> and BOREN<1:0>
Configuration bits. There are a total of four BOR
configurations which are summarized in Table 4-1.
The BOR threshold is set by the BORV<1:0> bits. If BOR
is enabled (any values of BOREN<1:0>, except ‘00’),
any drop of VDD below VBOR (parameter D005) for
greater than TBOR (parameter 35) will reset the device.
A Reset may or may not occur if VDD falls below VBOR
for less than TBOR. The chip will remain in Brown-out
Reset until VDD rises above VBOR.
If the Power-up Timer is enabled, it will be invoked after
VDD rises above VBOR; it then will keep the chip in
Reset for an additional time delay, TPWRT
(parameter 33). If VDD drops below VBOR while the
Power-up Timer is running, the chip will go back into a
Brown-out Reset and the Power-up Timer will be
initialized. Once VDD rises above VBOR, the Power-up
Timer will execute the additional time delay.
BOR and the Power-up Timer (PWRT) are
independently configured. Enabling the Brown-out
Reset does not automatically enable the PWRT.
4.4.1 SOFTWARE ENABLED BOR
When BOREN<1:0> = 01, the BOR can be enabled or
disabled by the user in software. This is done with the
control bit, SBOREN (RCON<6>). Setting SBOREN
enables the BOR to function as previously described.
Clearing SBOREN disables the BOR entirely. The
SBOREN bit operates only in this mode; otherwise it is
read as ‘0’.
Placing the BOR under software control gives the user
the additional flexibility of tailoring the application to its
environment without having to reprogram the device to
change BOR configuration. It also allows the user to
tailor device power consumption in software by eliminating
the incremental current that the BOR consumes.
While the BOR current is typically very small, it may
have some impact in low-power applications.
4.4.2 DETECTING BOR
When BOR is enabled, the BOR bit always resets to ‘0’
on any BOR or POR event. This makes it difficult to
determine if a BOR event has occurred just by reading
the state of BOR alone. A more reliable method is to
simultaneously check the state of both POR and BOR.
This assumes that the POR bit is reset to ‘1’ in software
immediately after any POR event. If BOR is ‘0’ while
POR is ‘1’, it can be reliably assumed that a BOR event
has occurred.
4.4.3 DISABLING BOR IN SLEEP MODE
When BOREN<1:0> = 10, the BOR remains under
hardware control and operates as previously
described. Whenever the device enters Sleep mode,
however, the BOR is automatically disabled. When the
device returns to any other operating mode, BOR is
automatically re-enabled.
This mode allows for applications to recover from
brown-out situations, while actively executing code,
when the device requires BOR protection the most. At
the same time, it saves additional power in Sleep mode
by eliminating the small incremental BOR current.
TABLE 4-1: BOR CONFIGURATIONS
Note: Even when BOR is under software control,
the Brown-out Reset voltage level is still
set by the BORV<1:0> Configuration bits;
it cannot be changed in software.
BOR Configuration Status of
SBOREN
(RCON<6>)
BOR Operation
BOREN1 BOREN0
0 0 Unavailable BOR disabled; must be enabled by reprogramming the Configuration bits.
0 1 Available BOR enabled in software; operation controlled by SBOREN.
1 0 Unavailable BOR enabled in hardware in Run and Idle modes, disabled during
Sleep mode.
1 1 Unavailable BOR enabled in hardware; must be disabled by reprogramming the
Configuration bits.© 2008 Microchip Technology Inc. DS39631E-page 45
PIC18F2420/2520/4420/4520
4.5 Device Reset Timers
PIC18F2420/2520/4420/4520 devices incorporate three
separate on-chip timers that help regulate the Power-on
Reset process. Their main function is to ensure that the
device clock is stable before code is executed. These
timers are:
• Power-up Timer (PWRT)
• Oscillator Start-up Timer (OST)
• PLL Lock Time-out
4.5.1 POWER-UP TIMER (PWRT)
The Power-up Timer (PWRT) of PIC18F2420/2520/
4420/4520 devices is an 11-bit counter which uses
the INTRC source as the clock input. This yields an
approximate time interval of 2048 x 32 μs = 65.6 ms.
While the PWRT is counting, the device is held in
Reset.
The power-up time delay depends on the INTRC clock
and will vary from chip to chip due to temperature and
process variation. See DC parameter 33 for details.
The PWRT is enabled by clearing the PWRTEN
Configuration bit.
4.5.2 OSCILLATOR START-UP TIMER
(OST)
The Oscillator Start-up Timer (OST) provides a
1024 oscillator cycle (from OSC1 input) delay after the
PWRT delay is over (parameter 33). This ensures that
the crystal oscillator or resonator has started and
stabilized.
The OST time-out is invoked only for XT, LP, HS and
HSPLL modes and only on Power-on Reset, or on exit
from most power-managed modes.
4.5.3 PLL LOCK TIME-OUT
With the PLL enabled in its PLL mode, the time-out
sequence following a Power-on Reset is slightly different
from other oscillator modes. A separate timer is
used to provide a fixed time-out that is sufficient for the
PLL to lock to the main oscillator frequency. This PLL
lock time-out (TPLL) is typically 2 ms and follows the
oscillator start-up time-out.
4.5.4 TIME-OUT SEQUENCE
On power-up, the time-out sequence is as follows:
1. After the POR pulse has cleared, PWRT time-out
is invoked (if enabled).
2. Then, the OST is activated.
The total time-out will vary based on oscillator configuration
and the status of the PWRT. Figure 4-3,
Figure 4-4, Figure 4-5, Figure 4-6 and Figure 4-7 all
depict time-out sequences on power-up, with the
Power-up Timer enabled and the device operating in
HS Oscillator mode. Figure 4-3 through Figure 4-6 also
apply to devices operating in XT or LP modes. For
devices in RC mode and with the PWRT disabled, on
the other hand, there will be no time-out at all.
Since the time-outs occur from the POR pulse, if MCLR
is kept low long enough, all time-outs will expire. Bringing
MCLR high will begin execution immediately
(Figure 4-5). This is useful for testing purposes or to
synchronize more than one PIC18FXXXX device
operating in parallel.
TABLE 4-2: TIME-OUT IN VARIOUS SITUATIONS
Oscillator
Configuration
Power-up(2) and Brown-out Exit from
Power-Managed Mode PWRTEN = 0 PWRTEN = 1
HSPLL 66 ms(1) + 1024 TOSC + 2 ms(2) 1024 TOSC + 2 ms(2) 1024 TOSC + 2 ms(2)
HS, XT, LP 66 ms(1) + 1024 TOSC 1024 TOSC 1024 TOSC
EC, ECIO 66 ms(1) — —
RC, RCIO 66 ms(1) — —
INTIO1, INTIO2 66 ms(1) — —
Note 1: 66 ms (65.5 ms) is the nominal Power-up Timer (PWRT) delay.
2: 2 ms is the nominal time required for the PLL to lock.PIC18F2420/2520/4420/4520
DS39631E-page 46 © 2008 Microchip Technology Inc.
FIGURE 4-3: TIME-OUT SEQUENCE ON POWER-UP (MCLR TIED TO VDD, VDD RISE < TPWRT)
FIGURE 4-4: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 1
FIGURE 4-5: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 2
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST© 2008 Microchip Technology Inc. DS39631E-page 47
PIC18F2420/2520/4420/4520
FIGURE 4-6: SLOW RISE TIME (MCLR TIED TO VDD, VDD RISE > TPWRT)
FIGURE 4-7: TIME-OUT SEQUENCE ON POR W/PLL ENABLED (MCLR TIED TO VDD)
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
0V
5V
TPWRT
TOST
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
PLL TIME-OUT
TPLL
Note: TOST = 1024 clock cycles.
TPLL ≈ 2 ms max. First three stages of the PWRT timer.PIC18F2420/2520/4420/4520
DS39631E-page 48 © 2008 Microchip Technology Inc.
4.6 Reset State of Registers
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” depending on the type of Reset that occurred.
Most registers are not affected by a WDT wake-up,
since this is viewed as the resumption of normal operation.
Status bits from the RCON register, RI, TO, PD,
POR and BOR, are set or cleared differently in different
Reset situations, as indicated in Table 4-3. These bits
are used in software to determine the nature of the
Reset.
Table 4-4 describes the Reset states for all of the
Special Function Registers. These are categorized by
Power-on and Brown-out Resets, Master Clear and
WDT Resets and WDT wake-ups.
TABLE 4-3: STATUS BITS, THEIR SIGNIFICANCE AND THE INITIALIZATION CONDITION
FOR RCON REGISTER
Condition Program
Counter
RCON Register STKPTR Register
RI TO PD POR BOR STKFUL STKUNF
Power-on Reset 0000h 11100 0 0
RESET Instruction 0000h 0uuuu u u
Brown-out Reset 0000h 111u0 u u
MCLR Reset during Power-Managed
Run Modes
0000h u1uuu u u
MCLR Reset during Power-Managed
Idle Modes and Sleep Mode
0000h u10uu u u
WDT Time-out during Full Power or
Power-Managed Run Mode
0000h u0uuu u u
MCLR Reset during Full-Power
Execution
0000h uuuuu u u
Stack Full Reset (STVREN = 1) 0000h uuuuu 1 u
Stack Underflow Reset (STVREN = 1) 0000h uuuuu u 1
Stack Underflow Error (not an actual
Reset, STVREN = 0)
0000h uuuuu u 1
WDT Time-out during
Power-Managed Idle or Sleep Modes
PC + 2 u00uu u u
Interrupt Exit from Power-Managed
Modes
PC + 2(1) uu0uu u u
Legend: u = unchanged
Note 1: When the wake-up is due to an interrupt and the GIEH or GIEL bits are set, the PC is loaded with the
interrupt vector (008h or 0018h).© 2008 Microchip Technology Inc. DS39631E-page 49
PIC18F2420/2520/4420/4520
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets,
WDT Reset,
RESET Instruction,
Stack Resets
Wake-up via WDT
or Interrupt
TOSU 2420 2520 4420 4520 ---0 0000 ---0 0000 ---0 uuuu(3)
TOSH 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu(3)
TOSL 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu(3)
STKPTR 2420 2520 4420 4520 00-0 0000 uu-0 0000 uu-u uuuu(3)
PCLATU 2420 2520 4420 4520 ---0 0000 ---0 0000 ---u uuuu
PCLATH 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
PCL 2420 2520 4420 4520 0000 0000 0000 0000 PC + 2(2)
TBLPTRU 2420 2520 4420 4520 --00 0000 --00 0000 --uu uuuu
TBLPTRH 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TBLPTRL 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TABLAT 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
PRODH 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
PRODL 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
INTCON 2420 2520 4420 4520 0000 000x 0000 000u uuuu uuuu(1)
INTCON2 2420 2520 4420 4520 1111 -1-1 1111 -1-1 uuuu -u-u(1)
INTCON3 2420 2520 4420 4520 11-0 0-00 11-0 0-00 uu-u u-uu(1)
INDF0 2420 2520 4420 4520 N/A N/A N/A
POSTINC0 2420 2520 4420 4520 N/A N/A N/A
POSTDEC0 2420 2520 4420 4520 N/A N/A N/A
PREINC0 2420 2520 4420 4520 N/A N/A N/A
PLUSW0 2420 2520 4420 4520 N/A N/A N/A
FSR0H 2420 2520 4420 4520 ---- 0000 ---- 0000 ---- uuuu
FSR0L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
WREG 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
INDF1 2420 2520 4420 4520 N/A N/A N/A
POSTINC1 2420 2520 4420 4520 N/A N/A N/A
POSTDEC1 2420 2520 4420 4520 N/A N/A N/A
PREINC1 2420 2520 4420 4520 N/A N/A N/A
PLUSW1 2420 2520 4420 4520 N/A N/A N/A
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
(0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
4: See Table 4-3 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled depending on the oscillator mode selected. When not enabled as
PORTA pins, they are disabled and read ‘0’.
6: The Reset value of the PCFG bits depends on the value of the PBADEN Configuration bit (CONFIG3H<1>). When
PBADEN = 1, PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.PIC18F2420/2520/4420/4520
DS39631E-page 50 © 2008 Microchip Technology Inc.
FSR1H 2420 2520 4420 4520 ---- 0000 ---- 0000 ---- uuuu
FSR1L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
BSR 2420 2520 4420 4520 ---- 0000 ---- 0000 ---- uuuu
INDF2 2420 2520 4420 4520 N/A N/A N/A
POSTINC2 2420 2520 4420 4520 N/A N/A N/A
POSTDEC2 2420 2520 4420 4520 N/A N/A N/A
PREINC2 2420 2520 4420 4520 N/A N/A N/A
PLUSW2 2420 2520 4420 4520 N/A N/A N/A
FSR2H 2420 2520 4420 4520 ---- 0000 ---- 0000 ---- uuuu
FSR2L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
STATUS 2420 2520 4420 4520 ---x xxxx ---u uuuu ---u uuuu
TMR0H 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TMR0L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
T0CON 2420 2520 4420 4520 1111 1111 1111 1111 uuuu uuuu
OSCCON 2420 2520 4420 4520 0100 q000 0100 q000 uuuu quuu
HLVDCON 2420 2520 4420 4520 0-00 0101 0-00 0101 u-uu uuuu
WDTCON 2420 2520 4420 4520 ---- ---0 ---- ---0 ---- ---u
RCON(4) 2420 2520 4420 4520 0q-1 11q0 0q-q qquu uq-u qquu
TMR1H 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
TMR1L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
T1CON 2420 2520 4420 4520 0000 0000 u0uu uuuu uuuu uuuu
TMR2 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
PR2 2420 2520 4420 4520 1111 1111 1111 1111 1111 1111
T2CON 2420 2520 4420 4520 -000 0000 -000 0000 -uuu uuuu
SSPBUF 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
SSPADD 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
SSPSTAT 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
SSPCON1 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
SSPCON2 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets,
WDT Reset,
RESET Instruction,
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
(0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
4: See Table 4-3 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled depending on the oscillator mode selected. When not enabled as
PORTA pins, they are disabled and read ‘0’.
6: The Reset value of the PCFG bits depends on the value of the PBADEN Configuration bit (CONFIG3H<1>). When
PBADEN = 1, PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.© 2008 Microchip Technology Inc. DS39631E-page 51
PIC18F2420/2520/4420/4520
ADRESH 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
ADRESL 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
ADCON0 2420 2520 4420 4520 --00 0000 --00 0000 --uu uuuu
ADCON1 2420 2520 4420 4520 --00 0qqq(6) --00 0qqq(6) --uu uuuu
ADCON2 2420 2520 4420 4520 0-00 0000 0-00 0000 u-uu uuuu
CCPR1H 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
CCPR1L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
CCP1CON
2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
2420 2520 4420 4520 --00 0000 --00 0000 --uu uuuu
CCPR2H 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
CCPR2L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
CCP2CON 2420 2520 4420 4520 --00 0000 --00 0000 --uu uuuu
BAUDCON 2420 2520 4420 4520 0100 0-00 0100 0-00 uuuu u-uu
PWM1CON 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
ECCP1AS
2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
2420 2520 4420 4520 0000 00-- 0000 00-- uuuu uu--
CVRCON 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
CMCON 2420 2520 4420 4520 0000 0111 0000 0111 uuuu uuuu
TMR3H 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
TMR3L 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
T3CON 2420 2520 4420 4520 0000 0000 uuuu uuuu uuuu uuuu
SPBRGH 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
SPBRG 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
RCREG 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TXREG 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
TXSTA 2420 2520 4420 4520 0000 0010 0000 0010 uuuu uuuu
RCSTA 2420 2520 4420 4520 0000 000x 0000 000x uuuu uuuu
EEADR 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
EEDATA 2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
EECON2 2420 2520 4420 4520 0000 0000 0000 0000 0000 0000
EECON1 2420 2520 4420 4520 xx-0 x000 uu-0 u000 uu-0 u000
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets,
WDT Reset,
RESET Instruction,
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
(0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
4: See Table 4-3 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled depending on the oscillator mode selected. When not enabled as
PORTA pins, they are disabled and read ‘0’.
6: The Reset value of the PCFG bits depends on the value of the PBADEN Configuration bit (CONFIG3H<1>). When
PBADEN = 1, PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.PIC18F2420/2520/4420/4520
DS39631E-page 52 © 2008 Microchip Technology Inc.
IPR2 2420 2520 4420 4520 11-1 1111 11-1 1111 uu-u uuuu
PIR2 2420 2520 4420 4520 00-0 0000 00-0 0000 uu-u uuuu(1)
PIE2 2420 2520 4420 4520 00-0 0000 00-0 0000 uu-u uuuu
IPR1
2420 2520 4420 4520 1111 1111 1111 1111 uuuu uuuu
2420 2520 4420 4520 -111 1111 -111 1111 -uuu uuuu
PIR1
2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu(1)
2420 2520 4420 4520 -000 0000 -000 0000 -uuu uuuu(1)
PIE1
2420 2520 4420 4520 0000 0000 0000 0000 uuuu uuuu
2420 2520 4420 4520 -000 0000 -000 0000 -uuu uuuu
OSCTUNE 2420 2520 4420 4520 00-0 0000 00-0 0000 uu-u uuuu
TRISE 2420 2520 4420 4520 0000 -111 0000 -111 uuuu -uuu
TRISD 2420 2520 4420 4520 1111 1111 1111 1111 uuuu uuuu
TRISC 2420 2520 4420 4520 1111 1111 1111 1111 uuuu uuuu
TRISB 2420 2520 4420 4520 1111 1111 1111 1111 uuuu uuuu
TRISA(5) 2420 2520 4420 4520 1111 1111(5) 1111 1111(5) uuuu uuuu(5)
LATE 2420 2520 4420 4520 ---- -xxx ---- -uuu ---- -uuu
LATD 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
LATC 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
LATB 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
LATA(5) 2420 2520 4420 4520 xxxx xxxx(5) uuuu uuuu(5) uuuu uuuu(5)
PORTE 2420 2520 4420 4520 ---- xxxx ---- uuuu ---- uuuu
PORTD 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
PORTC 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
PORTB 2420 2520 4420 4520 xxxx xxxx uuuu uuuu uuuu uuuu
PORTA(5) 2420 2520 4420 4520 xx0x 0000(5) uu0u 0000(5) uuuu uuuu(5)
TABLE 4-4: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets,
WDT Reset,
RESET Instruction,
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as ‘0’, q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt vector
(0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are updated with
the current value of the PC. The STKPTR is modified to point to the next location in the hardware stack.
4: See Table 4-3 for Reset value for specific condition.
5: Bits 6 and 7 of PORTA, LATA and TRISA are enabled depending on the oscillator mode selected. When not enabled as
PORTA pins, they are disabled and read ‘0’.
6: The Reset value of the PCFG bits depends on the value of the PBADEN Configuration bit (CONFIG3H<1>). When
PBADEN = 1, PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.© 2008 Microchip Technology Inc. DS39631E-page 53
PIC18F2420/2520/4420/4520
5.0 MEMORY ORGANIZATION
There are three types of memory in PIC18 enhanced
microcontroller devices:
• Program Memory
• Data RAM
• Data EEPROM
As Harvard architecture devices, the data and program
memories use separate busses; this allows for concurrent
access of the two memory spaces. The data
EEPROM, for practical purposes, can be regarded as
a peripheral device, since it is addressed and accessed
through a set of control registers.
Additional detailed information on the operation of the
Flash program memory is provided in Section 6.0
“Flash Program Memory”. Data EEPROM is
discussed separately in Section 7.0 “Data EEPROM
Memory”.
5.1 Program Memory Organization
PIC18 microcontrollers implement a 21-bit program
counter, which is capable of addressing a 2-Mbyte
program memory space. Accessing a location between
the upper boundary of the physically implemented
memory and the 2-Mbyte address will return all ‘0’s (a
NOP instruction).
The PIC18F2420 and PIC18F4420 each have 16 Kbytes
of Flash memory and can store up to 8,192 single-word
instructions. The PIC18F2520 and PIC18F4520 each
have 32 Kbytes of Flash memory and can store up to
16,384 single-word instructions.
PIC18 devices have two interrupt vectors. The Reset
vector address is at 0000h and the interrupt vector
addresses are at 0008h and 0018h.
The program memory map for PIC18F2420/2520/
4420/4520 devices is shown in Figure 5-1.
FIGURE 5-1: PROGRAM MEMORY MAP AND STACK FOR
PIC18F2420/2520/4420/4520 DEVICES
PC<20:0>
Stack Level 1 •
Stack Level 31
Reset Vector
Low-Priority Interrupt Vector
•
•
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
On-Chip
Program Memory
High-Priority Interrupt Vector 0008h
User Memory Space
1FFFFFh
4000h
3FFFh
Read ‘0’
200000h
8000h
7FFFh
On-Chip
Program Memory
Read ‘0’
PIC18F2420/4420
PIC18F2520/4520PIC18F2420/2520/4420/4520
DS39631E-page 54 © 2008 Microchip Technology Inc.
5.1.1 PROGRAM COUNTER
The Program Counter (PC) specifies the address of the
instruction to fetch for execution. The PC is 21 bits wide
and is contained in three separate 8-bit registers. The
low byte, known as the PCL register, is both readable
and writable. The high byte, or PCH register, contains
the PC<15:8> bits; it is not directly readable or writable.
Updates to the PCH register are performed through the
PCLATH register. The upper byte is called PCU. This
register contains the PC<20:16> bits; it is also not
directly readable or writable. Updates to the PCU
register are performed through the PCLATU register.
The contents of PCLATH and PCLATU are transferred
to the program counter by any operation that writes
PCL. Similarly, the upper two bytes of the program
counter are transferred to PCLATH and PCLATU by an
operation that reads PCL. This is useful for computed
offsets to the PC (see Section 5.1.4.1 “Computed
GOTO”).
The PC addresses bytes in the program memory. To
prevent the PC from becoming misaligned with word
instructions, the Least Significant bit of PCL is fixed to
a value of ‘0’. The PC increments by 2 to address
sequential instructions in the program memory.
The CALL, RCALL, GOTO and program branch
instructions write to the program counter directly. For
these instructions, the contents of PCLATH and
PCLATU are not transferred to the program counter.
5.1.2 RETURN ADDRESS STACK
The return address stack allows any combination of up
to 31 program calls and interrupts to occur. The PC 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 or CALL instructions.
The stack operates as a 31-word by 21-bit RAM and a
5-bit Stack Pointer, STKPTR. The stack space is not
part of either program or data space. The Stack Pointer
is readable and writable and the address on the top of
the stack is readable and writable through the Top-ofStack
(TOS) Special Function Registers. Data can also
be pushed to, or popped from the stack, using these
registers.
A CALL type instruction causes a push onto the stack;
the Stack Pointer is first incremented and the location
pointed to by the Stack Pointer is written with the
contents of the PC (already pointing to the instruction
following the CALL). A RETURN type instruction causes
a pop from the stack; the contents of the location
pointed to by the STKPTR are transferred to the PC
and then the Stack Pointer is decremented.
The Stack Pointer is initialized to ‘00000’ after all
Resets. There is no RAM associated with the location
corresponding to a Stack Pointer value of ‘00000’; this
is only a Reset value. Status bits indicate if the stack is
full, or has overflowed or underflowed.
5.1.2.1 Top-of-Stack Access
Only the top of the return address stack (TOS) is
readable and writable. A set of three registers,
TOSU:TOSH:TOSL, hold the contents of the stack location
pointed to by the STKPTR register (Figure 5-2). This
allows users to implement a software stack if necessary.
After a CALL, RCALL or interrupt, the software can read
the pushed value by reading the TOSU:TOSH:TOSL
registers. These values can be placed on a user-defined
software stack. At return time, the software can return
these values to TOSU:TOSH:TOSL and do a return.
The user must disable the global interrupt enable bits
while accessing the stack to prevent inadvertent stack
corruption.
FIGURE 5-2: RETURN ADDRESS STACK AND ASSOCIATED REGISTERS
00011
001A34h
11111
11110
11101
00010
00001
00000
00010
Return Address Stack <20:0>
Top-of-Stack
000D58h
TOSU TOSH TOSL
00h 1Ah 34h
STKPTR<4:0>
Top-of-Stack Registers Stack Pointer© 2008 Microchip Technology Inc. DS39631E-page 55
PIC18F2420/2520/4420/4520
5.1.2.2 Return Stack Pointer (STKPTR)
The STKPTR register (Register 5-1) contains the Stack
Pointer value, the STKFUL (Stack Full) status bit and
the STKUNF (Stack Underflow) status bits. The value
of the Stack Pointer can be 0 through 31. The Stack
Pointer increments before values are pushed onto the
stack and decrements after values are popped off the
stack. On Reset, the Stack Pointer value will be zero.
The user may read and write the Stack Pointer value.
This feature can be used by a Real-Time Operating
System (RTOS) for return stack maintenance.
After the PC is pushed onto the stack 31 times (without
popping any values off the stack), the STKFUL bit is
set. The STKFUL bit is cleared by software or by a
POR.
The action that takes place when the stack becomes
full depends on the state of the STVREN (Stack Overflow
Reset Enable) Configuration bit. (Refer to
Section 23.1 “Configuration Bits” for a description of
the device Configuration bits.) If STVREN is set
(default), the 31st push will push the (PC + 2) value
onto the stack, set the STKFUL bit and reset the
device. The STKFUL bit will remain set and the Stack
Pointer will be set to zero.
If STVREN is cleared, the STKFUL bit will be set on the
31st push and the Stack Pointer will increment to 31.
Any additional pushes will not overwrite the 31st push
and STKPTR will remain at 31.
When the stack has been popped enough times to
unload the stack, the next pop will return a value of zero
to the PC and sets the STKUNF bit, while the Stack
Pointer remains at zero. The STKUNF bit will remain
set until cleared by software or until a POR occurs.
5.1.2.3 PUSH and POP Instructions
Since the Top-of-Stack 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 feature. The PIC18 instruction set
includes two instructions, PUSH and POP, that permit
the TOS to be manipulated under software control.
TOSU, TOSH and TOSL can be modified to place data
or a return address on the stack.
The PUSH instruction places the current PC value onto
the stack. This increments the Stack Pointer and loads
the current PC value onto the stack.
The POP instruction discards the current TOS by decrementing
the Stack Pointer. The previous value pushed
onto the stack then becomes the TOS value.
Note: Returning a value of 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. This is
not the same as a Reset, as the contents
of the SFRs are not affected.
REGISTER 5-1: STKPTR: STACK POINTER REGISTER
R/C-0 R/C-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
STKFUL(1) STKUNF(1) — SP4 SP3 SP2 SP1 SP0
bit 7 bit 0
Legend: C = Clearable bit
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 STKFUL: Stack Full Flag bit(1)
1 = Stack became full or overflowed
0 = Stack has not become full or overflowed
bit 6 STKUNF: Stack Underflow Flag bit(1)
1 = Stack underflow occurred
0 = Stack underflow did not occur
bit 5 Unimplemented: Read as ‘0’
bit 4-0 SP<4:0>: Stack Pointer Location bits
Note 1: Bit 7 and bit 6 are cleared by user software or by a POR.PIC18F2420/2520/4420/4520
DS39631E-page 56 © 2008 Microchip Technology Inc.
5.1.2.4 Stack Full and Underflow Resets
Device Resets on stack overflow and stack underflow
conditions are enabled by setting the STVREN bit in
Configuration Register 4L. When STVREN is set, a full
or underflow will set the appropriate STKFUL or
STKUNF bit and then cause a device Reset. When
STVREN is cleared, a full or underflow condition will set
the appropriate STKFUL or STKUNF bit but not cause
a device Reset. The STKFUL or STKUNF bits are
cleared by the user software or a Power-on Reset.
5.1.3 FAST REGISTER STACK
A Fast Register Stack is provided for the STATUS,
WREG and BSR registers, to provide a “fast return”
option for interrupts. The stack for each register is only
one level deep and is neither readable nor writable. It is
loaded with the current value of the corresponding register
when the processor vectors for an interrupt. All
interrupt sources will push values into the stack registers.
The values in the registers are then loaded back
into their associated registers if the RETFIE, FAST
instruction is used to return from the interrupt.
If both low and high-priority interrupts are enabled, the
stack registers cannot be used reliably to return from
low-priority interrupts. If a high-priority interrupt occurs
while servicing a low-priority interrupt, the stack register
values stored by the low-priority interrupt will be
overwritten. In these cases, users must save the key
registers in software during a low-priority interrupt.
If interrupt priority is not used, all interrupts may use the
Fast Register Stack for returns from 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 CALL label, FAST
instruction must be executed to save the STATUS,
WREG and BSR registers to the Fast Register Stack. A
RETURN, FAST instruction is then executed to restore
these registers from the Fast Register Stack.
Example 5-1 shows a source code example that uses
the Fast Register Stack during a subroutine call and
return.
EXAMPLE 5-1: FAST REGISTER STACK
CODE EXAMPLE
5.1.4 LOOK-UP TABLES IN PROGRAM
MEMORY
There may be programming situations that require the
creation of data structures, or look-up tables, in
program memory. For PIC18 devices, look-up tables
can be implemented in two ways:
• Computed GOTO
• Table Reads
5.1.4.1 Computed GOTO
A computed GOTO is accomplished by adding an offset
to the program counter. An example is shown in
Example 5-2.
A look-up table can be formed with an ADDWF PCL
instruction and a group of RETLW nn instructions. The
W register is loaded with an 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 nn
instructions that returns the value ‘nn’ to the calling
function.
The offset value (in WREG) specifies the number of
bytes that the program counter should advance and
should be multiples of 2 (LSb = 0).
In this method, only one data byte may be stored in
each instruction location and room on the return
address stack is required.
EXAMPLE 5-2: COMPUTED GOTO USING
AN OFFSET VALUE
5.1.4.2 Table Reads and Table Writes
A better method of storing data in program memory
allows two bytes of data to be stored in each instruction
location.
Look-up table data may be stored two bytes per program
word by using table reads and writes. The Table
Pointer (TBLPTR) register specifies the byte address
and the Table Latch (TABLAT) register contains the
data that is read from or written to program memory.
Data is transferred to or from program memory one
byte at a time.
Table read and table write operations are discussed
further in Section 6.1 “Table Reads and Table
Writes”.
CALL SUB1, FAST ;STATUS, WREG, BSR
;SAVED IN FAST REGISTER
;STACK
•
•
SUB1 •
•
RETURN, FAST ;RESTORE VALUES SAVED
;IN FAST REGISTER STACK
MOVF OFFSET, W
CALL TABLE
ORG nn00h
TABLE ADDWF PCL
RETLW nnh
RETLW nnh
RETLW nnh
.
.
.© 2008 Microchip Technology Inc. DS39631E-page 57
PIC18F2420/2520/4420/4520
5.2 PIC18 Instruction Cycle
5.2.1 CLOCKING SCHEME
The microcontroller clock input, whether from an internal
or external source, is internally divided by four to
generate four non-overlapping quadrature clocks (Q1,
Q2, Q3 and Q4). Internally, the program counter is
incremented on every Q1; the instruction is fetched
from the program memory and latched into the instruction
register during Q4. The instruction is decoded and
executed during the following Q1 through Q4. The
clocks and instruction execution flow are shown in
Figure 5-3.
5.2.2 INSTRUCTION FLOW/PIPELINING
An “Instruction Cycle” consists of four Q cycles: Q1
through Q4. The instruction fetch and execute are
pipelined in such a manner that a fetch takes one
instruction cycle, while the decode and execute take
another instruction cycle. However, due to the pipelining,
each instruction effectively executes in one
cycle. If an instruction causes the program counter to
change (e.g., GOTO), then two cycles are required to
complete the instruction (Example 5-3).
A fetch cycle begins with the Program Counter (PC)
incrementing in Q1.
In the execution 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).
FIGURE 5-3: CLOCK/INSTRUCTION CYCLE
EXAMPLE 5-3: INSTRUCTION PIPELINE FLOW
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
Q1
Q2
Q3
Q4
PC
OSC2/CLKO
(RC mode)
PC PC + 2 PC + 4
Fetch INST (PC)
Execute INST (PC – 2)
Fetch INST (PC + 2)
Execute INST (PC)
Fetch INST (PC + 4)
Execute INST (PC + 2)
Internal
Phase
Clock
All instructions are single cycle, except for any program branches. These take two cycles since the fetch instruction
is “flushed” from the pipeline while the new instruction is being fetched and then executed.
TCY0 TCY1 TCY2 TCY3 TCY4 TCY5
1. MOVLW 55h Fetch 1 Execute 1
2. MOVWF PORTB Fetch 2 Execute 2
3. BRA SUB_1 Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP) Fetch 4 Flush (NOP)
5. Instruction @ address SUB_1 Fetch SUB_1 Execute SUB_1PIC18F2420/2520/4420/4520
DS39631E-page 58 © 2008 Microchip Technology Inc.
5.2.3 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). To maintain alignment
with instruction boundaries, the PC increments in steps
of 2 and the LSb will always read ‘0’ (see Section 5.1.1
“Program Counter”).
Figure 5-4 shows an example of how instruction words
are stored in the program memory.
The CALL and GOTO instructions have the absolute program
memory address embedded into the instruction.
Since instructions are always stored on word boundaries,
the data contained in the instruction is a word
address. The word address is written to PC<20:1>,
which accesses the desired byte address in program
memory. Instruction #2 in Figure 5-4 shows how the
instruction GOTO 0006h is encoded in the program
memory. Program branch instructions, which encode a
relative address offset, operate in the same manner. The
offset value stored in a branch instruction represents the
number of single-word instructions that the PC will be
offset by. Section 24.0 “Instruction Set Summary”
provides further details of the instruction set.
FIGURE 5-4: INSTRUCTIONS IN PROGRAM MEMORY
5.2.4 TWO-WORD INSTRUCTIONS
The standard PIC18 instruction set has four two-word
instructions: CALL, MOVFF, GOTO and LSFR. In all
cases, the second word of the instructions always has
‘1111’ as its four Most Significant bits; the other 12 bits
are literal data, usually a data memory address.
The use of ‘1111’ in the 4 MSbs of an instruction specifies
a special form of NOP. If the instruction is executed
in proper sequence – immediately after the first word –
the data in the second word is accessed and used by
the instruction sequence. If the first word is skipped for
some reason and the second word is executed by itself,
a NOP is executed instead. This is necessary for cases
when the two-word instruction is preceded by a conditional
instruction that changes the PC. Example 5-4
shows how this works.
EXAMPLE 5-4: TWO-WORD INSTRUCTIONS
Word Address
LSB = 1 LSB = 0 ↓
Program Memory
Byte Locations →
000000h
000002h
000004h
000006h
Instruction 1: MOVLW 055h 0Fh 55h 000008h
Instruction 2: GOTO 0006h EFh 03h 00000Ah
F0h 00h 00000Ch
Instruction 3: MOVFF 123h, 456h C1h 23h 00000Eh
F4h 56h 000010h
000012h
000014h
Note: See Section 5.6 “PIC18 Instruction
Execution and the Extended Instruction
Set” for information on two-word
instructions in the extended instruction set.
CASE 1:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; No, skip this word
1111 0100 0101 0110 ; Execute this word as a NOP
0010 0100 0000 0000 ADDWF REG3 ; continue code
CASE 2:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; Yes, execute this word
1111 0100 0101 0110 ; 2nd word of instruction
0010 0100 0000 0000 ADDWF REG3 ; continue code© 2008 Microchip Technology Inc. DS39631E-page 59
PIC18F2420/2520/4420/4520
5.3 Data Memory Organization
The data memory in PIC18 devices is implemented as
static RAM. Each register in the data memory has a
12-bit address, allowing up to 4096 bytes of data
memory. The memory space is divided into as many as
16 banks that contain 256 bytes each; PIC18F2420/
2520/4420/4520 devices implement all 16 banks.
Figure 5-5 shows the data memory organization for the
PIC18F2420/2520/4420/4520 devices.
The data memory contains Special Function Registers
(SFRs) and General Purpose Registers (GPRs). The
SFRs are used for control and status of the controller
and peripheral functions, while GPRs are used for data
storage and scratchpad operations in the user’s
application. Any read of an unimplemented location will
read as ‘0’s.
The instruction set and architecture allow operations
across all banks. The entire data memory may be
accessed by Direct, Indirect or Indexed Addressing
modes. Addressing modes are discussed later in this
subsection.
To ensure that commonly used registers (SFRs and
select GPRs) can be accessed in a single cycle, PIC18
devices implement an Access Bank. This is a 256-byte
memory space that provides fast access to SFRs and
the lower portion of GPR Bank 0 without using the
BSR. Section 5.3.2 “Access Bank” provides a
detailed description of the Access RAM.
5.3.1 BANK SELECT REGISTER (BSR)
Large areas of data memory require an efficient
addressing scheme to make rapid access to any
address possible. Ideally, this means that an entire
address does not need to be provided for each read or
write operation. For PIC18 devices, this is accomplished
with a RAM banking scheme. This divides the
memory space into 16 contiguous banks of 256 bytes.
Depending on the instruction, each location can be
addressed directly by its full 12-bit address, or an 8-bit
low-order address and a 4-bit Bank Pointer.
Most instructions in the PIC18 instruction set make use
of the Bank Pointer, known as the Bank Select Register
(BSR). This SFR holds the 4 Most Significant bits of a
location’s address; the instruction itself includes the
8 Least Significant bits. Only the four lower bits of the
BSR are implemented (BSR<3:0>). The upper four bits
are unused; they will always read ‘0’ and cannot be
written to. The BSR can be loaded directly by using the
MOVLB instruction.
The value of the BSR indicates the bank in data
memory; the 8 bits in the instruction show the location
in the bank and can be thought of as an offset from the
bank’s lower boundary. The relationship between the
BSR’s value and the bank division in data memory is
shown in Figure 5-7.
Since up to 16 registers may share the same low-order
address, the user must always be careful to ensure that
the proper bank is selected before performing a data
read or write. For example, writing what should be
program data to an 8-bit address of F9h while the BSR
is 0Fh will end up resetting the program counter.
While any bank can be selected, only those banks that
are actually implemented can be read or written to.
Writes to unimplemented banks are ignored, while
reads from unimplemented banks will return ‘0’s. Even
so, the STATUS register will still be affected as if the
operation was successful. The data memory map in
Figure 5-5 indicates which banks are implemented.
In the core PIC18 instruction set, only the MOVFF
instruction fully specifies the 12-bit address of the
source and target registers. This instruction ignores the
BSR completely when it executes. All other instructions
include only the low-order address as an operand and
must use either the BSR or the Access Bank to locate
their target registers.
Note: The operation of some aspects of data
memory are changed when the PIC18
extended instruction set is enabled. See
Section 5.5 “Data Memory and the
Extended Instruction Set” for more
information.PIC18F2420/2520/4420/4520
DS39631E-page 60 © 2008 Microchip Technology Inc.
FIGURE 5-5: DATA MEMORY MAP FOR PIC18F2420/4420 DEVICES
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000
= 0001
= 1111
080h
07Fh
F80h
FFFh
00h
7Fh
80h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored and the
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).
When ‘a’ = 1:
The BSR specifies the Bank
used by the instruction.
F7Fh
F00h
EFFh
1FFh
100h
0FFh
000h Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
Unused
Read 00h
Unused© 2008 Microchip Technology Inc. DS39631E-page 61
PIC18F2420/2520/4420/4520
FIGURE 5-6: DATA MEMORY MAP FOR PIC18F2520/4520 DEVICES
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000
= 0001
= 1111
080h
07Fh
F80h
FFFh
00h
7Fh
80h
FFh
Access Bank
When ‘a’ = 0:
The BSR is ignored and the
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).
When ‘a’ = 1:
The BSR specifies the Bank
used by the instruction.
F7Fh
F00h
EFFh
1FFh
100h
0FFh
000h Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Access RAM High
Access RAM Low
Bank 2
= 0110
= 0010
(SFRs)
2FFh
200h
3FFh
300h
4FFh
400h
5FFh
500h
6FFh
600h
7FFh
700h
8FFh
800h
9FFh
900h
AFFh
A00h
BFFh
B00h
CFFh
C00h
DFFh
D00h
E00h
Bank 3
Bank 4
Bank 5
Bank 6
Bank 7
Bank 8
Bank 9
Bank 10
Bank 11
Bank 12
Bank 13
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
FFh
00h
= 0011
= 0100
= 0101
= 0111
= 1000
= 1001
= 1010
= 1011
= 1100
= 1101
= 1110
Unused
Read 00h
Unused
GPR
GPR
GPRPIC18F2420/2520/4420/4520
DS39631E-page 62 © 2008 Microchip Technology Inc.
FIGURE 5-7: USE OF THE BANK SELECT REGISTER (DIRECT ADDRESSING)
5.3.2 ACCESS BANK
While the use of the BSR with an embedded 8-bit
address allows users to address the entire range of
data memory, it also means that the user must always
ensure that the correct bank is selected. Otherwise,
data may be read from or written to the wrong location.
This can be disastrous if a GPR is the intended target
of an operation, but an SFR is written to instead.
Verifying and/or changing the BSR for each read or
write to data memory can become very inefficient.
To streamline access for the most commonly used data
memory locations, the data memory is configured with
an Access Bank, which allows users to access a
mapped block of memory without specifying a BSR.
The Access Bank consists of the first 128 bytes of
memory (00h-7Fh) in Bank 0 and the last 128 bytes of
memory (80h-FFh) in Block 15. The lower half is known
as the “Access RAM” and is composed of GPRs. This
upper half is also where the device’s SFRs are
mapped. These two areas are mapped contiguously in
the Access Bank and can be addressed in a linear
fashion by an 8-bit address (Figure 5-5).
The Access Bank is used by core PIC18 instructions
that include the Access RAM bit (the ‘a’ parameter in
the instruction). When ‘a’ is equal to ‘1’, the instruction
uses the BSR and the 8-bit address included in the
opcode for the data memory address. When ‘a’ is ‘0’,
however, the instruction is forced to use the Access
Bank address map; the current value of the BSR is
ignored entirely.
Using this “forced” addressing allows the instruction to
operate on a data address in a single cycle, without
updating the BSR first. For 8-bit addresses of 80h and
above, this means that users can evaluate and operate
on SFRs more efficiently. The Access RAM below 80h
is a good place for data values that the user might need
to access rapidly, such as immediate computational
results or common program variables. Access RAM
also allows for faster and more code efficient context
saving and switching of variables.
The mapping of the Access Bank is slightly different
when the extended instruction set is enabled (XINST
Configuration bit = 1). This is discussed in more detail
in Section 5.5.3 “Mapping the Access Bank in
Indexed Literal Offset Mode”.
5.3.3 GENERAL PURPOSE REGISTER
FILE
PIC18 devices may have banked memory in the GPR
area. This is data RAM, which is available for use by all
instructions. GPRs start at the bottom of Bank 0
(address 000h) and grow upwards towards the bottom of
the SFR area. GPRs are not initialized by a Power-on
Reset and are unchanged on all other Resets.
Note 1: The Access RAM bit of the instruction can be used to force an override of the selected bank (BSR<3:0>) to
the registers of the Access Bank.
2: The MOVFF instruction embeds the entire 12-bit address in the instruction.
Data Memory
Bank Select(2)
7 0
From Opcode(2)
0000
000h
100h
200h
300h
F00h
E00h
FFFh
Bank 0
Bank 1
Bank 2
Bank 14
Bank 15
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
Bank 3
through
Bank 13
0011 11111111
7 0
BSR(1)© 2008 Microchip Technology Inc. DS39631E-page 63
PIC18F2420/2520/4420/4520
5.3.4 SPECIAL FUNCTION REGISTERS
The Special Function Registers (SFRs) are registers
used by the CPU and peripheral modules for controlling
the desired operation of the device. These registers are
implemented as static RAM. SFRs start at the top of
data memory (FFFh) and extend downward to occupy
the top half of Bank 15 (F80h to FFFh). A list of these
registers is given in Table 5-1 and Table 5-2.
The SFRs can be classified into two sets: those associated
with the “core” device functionality (ALU, Resets
and interrupts) and those related to the peripheral functions.
The Reset and Interrupt registers are described
in their respective chapters, while the ALU’s STATUS
register is described later in this section. Registers
related to the operation of a peripheral feature are
described in the chapter for that peripheral.
The SFRs are typically distributed among the
peripherals whose functions they control. Unused SFR
locations are unimplemented and read as ‘0’s.
TABLE 5-1: SPECIAL FUNCTION REGISTER MAP FOR PIC18F2420/2520/4420/4520 DEVICES
Address Name Address Name Address Name Address Name
FFFh TOSU FDFh INDF2(1) FBFh CCPR1H F9Fh IPR1
FFEh TOSH FDEh POSTINC2(1) FBEh CCPR1L F9Eh PIR1
FFDh TOSL FDDh POSTDEC2(1) FBDh CCP1CON F9Dh PIE1
FFCh STKPTR FDCh PREINC2(1) FBCh CCPR2H F9Ch —(2)
FFBh PCLATU FDBh PLUSW2(1) FBBh CCPR2L F9Bh OSCTUNE
FFAh PCLATH FDAh FSR2H FBAh CCP2CON F9Ah —(2)
FF9h PCL FD9h FSR2L FB9h —(2) F99h —(2)
FF8h TBLPTRU FD8h STATUS FB8h BAUDCON F98h —(2)
FF7h TBLPTRH FD7h TMR0H FB7h PWM1CON(3) F97h —(2)
FF6h TBLPTRL FD6h TMR0L FB6h ECCP1AS(3) F96h TRISE(3)
FF5h TABLAT FD5h T0CON FB5h CVRCON F95h TRISD(3)
FF4h PRODH FD4h —(2) FB4h CMCON F94h TRISC
FF3h PRODL FD3h OSCCON FB3h TMR3H F93h TRISB
FF2h INTCON FD2h HLVDCON FB2h TMR3L F92h TRISA
FF1h INTCON2 FD1h WDTCON FB1h T3CON F91h —(2)
FF0h INTCON3 FD0h RCON FB0h SPBRGH F90h —(2)
FEFh INDF0(1) FCFh TMR1H FAFh SPBRG F8Fh —(2)
FEEh POSTINC0(1) FCEh TMR1L FAEh RCREG F8Eh —(2)
FEDh POSTDEC0(1) FCDh T1CON FADh TXREG F8Dh LATE(3)
FECh PREINC0(1) FCCh TMR2 FACh TXSTA F8Ch LATD(3)
FEBh PLUSW0(1) FCBh PR2 FABh RCSTA F8Bh LATC
FEAh FSR0H FCAh T2CON FAAh —(2) F8Ah LATB
FE9h FSR0L FC9h SSPBUF FA9h EEADR F89h LATA
FE8h WREG FC8h SSPADD FA8h EEDATA F88h —(2)
FE7h INDF1(1) FC7h SSPSTAT FA7h EECON2(1) F87h —(2)
FE6h POSTINC1(1) FC6h SSPCON1 FA6h EECON1 F86h —(2)
FE5h POSTDEC1(1) FC5h SSPCON2 FA5h —(2) F85h —(2)
FE4h PREINC1(1) FC4h ADRESH FA4h —(2) F84h PORTE(3)
FE3h PLUSW1(1) FC3h ADRESL FA3h —(2) F83h PORTD(3)
FE2h FSR1H FC2h ADCON0 FA2h IPR2 F82h PORTC
FE1h FSR1L FC1h ADCON1 FA1h PIR2 F81h PORTB
FE0h BSR FC0h ADCON2 FA0h PIE2 F80h PORTA
Note 1: This is not a physical register.
2: Unimplemented registers are read as ‘0’.
3: This register is not available on 28-pin devices.PIC18F2420/2520/4420/4520
DS39631E-page 64 © 2008 Microchip Technology Inc.
TABLE 5-2: PIC18F2420/2520/4420/4520 REGISTER FILE SUMMARY
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
TOSU — — — Top-of-Stack Upper Byte (TOS<20:16>) ---0 0000 49, 54
TOSH Top-of-Stack High Byte (TOS<15:8>) 0000 0000 49, 54
TOSL Top-of-Stack Low Byte (TOS<7:0>) 0000 0000 49, 54
STKPTR STKFUL STKUNF — SP4 SP3 SP2 SP1 SP0 00-0 0000 49, 55
PCLATU — — — Holding Register for PC<20:16> ---0 0000 49, 54
PCLATH Holding Register for PC<15:8> 0000 0000 49, 54
PCL PC Low Byte (PC<7:0>) 0000 0000 49, 54
TBLPTRU — — bit 21 Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) --00 0000 49, 76
TBLPTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 0000 0000 49, 76
TBLPTRL Program Memory Table Pointer Low Byte (TBLPTR<7:0>) 0000 0000 49, 76
TABLAT Program Memory Table Latch 0000 0000 49, 76
PRODH Product Register High Byte xxxx xxxx 49, 89
PRODL Product Register Low Byte xxxx xxxx 49, 89
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 49, 93
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 49, 94
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 49, 95
INDF0 Uses contents of FSR0 to address data memory – value of FSR0 not changed (not a physical register) N/A 49, 69
POSTINC0 Uses contents of FSR0 to address data memory – value of FSR0 post-incremented (not a physical register) N/A 49, 69
POSTDEC0 Uses contents of FSR0 to address data memory – value of FSR0 post-decremented (not a physical register) N/A 49, 69
PREINC0 Uses contents of FSR0 to address data memory – value of FSR0 pre-incremented (not a physical register) N/A 49, 69
PLUSW0 Uses contents of FSR0 to address data memory – value of FSR0 pre-incremented (not a physical register) –
value of FSR0 offset by W
N/A 49, 69
FSR0H — — — — Indirect Data Memory Address Pointer 0 High Byte ---- 0000 49, 69
FSR0L Indirect Data Memory Address Pointer 0 Low Byte xxxx xxxx 49, 69
WREG Working Register xxxx xxxx 49
INDF1 Uses contents of FSR1 to address data memory – value of FSR1 not changed (not a physical register) N/A 49, 69
POSTINC1 Uses contents of FSR1 to address data memory – value of FSR1 post-incremented (not a physical register) N/A 49, 69
POSTDEC1 Uses contents of FSR1 to address data memory – value of FSR1 post-decremented (not a physical register) N/A 49, 69
PREINC1 Uses contents of FSR1 to address data memory – value of FSR1 pre-incremented (not a physical register) N/A 49, 69
PLUSW1 Uses contents of FSR1 to address data memory – value of FSR1 pre-incremented (not a physical register) –
value of FSR1 offset by W
N/A 49, 69
FSR1H — — — — Indirect Data Memory Address Pointer 1 High Byte ---- 0000 50, 69
FSR1L Indirect Data Memory Address Pointer 1 Low Byte xxxx xxxx 50, 69
BSR — — — — Bank Select Register ---- 0000 50, 59
INDF2 Uses contents of FSR2 to address data memory – value of FSR2 not changed (not a physical register) N/A 50, 69
POSTINC2 Uses contents of FSR2 to address data memory – value of FSR2 post-incremented (not a physical register) N/A 50, 69
POSTDEC2 Uses contents of FSR2 to address data memory – value of FSR2 post-decremented (not a physical register) N/A 50, 69
PREINC2 Uses contents of FSR2 to address data memory – value of FSR2 pre-incremented (not a physical register) N/A 50, 69
PLUSW2 Uses contents of FSR2 to address data memory – value of FSR2 pre-incremented (not a physical register) –
value of FSR2 offset by W
N/A 50, 69
FSR2H — — — — Indirect Data Memory Address Pointer 2 High Byte ---- 0000 50, 69
FSR2L Indirect Data Memory Address Pointer 2 Low Byte xxxx xxxx 50, 69
STATUS — — — N OV Z DC C ---x xxxx 50, 67
Legend: x = unknown, u = unchanged, — = unimplemented, q = value depends on condition. Shaded cells are unimplemented, read as ‘0’.
Note 1: The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise, it is disabled and reads as ‘0’. See
Section 4.4 “Brown-out Reset (BOR)”.
2: These registers and/or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
individual unimplemented bits should be interpreted as ‘-’.
3: The PLLEN bit is only available in specific oscillator configurations; otherwise, it is disabled and reads as ‘0’. See Section 2.6.4 “PLL in
INTOSC Modes”.
4: The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0); otherwise, RE3 reads as ‘0’. This bit is
read-only.
5: RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
When disabled, these bits read as ‘0’.© 2008 Microchip Technology Inc. DS39631E-page 65
PIC18F2420/2520/4420/4520
TMR0H Timer0 Register High Byte 0000 0000 50, 125
TMR0L Timer0 Register Low Byte xxxx xxxx 50, 125
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 50, 123
OSCCON IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 0100 q000 30, 50
HLVDCON VDIRMAG — IRVST HLVDEN HLVDL3 HLVDL2 HLVDL1 HLVDL0 0-00 0101 50, 245
WDTCON — — — — — — — SWDTEN --- ---0 50, 259
RCON IPEN SBOREN(1) — RI TO PD POR BOR 0q-1 11q0 42, 48,
102
TMR1H Timer1 Register High Byte xxxx xxxx 50, 132
TMR1L Timer1 Register Low Bytes xxxx xxxx 50, 132
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0000 0000 50, 127
TMR2 Timer2 Register 0000 0000 50, 134
PR2 Timer2 Period Register 1111 1111 50, 134
T2CON — T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 50, 133
SSPBUF MSSP Receive Buffer/Transmit Register xxxx xxxx 50, 169,
170
SSPADD MSSP Address Register in I2C™ Slave Mode. MSSP Baud Rate Reload Register in I2C Master Mode. 0000 0000 50, 170
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 50, 162,
171
SSPCON1 WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 50, 163,
172
SSPCON2 GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN 0000 0000 50, 173
ADRESH A/D Result Register High Byte xxxx xxxx 51, 232
ADRESL A/D Result Register Low Byte xxxx xxxx 51, 232
ADCON0 — — CHS3 CHS2 CHS1 CHS0 GO/DONE ADON --00 0000 51, 223
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 --00 0qqq 51, 224
ADCON2 ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 0-00 0000 51, 225
CCPR1H Capture/Compare/PWM Register 1 High Byte xxxx xxxx 51, 140
CCPR1L Capture/Compare/PWM Register 1 Low Byte xxxx xxxx 51, 140
CCP1CON P1M1(2) P1M0(2) DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 0000 0000 51, 139,
147
CCPR2H Capture/Compare/PWM Register 2 High Byte xxxx xxxx 51, 140
CCPR2L Capture/Compare/PWM Register 2 Low Byte xxxx xxxx 51, 140
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 51, 139
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 0100 0-00 51, 204
PWM1CON PRSEN PDC6(2) PDC5(2) PDC4(2) PDC3(2) PDC2(2) PDC1(2) PDC0(2) 0000 0000 51, 156
ECCP1AS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1(2) PSSBD0(2) 0000 0000 51, 157
CVRCON CVREN CVROE CVRR CVRSS CVR3 CVR2 CVR1 CVR0 0000 0000 51, 239
CMCON C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0 0000 0111 51, 233
TMR3H Timer3 Register High Byte xxxx xxxx 51, 137
TMR3L Timer3 Register Low Byte xxxx xxxx 51, 137
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0000 0000 51, 135
TABLE 5-2: PIC18F2420/2520/4420/4520 REGISTER FILE SUMMARY (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
Legend: x = unknown, u = unchanged, — = unimplemented, q = value depends on condition. Shaded cells are unimplemented, read as ‘0’.
Note 1: The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise, it is disabled and reads as ‘0’. See
Section 4.4 “Brown-out Reset (BOR)”.
2: These registers and/or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
individual unimplemented bits should be interpreted as ‘-’.
3: The PLLEN bit is only available in specific oscillator configurations; otherwise, it is disabled and reads as ‘0’. See Section 2.6.4 “PLL in
INTOSC Modes”.
4: The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0); otherwise, RE3 reads as ‘0’. This bit is
read-only.
5: RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
When disabled, these bits read as ‘0’.PIC18F2420/2520/4420/4520
DS39631E-page 66 © 2008 Microchip Technology Inc.
SPBRGH EUSART Baud Rate Generator Register High Byte 0000 0000 51, 206
SPBRG EUSART Baud Rate Generator Register Low Byte 0000 0000 51, 206
RCREG EUSART Receive Register 0000 0000 51, 213
TXREG EUSART Transmit Register 0000 0000 51, 211
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 0000 0010 51, 202
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 51, 203
EEADR EEPROM Address Register 0000 0000 51, 74, 83
EEDATA EEPROM Data Register 0000 0000 51, 74, 83
EECON2 EEPROM Control Register 2 (not a physical register) 0000 0000 51, 74, 83
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 51, 75, 84
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 11-1 1111 52, 101
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 00-0 0000 52, 97
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 00-0 0000 52, 99
IPR1 PSPIP(2) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 1111 1111 52, 100
PIR1 PSPIF(2) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 52, 96
PIE1 PSPIE(2) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 52, 98
OSCTUNE INTSRC PLLEN(3) — TUN4 TUN3 TUN2 TUN1 TUN0 0q-0 0000 27, 52
TRISE(2) IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0 0000 -111 52, 118
TRISD(2) PORTD Data Direction Register 1111 1111 52, 114
TRISC PORTC Data Direction Register 1111 1111 52, 111
TRISB PORTB Data Direction Register 1111 1111 52, 108
TRISA TRISA7(5) TRISA6(5) PORTA Data Direction Register 1111 1111 52, 105
LATE(2) — — — — — PORTE Data Latch Register
(Read and Write to Data Latch)
---- -xxx 52, 117
LATD(2) PORTD Data Latch Register (Read and Write to Data Latch) xxxx xxxx 52, 114
LATC PORTC Data Latch Register (Read and Write to Data Latch) xxxx xxxx 52, 111
LATB PORTB Data Latch Register (Read and Write to Data Latch) xxxx xxxx 52, 108
LATA LATA7(5) LATA6(5) PORTA Data Latch Register (Read and Write to Data Latch) xxxx xxxx 52, 105
PORTE — — — — RE3(4) RE2(2) RE1(2) RE0(2) ---- xxxx 52, 117
PORTD(2) RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 xxxx xxxx 52, 114
PORTC RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0 xxxx xxxx 52, 111
PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 xxxx xxxx 52, 108
PORTA RA7(5) RA6(5) RA5 RA4 RA3 RA2 RA1 RA0 xx0x 0000 52, 105
TABLE 5-2: PIC18F2420/2520/4420/4520 REGISTER FILE SUMMARY (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
Legend: x = unknown, u = unchanged, — = unimplemented, q = value depends on condition. Shaded cells are unimplemented, read as ‘0’.
Note 1: The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise, it is disabled and reads as ‘0’. See
Section 4.4 “Brown-out Reset (BOR)”.
2: These registers and/or bits are not implemented on 28-pin devices and are read as ‘0’. Reset values are shown for 40/44-pin devices;
individual unimplemented bits should be interpreted as ‘-’.
3: The PLLEN bit is only available in specific oscillator configurations; otherwise, it is disabled and reads as ‘0’. See Section 2.6.4 “PLL in
INTOSC Modes”.
4: The RE3 bit is only available when Master Clear Reset is disabled (MCLRE Configuration bit = 0); otherwise, RE3 reads as ‘0’. This bit is
read-only.
5: RA6/RA7 and their associated latch and direction bits are individually configured as port pins based on various primary oscillator modes.
When disabled, these bits read as ‘0’.© 2008 Microchip Technology Inc. DS39631E-page 67
PIC18F2420/2520/4420/4520
5.3.5 STATUS REGISTER
The STATUS register, shown in Register 5-2, contains
the arithmetic status of the ALU. As with any other SFR,
it can be the operand for any instruction.
If the STATUS register is the destination for an instruction
that affects the Z, DC, C, OV or N bits, the results
of the instruction are not written; instead, the STATUS
register is updated according to the instruction performed.
Therefore, the result of an instruction with the
STATUS register as its destination may be different
than intended. As an example, CLRF STATUS will set
the Z bit and leave the remaining Status bits
unchanged (‘000u u1uu’).
It is recommended that only BCF, BSF, SWAPF, MOVFF
and MOVWF instructions are used to alter the STATUS
register, because these instructions do not affect the Z,
C, DC, OV or N bits in the STATUS register.
For other instructions that do not affect Status bits, see
the instruction set summaries in Table 24-2 and
Table 24-3.
Note: The C and DC bits operate as the borrow
and digit borrow bits, respectively, in
subtraction.
REGISTER 5-2: 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(1) C(2)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-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 (bit 7) 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(1)
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
bit 0 C: Carry/borrow bit(2)
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 1: 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 bit 4 or bit 3 of the source register.
2: 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.PIC18F2420/2520/4420/4520
DS39631E-page 68 © 2008 Microchip Technology Inc.
5.4 Data Addressing Modes
While the program memory can be addressed in only
one way – through the program counter – information
in the data memory space can be addressed in several
ways. For most instructions, the addressing mode is
fixed. Other instructions may use up to three modes,
depending on which operands are used and whether or
not the extended instruction set is enabled.
The addressing modes are:
• Inherent
• Literal
• Direct
• Indirect
An additional addressing mode, Indexed Literal Offset,
is available when the extended instruction set is
enabled (XINST Configuration bit = 1). Its operation is
discussed in greater detail in Section 5.5.1 “Indexed
Addressing with Literal Offset”.
5.4.1 INHERENT AND LITERAL
ADDRESSING
Many PIC18 control instructions do not need any
argument at all; they either perform an operation that
globally affects the device or they operate implicitly on
one register. This addressing mode is known as Inherent
Addressing. Examples include SLEEP, RESET and DAW.
Other instructions work in a similar way but require an
additional explicit argument in the opcode. This is
known as Literal Addressing mode because they
require some literal value as an argument. Examples
include ADDLW and MOVLW, which respectively, add or
move a literal value to the W register. Other examples
include CALL and GOTO, which include a 20-bit
program memory address.
5.4.2 DIRECT ADDRESSING
Direct Addressing specifies all or part of the source
and/or destination address of the operation within the
opcode itself. The options are specified by the
arguments accompanying the instruction.
In the core PIC18 instruction set, bit-oriented and byteoriented
instructions use some version of Direct
Addressing by default. All of these instructions include
some 8-bit literal address as their Least Significant
Byte. This address specifies either a register address in
one of the banks of data RAM (Section 5.3.3 “General
Purpose Register File”) or a location in the Access
Bank (Section 5.3.2 “Access Bank”) as the data
source for the instruction.
The Access RAM bit ‘a’ determines how the address is
interpreted. When ‘a’ is ‘1’, the contents of the BSR
(Section 5.3.1 “Bank Select Register (BSR)”) are
used with the address to determine the complete 12-bit
address of the register. When ‘a’ is ‘0’, the address is
interpreted as being a register in the Access Bank.
Addressing that uses the Access RAM is sometimes
also known as Direct Forced Addressing mode.
A few instructions, such as MOVFF, include the entire
12-bit address (either source or destination) in their
opcodes. In these cases, the BSR is ignored entirely.
The destination of the operation’s results is determined
by the destination bit ‘d’. When ‘d’ is ‘1’, the results are
stored back in the source register, overwriting its original
contents. When ‘d’ is ‘0’, the results are stored in
the W register. Instructions without the ‘d’ argument
have a destination that is implicit in the instruction; their
destination is either the target register being operated
on or the W register.
5.4.3 INDIRECT ADDRESSING
Indirect Addressing allows the user to access a location
in data memory without giving a fixed address in the
instruction. This is done by using File Select Registers
(FSRs) as pointers to the locations to be read or written
to. Since the FSRs are themselves located in RAM as
Special Function Registers, they can also be directly
manipulated under program control. This makes FSRs
very useful in implementing data structures, such as
tables and arrays in data memory.
The registers for Indirect Addressing are also
implemented with Indirect File Operands (INDFs) that
permit automatic manipulation of the pointer value with
auto-incrementing, auto-decrementing or offsetting
with another value. This allows for efficient code, using
loops, such as the example of clearing an entire RAM
bank in Example 5-5.
EXAMPLE 5-5: HOW TO CLEAR RAM
(BANK 1) USING INDIRECT
ADDRESSING
Note: The execution of some instructions in the
core PIC18 instruction set are changed
when the PIC18 extended instruction set is
enabled. See Section 5.5 “Data Memory
and the Extended Instruction Set” for
more information.
LFSR FSR0, 100h;
NEXT CLRF POSTINC0 ; Clear INDF
; register then
; inc pointer
BTFSS FSR0H, 1; All done with
; Bank1?
BRA NEXT ; NO, clear next
CONTINUE ; YES, continue © 2008 Microchip Technology Inc. DS39631E-page 69
PIC18F2420/2520/4420/4520
5.4.3.1 FSR Registers and the INDF
Operand
At the core of Indirect Addressing are three sets of registers:
FSR0, FSR1 and FSR2. Each represents a pair
of 8-bit registers, FSRnH and FSRnL. The four upper
bits of the FSRnH register are not used so each FSR
pair holds a 12-bit value. This represents a value that
can address the entire range of the data memory in a
linear fashion. The FSR register pairs, then, serve as
pointers to data memory locations.
Indirect Addressing is accomplished with a set of
Indirect File Operands, INDF0 through INDF2. These
can be thought of as “virtual” registers: they are
mapped in the SFR space but are not physically implemented.
Reading or writing to a particular INDF register
actually accesses its corresponding FSR register pair.
A read from INDF1, for example, reads the data at the
address indicated by FSR1H:FSR1L. Instructions that
use the INDF registers as operands actually use the
contents of their corresponding FSR as a pointer to the
instruction’s target. The INDF operand is just a
convenient way of using the pointer.
Because Indirect Addressing uses a full 12-bit address,
data RAM banking is not necessary. Thus, the current
contents of the BSR and the Access RAM bit have no
effect on determining the target address.
5.4.3.2 FSR Registers and POSTINC,
POSTDEC, PREINC and PLUSW
In addition to the INDF operand, each FSR register pair
also has four additional indirect operands. Like INDF,
these are “virtual” registers that cannot be indirectly
read or written to. Accessing these registers actually
accesses the associated FSR register pair, but also
performs a specific action on it stored value. They are:
• POSTDEC: accesses the FSR value, then
automatically decrements it by 1 afterwards
• POSTINC: accesses the FSR value, then
automatically increments it by 1 afterwards
• PREINC: increments the FSR value by 1, then
uses it in the operation
• PLUSW: adds the signed value of the W register
(range of -127 to 128) to that of the FSR and uses
the new value in the operation.
In this context, accessing an INDF register uses the
value in the FSR registers without changing them. Similarly,
accessing a PLUSW register gives the FSR value
offset by that in the W register; neither value is actually
changed in the operation. Accessing the other virtual
registers changes the value of the FSR registers.
Operations on the FSRs with POSTDEC, POSTINC
and PREINC affect the entire register pair; that is, rollovers
of the FSRnL register from FFh to 00h carry over
to the FSRnH register. On the other hand, results of
these operations do not change the value of any flags
in the STATUS register (e.g., Z, N, OV, etc.).
FIGURE 5-8: INDIRECT ADDRESSING
FSR1H:FSR1L
7 0
Data Memory
000h
100h
200h
300h
F00h
E00h
FFFh
Bank 0
Bank 1
Bank 2
Bank 14
Bank 15
Bank 3
through
Bank 13
ADDWF, INDF1, 1
7 0
Using an instruction with one of the
Indirect Addressing registers as the
operand....
...uses the 12-bit address stored in
the FSR pair associated with that
register....
...to determine the data memory
location to be used in that operation.
In this case, the FSR1 pair contains
ECCh. This means the contents of
location ECCh will be added to that
of the W register and stored back in
ECCh.
xxxx 1110 11001100PIC18F2420/2520/4420/4520
DS39631E-page 70 © 2008 Microchip Technology Inc.
The PLUSW register can be used to implement a form
of Indexed Addressing in the data memory space. By
manipulating the value in the W register, users can
reach addresses that are fixed offsets from pointer
addresses. In some applications, this can be used to
implement some powerful program control structure,
such as software stacks, inside of data memory.
5.4.3.3 Operations by FSRs on FSRs
Indirect Addressing operations that target other FSRs
or virtual registers represent special cases. For
example, using an FSR to point to one of the virtual
registers will not result in successful operations. As a
specific case, assume that FSR0H:FSR0L contains
FE7h, the address of INDF1. Attempts to read the
value of the INDF1 using INDF0 as an operand will
return 00h. Attempts to write to INDF1 using INDF0 as
the operand will result in a NOP.
On the other hand, using the virtual registers to write to
an FSR pair may not occur as planned. In these cases,
the value will be written to the FSR pair but without any
incrementing or decrementing. Thus, writing to INDF2
or POSTDEC2 will write the same value to the
FSR2H:FSR2L.
Since the FSRs are physical registers mapped in the
SFR space, they can be manipulated through all direct
operations. Users should proceed cautiously when
working on these registers, particularly if their code
uses indirect addressing.
Similarly, operations by Indirect Addressing are generally
permitted on all other SFRs. Users should exercise
the appropriate caution that they do not inadvertently
change settings that might affect the operation of the
device.
5.5 Data Memory and the Extended
Instruction Set
Enabling the PIC18 extended instruction set (XINST
Configuration bit = 1) significantly changes certain
aspects of data memory and its addressing. Specifically,
the use of the Access Bank for many of the core
PIC18 instructions is different; this is due to the
introduction of a new addressing mode for the data
memory space.
What does not change is just as important. The size of
the data memory space is unchanged, as well as its
linear addressing. The SFR map remains the same.
Core PIC18 instructions can still operate in both Direct
and Indirect Addressing mode; inherent and literal
instructions do not change at all. Indirect Addressing
with FSR0 and FSR1 also remains unchanged.
5.5.1 INDEXED ADDRESSING WITH
LITERAL OFFSET
Enabling the PIC18 extended instruction set changes
the behavior of Indirect Addressing using the FSR2
register pair within Access RAM. Under the proper
conditions, instructions that use the Access Bank – that
is, most bit-oriented and byte-oriented instructions –
can invoke a form of Indexed Addressing using an
offset specified in the instruction. This special addressing
mode is known as Indexed Addressing with Literal
Offset, or Indexed Literal Offset mode.
When using the extended instruction set, this
addressing mode requires the following:
• The use of the Access Bank is forced (‘a’ = 0) and
• The file address argument is less than or equal to
5Fh.
Under these conditions, the file address of the instruction
is not interpreted as the lower byte of an address
(used with the BSR in direct addressing), or as an 8-bit
address in the Access Bank. Instead, the value is
interpreted as an offset value to an Address Pointer,
specified by FSR2. The offset and the contents of
FSR2 are added to obtain the target address of the
operation.
5.5.2 INSTRUCTIONS AFFECTED BY
INDEXED LITERAL OFFSET MODE
Any of the core PIC18 instructions that can use Direct
Addressing are potentially affected by the Indexed
Literal Offset Addressing mode. This includes all
byte-oriented and bit-oriented instructions, or almost
one-half of the standard PIC18 instruction set.
Instructions that only use Inherent or Literal Addressing
modes are unaffected.
Additionally, byte-oriented and bit-oriented instructions
are not affected if they do not use the Access Bank
(Access RAM bit is ‘1’), or include a file address of 60h
or above. Instructions meeting these criteria will
continue to execute as before. A comparison of the different
possible addressing modes when the extended
instruction set is enabled in shown in Figure 5-9.
Those who desire to use byte-oriented or bit-oriented
instructions in the Indexed Literal Offset mode should
note the changes to assembler syntax for this mode.
This is described in more detail in Section 24.2.1
“Extended Instruction Syntax”.© 2008 Microchip Technology Inc. DS39631E-page 71
PIC18F2420/2520/4420/4520
FIGURE 5-9: COMPARING ADDRESSING OPTIONS FOR BIT-ORIENTED AND
BYTE-ORIENTED INSTRUCTIONS (EXTENDED INSTRUCTION SET ENABLED)
EXAMPLE INSTRUCTION: ADDWF, f, d, a (Opcode: 0010 01da ffff ffff)
When ‘a’ = 0 and f ≥ 60h:
The instruction executes in
Direct Forced mode. ‘f’ is interpreted
as a location in the
Access RAM between 060h
and 0FFh. This is the same as
locations 060h to 07Fh
(Bank 0) and F80h to FFFh
(Bank 15) of data memory.
Locations below 60h are not
available in this addressing
mode.
When ‘a’ = 0 and f ≤ 5Fh:
The instruction executes in
Indexed Literal Offset mode. ‘f’
is interpreted as an offset to the
address value in FSR2. The
two are added together to
obtain the address of the target
register for the instruction. The
address can be anywhere in
the data memory space.
Note that in this mode, the
correct syntax is now:
ADDWF [k], d
where ‘k’ is the same as ‘f’.
When ‘a’ = 1 (all values of f):
The instruction executes in
Direct mode (also known as
Direct Long mode). ‘f’ is interpreted
as a location in one of
the 16 banks of the data
memory space. The bank is
designated by the Bank Select
Register (BSR). The address
can be in any implemented
bank in the data memory
space.
000h
060h
100h
F00h
F80h
FFFh
Valid range
00h
60h
80h
FFh
Data Memory
Access RAM
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
000h
080h
100h
F00h
F80h
FFFh
Data Memory
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
FSR2H FSR2L
001001da ffffffff
001001da ffffffff
000h
080h
100h
F00h
F80h
FFFh
Data Memory
Bank 0
Bank 1
through
Bank 14
Bank 15
SFRs
for ‘f’
BSR
00000000
080hPIC18F2420/2520/4420/4520
DS39631E-page 72 © 2008 Microchip Technology Inc.
5.5.3 MAPPING THE ACCESS BANK IN
INDEXED LITERAL OFFSET MODE
The use of Indexed Literal Offset Addressing mode
effectively changes how the first 96 locations of Access
RAM (00h to 5Fh) are mapped. Rather than containing
just the contents of the bottom half of Bank 0, this mode
maps the contents from Bank 0 and a user-defined
“window” that can be located anywhere in the data
memory space. The value of FSR2 establishes the
lower boundary of the addresses mapped into the
window, while the upper boundary is defined by FSR2
plus 95 (5Fh). Addresses in the Access RAM above
5Fh are mapped as previously described (see
Section 5.3.2 “Access Bank”). An example of Access
Bank remapping in this addressing mode is shown in
Figure 5-10.
Remapping of the Access Bank applies only to operations
using the Indexed Literal Offset mode. Operations
that use the BSR (Access RAM bit is ‘1’) will continue
to use Direct Addressing as before.
5.6 PIC18 Instruction Execution and
the Extended Instruction Set
Enabling the extended instruction set adds eight
additional commands to the existing PIC18 instruction
set. These instructions are executed as described in
Section 24.2 “Extended Instruction Set”.
FIGURE 5-10: REMAPPING THE ACCESS BANK WITH INDEXED LITERAL OFFSET ADDRESSING
Data Memory
000h
100h
200h
F80h
F00h
FFFh
Bank 1
Bank 15
Bank 2
through
Bank 14
SFRs
05Fh
ADDWF f, d, a
FSR2H:FSR2L = 120h
Locations in the region
from the FSR2 Pointer
(120h) to the pointer plus
05Fh (17Fh) are mapped
to the bottom of the
Access RAM (000h-05Fh).
Locations in Bank 0 from
060h to 07Fh are mapped,
as usual, to the middle half
of the Access Bank.
Special Function Registers
at F80h through FFFh are
mapped to 80h through
FFh, as usual.
Bank 0 addresses below
5Fh can still be addressed
by using the BSR.
Access Bank
00h
80h
FFh
7Fh
Bank 0
SFRs
Bank 1 “Window”
Bank 0
Bank 0
Window
Example Situation:
07Fh
120h
17Fh
5Fh
Bank 1© 2008 Microchip Technology Inc. DS39631E-page 73
PIC18F2420/2520/4420/4520
6.0 FLASH PROGRAM MEMORY
The Flash program memory is readable, writable and
erasable during normal operation over the entire VDD
range.
A read from program memory is executed on one byte
at a time. A write to program memory is executed on
blocks of 32 bytes at a time. Program memory is
erased in blocks of 64 bytes at a time. A bulk erase
operation may not be issued from user code.
Writing or erasing program memory will cease
instruction fetches until the operation is complete. The
program memory cannot be accessed during the write
or erase, therefore, code cannot execute. An internal
programming timer terminates program memory writes
and erases.
A value written to program memory does not need to be
a valid instruction. Executing a program memory
location that forms an invalid instruction results in a
NOP.
6.1 Table Reads and Table Writes
In order to read and write program memory, there are
two operations that allow the processor to move bytes
between the program memory space and the data RAM:
• Table Read (TBLRD)
• Table Write (TBLWT)
The program memory space is 16 bits wide, while the
data RAM space is 8 bits wide. Table reads and table
writes move data between these two memory spaces
through an 8-bit register (TABLAT).
Table read operations retrieve data from program
memory and places it into the data RAM space.
Figure 6-1 shows the operation of a table read with
program memory and data RAM.
Table write operations store data from the data memory
space into holding registers in program memory. The
procedure to write the contents of the holding registers
into program memory is detailed in Section 6.5 “Writing
to Flash Program Memory”. Figure 6-2 shows the
operation of a table write with program memory and data
RAM.
Table operations work with byte entities. A table block
containing data, rather than program instructions, is not
required to be word aligned. Therefore, a table block can
start and end at any byte address. If a table write is being
used to write executable code into program memory,
program instructions will need to be word aligned.
FIGURE 6-1: TABLE READ OPERATION
Table Pointer(1)
Table Latch (8-bit)
Program Memory
TBLPTRH TBLPTRL
TABLAT
TBLPTRU
Instruction: TBLRD*
Note 1: The Table Pointer register points to a byte in program memory.
Program Memory
(TBLPTR)PIC18F2420/2520/4420/4520
DS39631E-page 74 © 2008 Microchip Technology Inc.
FIGURE 6-2: TABLE WRITE OPERATION
6.2 Control Registers
Several control registers are used in conjunction with
the TBLRD and TBLWT instructions. These include the:
• EECON1 register
• EECON2 register
• TABLAT register
• TBLPTR registers
6.2.1 EECON1 AND EECON2 REGISTERS
The EECON1 register (Register 6-1) is the control
register for memory accesses. The EECON2 register is
not a physical register; it is used exclusively in the
memory write and erase sequences. Reading
EECON2 will read all ‘0’s.
The EEPGD control bit determines if the access will be
a program or data EEPROM memory access. When
clear, any subsequent operations will operate on the
data EEPROM memory. When set, any subsequent
operations will operate on the program memory.
The CFGS control bit determines if the access will be
to the Configuration/Calibration registers or to program
memory/data EEPROM memory. When set,
subsequent operations will operate on Configuration
registers regardless of EEPGD (see Section 23.0
“Special Features of the CPU”). When clear, memory
selection access is determined by EEPGD.
The FREE bit, when set, will allow a program memory
erase operation. When FREE is set, the erase
operation is initiated on the next WR command. When
FREE is clear, only writes are enabled.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is clear. The WRERR bit is
set in hardware when the WR bit is set and cleared
when the internal programming timer expires and the
write operation is complete.
The WR control bit initiates write operations. The bit
cannot be cleared, only set, in software; it is cleared in
hardware at the completion of the write operation.
Table Pointer(1) Table Latch (8-bit)
TBLPTRH TBLPTRL TABLAT
Program Memory
(TBLPTR)
TBLPTRU
Instruction: TBLWT*
Note1: The Table Pointer actually points to one of 32 holding registers, the address of which is determined by
TBLPTRL<4:0>. The process for physically writing data to the program memory array is discussed in
Section 6.5 “Writing to Flash Program Memory”.
Holding Registers
Program Memory
Note: During normal operation, the WRERR is
read as ‘1’. This can indicate that a write
operation was prematurely terminated by
a Reset, or a write operation was
attempted improperly.
Note: The EEIF interrupt flag bit (PIR2<4>) is set
when the write is complete. It must be
cleared in software.© 2008 Microchip Technology Inc. DS39631E-page 75
PIC18F2420/2520/4420/4520
REGISTER 6-1: EECON1: EEPROM CONTROL REGISTER 1
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR(1) WREN WR RD
bit 7 bit 0
Legend: S = Settable bit (cannot be cleared in software)
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory
0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration registers
0 = Access Flash program or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’
bit 4 FREE: Flash Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command (cleared by
completion of erase operation)
0 = Perform write only
bit 3 WRERR: Flash Program/Data EEPROM Error Flag bit(1)
1 = A write operation is prematurely terminated (any Reset during self-timed programming in normal
operation, or an improper write attempt)
0 = The write operation completed
bit 2 WREN: Flash Program/Data EEPROM Write Enable bit
1 = Allows write cycles to Flash program/data EEPROM
0 = Inhibits write cycles to Flash program/data EEPROM
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle
(The operation is self-timed and the bit is cleared by hardware once write is complete. The WR bit
can only be set (not cleared) in software.)
0 = Write cycle to the EEPROM is complete
bit 0 RD: Read Control bit
1 = Initiates an EEPROM read (Read takes one cycle. RD is cleared in hardware. The RD bit can only
be set (not cleared) in software. RD bit cannot be set when EEPGD = 1 or CFGS = 1.)
0 = Does not initiate an EEPROM read
Note 1: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows tracing of the error
condition.PIC18F2420/2520/4420/4520
DS39631E-page 76 © 2008 Microchip Technology Inc.
6.2.2 TABLAT – TABLE LATCH REGISTER
The Table Latch (TABLAT) is an 8-bit register mapped
into the SFR space. The Table Latch register is used to
hold 8-bit data during data transfers between program
memory and data RAM.
6.2.3 TBLPTR – TABLE POINTER
REGISTER
The Table Pointer (TBLPTR) register addresses a byte
within the program memory. The TBLPTR is comprised
of three SFR registers: Table Pointer Upper Byte, Table
Pointer High Byte and Table Pointer Low Byte
(TBLPTRU:TBLPTRH:TBLPTRL). These three registers
join to form a 22-bit wide pointer. The low-order
21 bits allow the device to address up to 2 Mbytes of
program memory space. The 22nd bit allows access to
the device ID, the user ID and the Configuration bits.
The Table Pointer register, 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 6-1. These operations on the TBLPTR only affect
the low-order 21 bits.
6.2.4 TABLE POINTER BOUNDARIES
TBLPTR is used in reads, writes and erases of the
Flash program memory.
When a TBLRD is executed, all 22 bits of the TBLPTR
determine which byte is read from program memory
into TABLAT.
When a TBLWT is executed, the five LSbs of the Table
Pointer register (TBLPTR<4:0>) determine which of
the 32 program memory holding registers is written to.
When the timed write to program memory begins (via
the WR bit), the 16 MSbs of the TBLPTR
(TBLPTR<21:6>) determine which program memory
block of 32 bytes is written to. For more detail, see
Section 6.5 “Writing to Flash Program Memory”.
When an erase of program memory is executed, the
16 MSbs of the Table Pointer register (TBLPTR<21:6>)
point to the 64-byte block that will be erased. The Least
Significant bits (TBLPTR<5:0>) are ignored.
Figure 6-3 describes the relevant boundaries of
TBLPTR based on Flash program memory operations.
TABLE 6-1: TABLE POINTER OPERATIONS WITH TBLRD AND TBLWT INSTRUCTIONS
FIGURE 6-3: TABLE POINTER BOUNDARIES BASED ON OPERATION
Example 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
21 16 15 8 7 0
TABLE ERASE
TABLE READ – TBLPTR<21:0>
TBLPTRU TBLPTRH TBLPTRL
TBLPTR<21:6>
TABLE WRITE – TBLPTR<21:5>© 2008 Microchip Technology Inc. DS39631E-page 77
PIC18F2420/2520/4420/4520
6.3 Reading the Flash Program
Memory
The TBLRD instruction is used to retrieve data from
program memory and places it into data RAM. Table
reads from program memory are performed one byte at
a time.
TBLPTR points to a byte address in program space.
Executing TBLRD places the byte pointed to into
TABLAT. In addition, TBLPTR can be modified
automatically for the next table read operation.
The internal program memory is typically organized by
words. The Least Significant bit of the address selects
between the high and low bytes of the word. Figure 6-4
shows the interface between the internal program
memory and the TABLAT.
FIGURE 6-4: READS FROM FLASH PROGRAM MEMORY
EXAMPLE 6-1: READING A FLASH PROGRAM MEMORY WORD
(Even Byte Address)
Program Memory
(Odd Byte Address)
TBLRD TABLAT
TBLPTR = xxxxx1
FETCH Instruction Register
(IR) Read Register
TBLPTR = xxxxx0
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the word
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
READ_WORD
TBLRD*+ ; read into TABLAT and increment
MOVF TABLAT, W ; get data
MOVWF WORD_EVEN
TBLRD*+ ; read into TABLAT and increment
MOVFW TABLAT, W ; get data
MOVF WORD_ODDPIC18F2420/2520/4420/4520
DS39631E-page 78 © 2008 Microchip Technology Inc.
6.4 Erasing Flash Program Memory
The minimum erase block is 32 words or 64 bytes. Only
through the use of an external programmer, or through
ICSP control, can larger blocks of program memory be
bulk erased. Word erase in the Flash array is not
supported.
When initiating an erase sequence from the microcontroller
itself, a block of 64 bytes of program memory
is erased. The Most Significant 16 bits of the
TBLPTR<21:6> point to the block being erased.
TBLPTR<5:0> are ignored.
The EECON1 register commands the erase operation.
The EEPGD bit must be set to point to the Flash program
memory. The WREN bit must be set to enable
write operations. The FREE bit is set to select an erase
operation.
For protection, the write initiate sequence for EECON2
must be used.
A long write is necessary for erasing the internal Flash.
Instruction execution is halted while in a long write
cycle. The long write will be terminated by the internal
programming timer.
6.4.1 FLASH PROGRAM MEMORY
ERASE SEQUENCE
The sequence of events for erasing a block of internal
program memory location is:
1. Load Table Pointer register with address of row
being erased.
2. Set the EECON1 register for the erase operation:
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program memory;
• set WREN bit to enable writes;
• set FREE bit to enable the erase.
3. Disable interrupts.
4. Write 55h to EECON2.
5. Write 0AAh to EECON2.
6. Set the WR bit. This will begin the row erase
cycle.
7. The CPU will stall for duration of the erase
(about 2 ms using internal timer).
8. Re-enable interrupts.
EXAMPLE 6-2: ERASING A FLASH PROGRAM MEMORY ROW
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
ERASE_ROW
BSF EECON1, EEPGD ; point to Flash program memory
BCF EECON1, CFGS ; access Flash program memory
BSF EECON1, WREN ; enable write to memory
BSF EECON1, FREE ; enable Row Erase operation
BCF INTCON, GIE ; disable interrupts
Required MOVLW 55h
Sequence MOVWF EECON2 ; write 55h
MOVLW 0AAh
MOVWF EECON2 ; write 0AAh
BSF EECON1, WR ; start erase (CPU stall)
BSF INTCON, GIE ; re-enable interrupts© 2008 Microchip Technology Inc. DS39631E-page 79
PIC18F2420/2520/4420/4520
6.5 Writing to Flash Program Memory
The minimum programming block is 16 words or
32 bytes. Word or byte programming is not supported.
Table writes are used internally to load the holding
registers needed to program the Flash memory. There
are 32 holding registers used by the table writes for
programming.
Since the Table Latch (TABLAT) is only a single byte,
the TBLWT instruction may need to be executed
32 times for each programming operation. All of the
table write operations will essentially be short writes
because only the holding registers are written. At the
end of updating the 32 holding registers, the EECON1
register must be written to in order to start the
programming operation with a long write.
The long write is necessary for programming the internal
Flash. Instruction execution is halted while in a long
write cycle. The long write will be terminated by the
internal programming timer.
The EEPROM on-chip timer controls the write time.
The write/erase voltages are generated by an on-chip
charge pump, rated to operate over the voltage range
of the device.
FIGURE 6-5: TABLE WRITES TO FLASH PROGRAM MEMORY
6.5.1 FLASH PROGRAM MEMORY WRITE
SEQUENCE
The sequence of events for programming an internal
program memory location should be:
1. Read 64 bytes into RAM.
2. Update data values in RAM as necessary.
3. Load Table Pointer register with address being
erased.
4. Execute the row erase procedure.
5. Load Table Pointer register with address of first
byte being written.
6. Write the 32 bytes into the holding registers with
auto-increment.
7. Set the EECON1 register for the write operation:
• set EEPGD bit to point to program memory;
• clear the CFGS bit to access program memory;
• set WREN to enable byte writes.
8. Disable interrupts.
9. Write 55h to EECON2.
10. Write 0AAh to EECON2.
11. Set the WR bit. This will begin the write cycle.
12. The CPU will stall for duration of the write (about
2 ms using internal timer).
13. Re-enable interrupts.
14. Verify the memory (table read).
This procedure will require about 6 ms to update one
row of 64 bytes of memory. An example of the required
code is given in Example 6-3.
Note: The default value of the holding registers on
device Resets and after write operations is
FFh. A write of FFh to a holding register
does not modify that byte. This means individual
bytes of program memory may be
modified, provided that the change does not
attempt to change any bit from a ‘0’ to a ‘1’.
When modifying individual bytes, it is not
necessary to load all 32 holding registers
before executing a write operation.
TABLAT
TBLPTR = xxxxx0 TBLPTR = xxxxx1 TBLPTR = xxxx3F
Write Register
TBLPTR = xxxxx2
Program Memory
Holding Register Holding Register Holding Register Holding Register
8 8 8 8
Note: Before setting the WR bit, the Table
Pointer address needs to be within the
intended address range of the 32 bytes in
the holding register.PIC18F2420/2520/4420/4520
DS39631E-page 80 © 2008 Microchip Technology Inc.
EXAMPLE 6-3: WRITING TO FLASH PROGRAM MEMORY
MOVLW D'64 ; number of bytes in erase block
MOVWF COUNTER
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
READ_BLOCK
TBLRD*+ ; read into TABLAT, and inc
MOVF TABLAT, W ; get data
MOVWF POSTINC0 ; store data
DECFSZ COUNTER ; done?
BRA READ_BLOCK ; repeat
MODIFY_WORD
MOVLW DATA_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW DATA_ADDR_LOW
MOVWF FSR0L
MOVLW NEW_DATA_LOW ; update buffer word
MOVWF POSTINC0
MOVLW NEW_DATA_HIGH
MOVWF INDF0
ERASE_BLOCK
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
BSF EECON1, EEPGD ; point to Flash program memory
BCF EECON1, CFGS ; access Flash program memory
BSF EECON1, WREN ; enable write to memory
BSF EECON1, FREE ; enable Row Erase operation
BCF INTCON, GIE ; disable interrupts
MOVLW 55h
Required MOVWF EECON2 ; write 55h
Sequence MOVLW 0AAh
MOVWF EECON2 ; write 0AAh
BSF EECON1, WR ; start erase (CPU stall)
BSF INTCON, GIE ; re-enable interrupts
TBLRD*- ; dummy read decrement
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
WRITE_BUFFER_BACK
MOVLW D’32 ; number of bytes in holding register
MOVWF COUNTER
WRITE_BYTE_TO_HREGS
MOVFF POSTINC0, WREG ; get low byte of buffer data
MOVWF TABLAT ; present data to table latch
TBLWT+* ; write data, perform a short write
; to internal TBLWT holding register.
DECFSZ COUNTER ; loop until buffers are full
BRA WRITE_WORD_TO_HREGS© 2008 Microchip Technology Inc. DS39631E-page 81
PIC18F2420/2520/4420/4520
EXAMPLE 6-3: WRITING TO FLASH PROGRAM MEMORY (CONTINUED)
6.5.2 WRITE VERIFY
Depending on the application, good programming
practice may dictate that the value written to the
memory should be verified against the original value.
This should be used in applications where excessive
writes can stress bits near the specification limit.
6.5.3 UNEXPECTED TERMINATION OF
WRITE OPERATION
If a write is terminated by an unplanned event, such as
loss of power or an unexpected Reset, the memory
location just programmed should be verified and reprogrammed
if needed. If the write operation is interrupted
by a MCLR Reset or a WDT Time-out Reset during
normal operation, the user can check the WRERR bit
and rewrite the location(s) as needed.
6.5.4 PROTECTION AGAINST
SPURIOUS WRITES
To protect against spurious writes to Flash program
memory, the write initiate sequence must also be
followed. See Section 23.0 “Special Features of
the CPU” for more detail.
6.6 Flash Program Operation During
Code Protection
See Section 23.5 “Program Verification and Code
Protection” for details on code protection of Flash
program memory.
TABLE 6-2: REGISTERS ASSOCIATED WITH PROGRAM FLASH MEMORY
PROGRAM_MEMORY
BSF EECON1, EEPGD ; point to Flash program memory
BCF EECON1, CFGS ; access Flash program memory
BSF EECON1, WREN ; enable write to memory
BCF INTCON, GIE ; disable interrupts
MOVLW 55h
Required MOVWF EECON2 ; write 55h
Sequence MOVLW 0AAh
MOVWF EECON2 ; write 0AAh
BSF EECON1, WR ; start program (CPU stall)
BSF INTCON, GIE ; re-enable interrupts
BCF EECON1, WREN ; disable write to memory
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values on
page
TBLPTRU — — bit 21 Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) 49
TBLPTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 49
TBLPTRL Program Memory Table Pointer Low Byte (TBLPTR<7:0>) 49
TABLAT Program Memory Table Latch 49
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
EECON2 EEPROM Control Register 2 (not a physical register) 51
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD 51
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.PIC18F2420/2520/4420/4520
DS39631E-page 82 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 83
PIC18F2420/2520/4420/4520
7.0 DATA EEPROM MEMORY
The data EEPROM is a nonvolatile memory array,
separate from the data RAM and program memory, that
is used for long-term storage of program data. It is not
directly mapped in either the register file or program
memory space but is indirectly addressed through the
Special Function Registers (SFRs). The EEPROM is
readable and writable during normal operation over the
entire VDD range.
Five SFRs are used to read and write to the data
EEPROM as well as the program memory. They are:
• EECON1
• EECON2
• EEDATA
• EEADR
The data EEPROM allows byte read and write. When
interfacing to the data memory block, EEDATA holds
the 8-bit data for read/write and the EEADR register
holds the address of the EEPROM location being
accessed.
The EEPROM data memory is rated for high erase/write
cycle endurance. A byte write automatically erases the
location and writes the new data (erase-before-write).
The write time is controlled by an on-chip timer; it will
vary with voltage and temperature as well as from chip
to chip. Please refer to parameter D122 (Table 26-1 in
Section 26.0 “Electrical Characteristics”) for exact
limits.
7.1 EEADR Register
The EEADR register is used to address the data
EEPROM for read and write operations. The 8-bit
range of the register can address a memory range of
256 bytes (00h to FFh).
7.2 EECON1 and EECON2 Registers
Access to the data EEPROM is controlled by two
registers: EECON1 and EECON2. These are the same
registers which control access to the program memory
and are used in a similar manner for the data
EEPROM.
The EECON1 register (Register 7-1) is the control
register for data and program memory access. Control
bit EEPGD determines if the access will be to program
or data EEPROM memory. When clear, operations will
access the data EEPROM memory. When set, program
memory is accessed.
Control bit, CFGS, determines if the access will be to
the Configuration registers or to program memory/data
EEPROM memory. When set, subsequent operations
access Configuration registers. When CFGS is clear,
the EEPGD bit selects either program Flash or data
EEPROM memory.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is clear. The WRERR bit is
set in hardware when the WR bit is set and cleared
when the internal programming timer expires and the
write operation is complete.
The WR control bit initiates write operations. The bit
can be set but not cleared in software. It is only cleared
in hardware at the completion of the write operation.
Control bits, RD and WR, start read and erase/write
operations, respectively. These bits are set by firmware
and cleared by hardware at the completion of the
operation.
The RD bit cannot be set when accessing program
memory (EEPGD = 1). Program memory is read using
table read instructions. See Section 6.1 “Table Reads
and Table Writes” regarding table reads.
The EECON2 register is not a physical register. It is
used exclusively in the memory write and erase
sequences. Reading EECON2 will read all ‘0’s.
Note: During normal operation, the WRERR
may read as ‘1’. This can indicate that a
write operation was prematurely terminated
by a Reset, or a write operation was
attempted improperly.
Note: The EEIF interrupt flag bit (PIR2<4>) is set
when the write is complete. It must be
cleared in software.PIC18F2420/2520/4420/4520
DS39631E-page 84 © 2008 Microchip Technology Inc.
REGISTER 7-1: EECON1: EEPROM CONTROL REGISTER 1
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR(1) WREN WR RD
bit 7 bit 0
Legend: S = Settable bit (cannot be cleared in software)
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 EEPGD: Flash Program or Data EEPROM Memory Select bit
1 = Access Flash program memory
0 = Access data EEPROM memory
bit 6 CFGS: Flash Program/Data EEPROM or Configuration Select bit
1 = Access Configuration registers
0 = Access Flash program or data EEPROM memory
bit 5 Unimplemented: Read as ‘0’
bit 4 FREE: Flash Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command (cleared by
completion of erase operation)
0 = Perform write only
bit 3 WRERR: Flash Program/Data EEPROM Error Flag bit(1)
1 = A write operation is prematurely terminated (any Reset during self-timed programming in normal
operation, or an improper write attempt)
0 = The write operation completed
bit 2 WREN: Flash Program/Data EEPROM Write Enable bit
1 = Allows write cycles to Flash program/data EEPROM
0 = Inhibits write cycles to Flash program/data EEPROM
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle
(The operation is self-timed and the bit is cleared by hardware once write is complete. The WR bit
can only be set (not cleared) in software.)
0 = Write cycle to the EEPROM is complete
bit 0 RD: Read Control bit
1 = Initiates an EEPROM read (Read takes one cycle. RD is cleared in hardware. The RD bit can only
be set (not cleared) in software. RD bit cannot be set when EEPGD = 1 or CFGS = 1.)
0 = Does not initiate an EEPROM read
Note 1: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows tracing of the error
condition.© 2008 Microchip Technology Inc. DS39631E-page 85
PIC18F2420/2520/4420/4520
7.3 Reading the Data EEPROM
Memory
To read a data memory location, the user must write the
address to the EEADR register, clear the EEPGD control
bit (EECON1<7>) and then set control bit, RD
(EECON1<0>). The data is available on the very next
instruction cycle; therefore, the EEDATA register can
be read by the next instruction. EEDATA will hold this
value until another read operation, or until it is written to
by the user (during a write operation).
The basic process is shown in Example 7-1.
7.4 Writing to the Data EEPROM
Memory
To write an EEPROM data location, the address must
first be written to the EEADR register and the data
written to the EEDATA register. The sequence in
Example 7-2 must be followed to initiate the write cycle.
The write will not begin if this sequence is not exactly
followed (write 55h to EECON2, write 0AAh to
EECON2, then set WR bit) for each byte. It is strongly
recommended that interrupts be disabled during this
code segment.
Additionally, the WREN bit in EECON1 must be set to
enable writes. This mechanism prevents accidental
writes to data EEPROM due to unexpected code execution
(i.e., runaway programs). The WREN bit should
be kept clear at all times, except when updating the
EEPROM. The WREN bit is not cleared by hardware.
After a write sequence has been initiated, EECON1,
EEADR and EEDATA cannot be modified. The WR bit
will be inhibited from being set unless the WREN bit is
set. Both WR and WREN cannot be set with the same
instruction.
At the completion of the write cycle, the WR bit is
cleared in hardware and the EEPROM Interrupt Flag
bit, EEIF, is set. The user may either enable this
interrupt or poll this bit. EEIF must be cleared by
software.
7.5 Write Verify
Depending on the application, good programming
practice may dictate that the value written to the
memory should be verified against the original value.
This should be used in applications where excessive
writes can stress bits near the specification limit.
EXAMPLE 7-1: DATA EEPROM READ
EXAMPLE 7-2: DATA EEPROM WRITE
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to read
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access EEPROM
BSF EECON1, RD ; EEPROM Read
MOVF EEDATA, W ; W = EEDATA
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to write
MOVLW DATA_EE_DATA ;
MOVWF EEDATA ; Data Memory Value to write
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access EEPROM
BSF EECON1, WREN ; Enable writes
BCF INTCON, GIE ; Disable Interrupts
MOVLW 55h ;
Required MOVWF EECON2 ; Write 55h
Sequence MOVLW 0AAh ;
MOVWF EECON2 ; Write 0AAh
BSF EECON1, WR ; Set WR bit to begin write
BSF INTCON, GIE ; Enable Interrupts
; User code execution
BCF EECON1, WREN ; Disable writes on write complete (EEIF set)PIC18F2420/2520/4420/4520
DS39631E-page 86 © 2008 Microchip Technology Inc.
7.6 Operation During Code-Protect
Data EEPROM memory has its own code-protect bits in
Configuration Words. External read and write
operations are disabled if code protection is enabled.
The microcontroller itself can both read and write to the
internal data EEPROM, regardless of the state of the
code-protect Configuration bit. Refer to Section 23.0
“Special Features of the CPU” for additional
information.
7.7 Protection Against Spurious Write
There are conditions when the user may not want to write
to the data EEPROM memory. To protect against spurious
EEPROM writes, various mechanisms have been
implemented. On power-up, the WREN bit is cleared. In
addition, writes to the EEPROM are blocked during the
Power-up Timer period (TPWRT, parameter 33).
The write initiate sequence and the WREN bit together
help prevent an accidental write during brown-out,
power glitch or software malfunction.
7.8 Using the Data EEPROM
The data EEPROM is a high-endurance, byte
addressable array that has been optimized for the
storage of frequently changing information (e.g.,
program variables or other data that are updated
often). Frequently changing values will typically be
updated more often than specification D124. If this is
not the case, an array refresh must be performed. For
this reason, variables that change infrequently (such as
constants, IDs, calibration, etc.) should be stored in
Flash program memory.
A simple data EEPROM refresh routine is shown in
Example 7-3.
EXAMPLE 7-3: DATA EEPROM REFRESH ROUTINE
Note: If data EEPROM is only used to store
constants and/or data that changes rarely,
an array refresh is likely not required. See
specification D124.
CLRF EEADR ; Start at address 0
BCF EECON1, CFGS ; Set for memory
BCF EECON1, EEPGD ; Set for Data EEPROM
BCF INTCON, GIE ; Disable interrupts
BSF EECON1, WREN ; Enable writes
Loop ; Loop to refresh array
BSF EECON1, RD ; Read current address
MOVLW 55h ;
MOVWF EECON2 ; Write 55h
MOVLW 0AAh ;
MOVWF EECON2 ; Write 0AAh
BSF EECON1, WR ; Set WR bit to begin write
BTFSC EECON1, WR ; Wait for write to complete
BRA $-2
INCFSZ EEADR, F ; Increment address
BRA LOOP ; Not zero, do it again
BCF EECON1, WREN ; Disable writes
BSF INTCON, GIE ; Enable interrupts© 2008 Microchip Technology Inc. DS39631E-page 87
PIC18F2420/2520/4420/4520
TABLE 7-1: REGISTERS ASSOCIATED WITH DATA EEPROM MEMORY
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
EEADR EEPROM Address Register 51
EEDATA EEPROM Data Register 51
EECON2 EEPROM Control Register 2 (not a physical register) 51
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD 51
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during Flash/EEPROM access.PIC18F2420/2520/4420/4520
DS39631E-page 88 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 89
PIC18F2420/2520/4420/4520
8.0 8 x 8 HARDWARE MULTIPLIER
8.1 Introduction
All PIC18 devices include an 8 x 8 hardware multiplier
as part of the ALU. The multiplier performs an unsigned
operation and yields a 16-bit result that is stored in the
product register pair, PRODH:PRODL. The multiplier’s
operation does not affect any flags in the STATUS
register.
Making multiplication a hardware operation allows it to
be completed in a single instruction cycle. This has the
advantages of higher computational throughput and
reduced code size for multiplication algorithms and
allows the PIC18 devices to be used in many applications
previously reserved for digital signal processors.
A comparison of various hardware and software
multiply operations, along with the savings in memory
and execution time, is shown in Table 8-1.
8.2 Operation
Example 8-1 shows the instruction sequence for an 8 x 8
unsigned multiplication. Only one instruction is required
when one of the arguments is already loaded in the
WREG register.
Example 8-2 shows the sequence to do an 8 x 8 signed
multiplication. To account for the sign bits of the arguments,
each argument’s Most Significant bit (MSb) is
tested and the appropriate subtractions are done.
EXAMPLE 8-1: 8 x 8 UNSIGNED MULTIPLY
ROUTINE
EXAMPLE 8-2: 8 x 8 SIGNED MULTIPLY
ROUTINE
TABLE 8-1: PERFORMANCE COMPARISON FOR VARIOUS MULTIPLY OPERATIONS
MOVF ARG1, W ;
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
MOVF ARG1, W
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
BTFSC ARG2, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG1
MOVF ARG2, W
BTFSC ARG1, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG2
Routine Multiply Method
Program
Memory
(Words)
Cycles
(Max)
Time
@ 40 MHz @ 10 MHz @ 4 MHz
8 x 8 unsigned Without hardware multiply 13 69 6.9 μs 27.6 μs 69 μs
Hardware multiply 1 1 100 ns 400 ns 1 μs
8 x 8 signed Without hardware multiply 33 91 9.1 μs 36.4 μs 91 μs
Hardware multiply 6 6 600 ns 2.4 μs 6 μs
16 x 16 unsigned Without hardware multiply 21 242 24.2 μs 96.8 μs 242 μs
Hardware multiply 28 28 2.8 μs 11.2 μs 28 μs
16 x 16 signed Without hardware multiply 52 254 25.4 μs 102.6 μs 254 μs
Hardware multiply 35 40 4.0 μs 16.0 μs 40 μsPIC18F2420/2520/4420/4520
DS39631E-page 90 © 2008 Microchip Technology Inc.
Example 8-3 shows the sequence to do a 16 x 16
unsigned multiplication. Equation 8-1 shows the
algorithm that is used. The 32-bit result is stored in four
registers (RES<3:0>).
EQUATION 8-1: 16 x 16 UNSIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 8-3: 16 x 16 UNSIGNED
MULTIPLY ROUTINE
Example 8-4 shows the sequence to do a 16 x 16
signed multiply. Equation 8-2 shows the algorithm
used. The 32-bit result is stored in four registers
(RES<3:0>). To account for the sign bits of the arguments,
the MSb for each argument pair is tested and
the appropriate subtractions are done.
EQUATION 8-2: 16 x 16 SIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 8-4: 16 x 16 SIGNED MULTIPLY
ROUTINE
RES<3:0> = ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28) +
(ARG1L • ARG2H • 28) +
(ARG1L • ARG2L)
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
RES<3:0> = ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28) +
(ARG1L • ARG2H • 28) +
(ARG1L • ARG2L) +
(-1 • ARG2H<7> • ARG1H:ARG1L • 216) +
(-1 • ARG1H<7> • ARG2H:ARG2L • 216)
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
BTFSS ARG2H, 7 ; ARG2H:ARG2L neg?
BRA SIGN_ARG1 ; no, check ARG1
MOVF ARG1L, W ;
SUBWF RES2 ;
MOVF ARG1H, W ;
SUBWFB RES3
;
SIGN_ARG1
BTFSS ARG1H, 7 ; ARG1H:ARG1L neg?
BRA CONT_CODE ; no, done
MOVF ARG2L, W ;
SUBWF RES2 ;
MOVF ARG2H, W ;
SUBWFB RES3
;
CONT_CODE
:© 2008 Microchip Technology Inc. DS39631E-page 91
PIC18F2420/2520/4420/4520
9.0 INTERRUPTS
The PIC18F2420/2520/4420/4520 devices have
multiple interrupt sources and an interrupt priority
feature that allows most interrupt sources to be
assigned a high-priority level or a low-priority level. The
high-priority interrupt vector is at 0008h and the lowpriority
interrupt vector is at 0018h. High-priority
interrupt events will interrupt any low-priority interrupts
that may be in progress.
There are ten registers which are used to control
interrupt operation. These registers are:
• RCON
• INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
It is recommended that the Microchip header files supplied
with MPLAB® IDE be used for the symbolic bit
names in these registers. This allows the assembler/
compiler to automatically take care of the placement of
these bits within the specified register.
In general, interrupt sources have three bits to control
their operation. They are:
• Flag bit to indicate that an interrupt event
occurred
• Enable bit that allows program execution to
branch to the interrupt vector address when the
flag bit is set
• Priority bit to select high priority or low priority
The interrupt priority feature is enabled by setting the
IPEN bit (RCON<7>). When interrupt priority is
enabled, there are two bits which enable interrupts
globally. Setting the GIEH bit (INTCON<7>) enables all
interrupts that have the priority bit set (high priority).
Setting the GIEL bit (INTCON<6>) enables all
interrupts that have the priority bit cleared (low priority).
When the interrupt flag, enable bit and appropriate
global interrupt enable bit are set, the interrupt will vector
immediately to address 0008h or 0018h, depending
on the priority bit setting. Individual interrupts can be
disabled through their corresponding enable bits.
When the IPEN bit is cleared (default state), the
interrupt priority feature is disabled and interrupts are
compatible with PIC® mid-range devices. In Compatibility
mode, the interrupt priority bits for each source
have no effect. INTCON<6> is the PEIE bit, which
enables/disables all peripheral interrupt sources.
INTCON<7> is the GIE bit, which enables/disables all
interrupt sources. All interrupts branch to address
0008h in Compatibility mode.
When an interrupt is responded to, the global interrupt
enable bit is cleared to disable further interrupts. If the
IPEN bit is cleared, this is the GIE bit. If interrupt priority
levels are used, this will be either the GIEH or GIEL bit.
High-priority interrupt sources can interrupt a lowpriority
interrupt. Low-priority interrupts are not
processed while high-priority interrupts are in progress.
The return address is pushed onto the stack and the
PC is loaded with the interrupt vector address (0008h
or 0018h). Once in the Interrupt Service Routine, the
source(s) of the interrupt can be determined by polling
the interrupt flag bits. The interrupt flag bits must be
cleared in software before re-enabling interrupts to
avoid recursive interrupts.
The “return from interrupt” instruction, RETFIE, exits
the interrupt routine and sets the GIE bit (GIEH or GIEL
if priority levels are used), which re-enables interrupts.
For external interrupt events, such as the INTx pins or
the PORTB input change interrupt, the interrupt latency
will be three to four instruction cycles. The exact
latency is the same for one or two-cycle instructions.
Individual interrupt flag bits are set, regardless of the
status of their corresponding enable bit or the GIE bit.
Note: Do not use the MOVFF instruction to modify
any of the interrupt control registers while
any interrupt is enabled. Doing so may
cause erratic microcontroller behavior.PIC18F2420/2520/4420/4520
DS39631E-page 92 © 2008 Microchip Technology Inc.
FIGURE 9-1: PIC18 INTERRUPT LOGIC
TMR0IE
GIE/GIEH
PEIE/GIEL
Wake-up if in
Interrupt to CPU
Vector to Location
0008h
INT2IF
INT2IE
INT2IP
INT1IF
INT1IE
INT1IP
TMR0IF
TMR0IE
TMR0IP
RBIF
RBIE
RBIP
IPEN
TMR0IF
TMR0IP
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
RBIF
RBIE
RBIP
INT0IF
INT0IE
PEIE/GIE
Interrupt to CPU
Vector to Location
IPEN
IPEN
0018h
SSPIF
SSPIE
SSPIP
SSPIF
SSPIE
SSPIP
ADIF
ADIE
ADIP
RCIF
RCIE
RCIP
Additional Peripheral Interrupts
ADIF
ADIE
ADIP
High-Priority Interrupt Generation
Low-Priority Interrupt Generation
RCIF
RCIE
RCIP
Additional Peripheral Interrupts
Idle or Sleep modes
GIE/GIEH© 2008 Microchip Technology Inc. DS39631E-page 93
PIC18F2420/2520/4420/4520
9.1 INTCON Registers
The INTCON registers are readable and writable
registers, which contain various enable, priority and
flag bits.
Note: Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the global
enable bit. User software should ensure
the appropriate interrupt flag bits are clear
prior to enabling an interrupt. This feature
allows for software polling.
REGISTER 9-1: INTCON: INTERRUPT 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-x
GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 GIE/GIEH: Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all high-priority interrupts
0 = Disables all interrupts
bit 6 PEIE/GIEL: Peripheral Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low-priority peripheral interrupts
0 = Disables all low-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)
1 = At least one of the RB<7:4> pins changed state (must be cleared in software)
0 = None of the RB<7:4> pins have changed state
Note 1: A mismatch condition will continue to set this bit. Reading PORTB will end the mismatch condition and
allow the bit to be cleared. PIC18F2420/2520/4420/4520
DS39631E-page 94 © 2008 Microchip Technology Inc.
REGISTER 9-2: INTCON2: INTERRUPT CONTROL REGISTER 2
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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 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 Interrupt 0 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 5 INTEDG1: External Interrupt 1 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 4 INTEDG2: External Interrupt 2 Edge Select bit
1 = Interrupt on rising edge
0 = Interrupt on falling edge
bit 3 Unimplemented: Read as ‘0’
bit 2 TMR0IP: TMR0 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 Unimplemented: Read as ‘0’
bit 0 RBIP: RB Port Change Interrupt Priority bit
1 = High priority
0 = Low priority
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state of its corresponding
enable bit or the global enable bit. User software should ensure the appropriate interrupt flag bits are clear
prior to enabling an interrupt. This feature allows for software polling.© 2008 Microchip Technology Inc. DS39631E-page 95
PIC18F2420/2520/4420/4520
REGISTER 9-3: INTCON3: INTERRUPT CONTROL REGISTER 3
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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 INT2IP: INT2 External Interrupt Priority bit
1 = High priority
0 = Low priority
bit 6 INT1IP: INT1 External Interrupt Priority bit
1 = High priority
0 = Low priority
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
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state of its corresponding
enable bit or the global enable bit. User software should ensure the appropriate interrupt flag bits are clear
prior to enabling an interrupt. This feature allows for software polling.PIC18F2420/2520/4420/4520
DS39631E-page 96 © 2008 Microchip Technology Inc.
9.2 PIR Registers
The PIR registers contain the individual flag bits for the
peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Request Flag registers (PIR1 and PIR2).
Note 1: Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the Global
Interrupt Enable bit, GIE (INTCON<7>).
2: User software should ensure the appropriate
interrupt flag bits are cleared prior to
enabling an interrupt and after servicing
that interrupt.
REGISTER 9-4: PIR1: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 1
R/W-0 R/W-0 R-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit(1)
1 = A read or a write operation has taken place (must be cleared in software)
0 = No read or write has occurred
bit 6 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 5 RCIF: EUSART Receive Interrupt Flag bit
1 = The EUSART receive buffer, RCREG, is full (cleared when RCREG is read)
0 = The EUSART receive buffer is empty
bit 4 TXIF: EUSART Transmit Interrupt Flag bit
1 = The EUSART transmit buffer, TXREG, is empty (cleared when TXREG is written)
0 = The EUSART transmit buffer is full
bit 3 SSPIF: Master Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete (must be cleared in software)
0 = Waiting to transmit/receive
bit 2 CCP1IF: CCP1 Interrupt Flag bit
Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
PWM mode:
Unused in this mode.
bit 1 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 0 TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed (must be cleared in software)
0 = TMR1 register did not overflow
Note 1: This bit is unimplemented on 28-pin devices and will read as ‘0’.© 2008 Microchip Technology Inc. DS39631E-page 97
PIC18F2420/2520/4420/4520
REGISTER 9-5: PIR2: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 2
R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 OSCFIF: Oscillator Fail Interrupt Flag bit
1 = Device oscillator failed, clock input has changed to INTOSC (must be cleared in software)
0 = Device clock operating
bit 6 CMIF: Comparator Interrupt Flag bit
1 = Comparator input has changed (must be cleared in software)
0 = Comparator input has not changed
bit 5 Unimplemented: Read as ‘0’
bit 4 EEIF: Data EEPROM/Flash Write Operation Interrupt Flag bit
1 = The write operation is complete (must be cleared in software)
0 = The write operation is not complete or has not been started
bit 3 BCLIF: Bus Collision Interrupt Flag bit
1 = A bus collision occurred (must be cleared in software)
0 = No bus collision occurred
bit 2 HLVDIF: High/Low-Voltage Detect Interrupt Flag bit
1 = A high/low-voltage condition occurred (direction determined by VDIRMAG bit, HLVDCON<7>)
0 = A high/low-voltage condition has not occurred
bit 1 TMR3IF: TMR3 Overflow Interrupt Flag bit
1 = TMR3 register overflowed (must be cleared in software)
0 = TMR3 register did not overflow
bit 0 CCP2IF: CCP2 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. PIC18F2420/2520/4420/4520
DS39631E-page 98 © 2008 Microchip Technology Inc.
9.3 PIE Registers
The PIE registers contain the individual enable bits for
the peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Enable registers (PIE1 and PIE2). When IPEN = 0, the
PEIE bit must be set to enable any of these peripheral
interrupts.
REGISTER 9-6: PIE1: PERIPHERAL INTERRUPT ENABLE REGISTER 1
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 PSPIE: Parallel Slave Port Read/Write Interrupt Enable bit(1)
1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt
bit 6 ADIE: A/D Converter Interrupt Enable bit
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
bit 5 RCIE: EUSART Receive Interrupt Enable bit
1 = Enables the EUSART receive interrupt
0 = Disables the EUSART receive interrupt
bit 4 TXIE: EUSART Transmit Interrupt Enable bit
1 = Enables the EUSART transmit interrupt
0 = Disables the EUSART transmit interrupt
bit 3 SSPIE: Master Synchronous Serial Port Interrupt Enable bit
1 = Enables the MSSP interrupt
0 = Disables the MSSP interrupt
bit 2 CCP1IE: CCP1 Interrupt Enable bit
1 = Enables the CCP1 interrupt
0 = Disables the CCP1 interrupt
bit 1 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 0 TMR1IE: TMR1 Overflow Interrupt Enable bit
1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt
Note 1: This bit is unimplemented on 28-pin devices and will read as ‘0’.© 2008 Microchip Technology Inc. DS39631E-page 99
PIC18F2420/2520/4420/4520
REGISTER 9-7: PIE2: PERIPHERAL INTERRUPT ENABLE REGISTER 2
R/W-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 OSCFIE: Oscillator Fail Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 6 CMIE: Comparator Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 5 Unimplemented: Read as ‘0’
bit 4 EEIE: Data EEPROM/Flash Write Operation Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 3 BCLIE: Bus Collision Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 2 HLVDIE: High/Low-Voltage Detect Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 1 TMR3IE: TMR3 Overflow Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 0 CCP2IE: CCP2 Interrupt Enable bit
1 = Enabled
0 = DisabledPIC18F2420/2520/4420/4520
DS39631E-page 100 © 2008 Microchip Technology Inc.
9.4 IPR Registers
The IPR registers contain the individual priority bits for
the peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Priority registers (IPR1 and IPR2). Using the priority bits
requires that the Interrupt Priority Enable (IPEN) bit be
set.
REGISTER 9-8: IPR1: PERIPHERAL INTERRUPT PRIORITY REGISTER 1
R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 PSPIP: Parallel Slave Port Read/Write Interrupt Priority bit(1)
1 = High priority
0 = Low priority
bit 6 ADIP: A/D Converter Interrupt Priority bit
1 = High priority
0 = Low priority
bit 5 RCIP: EUSART Receive Interrupt Priority bit
1 = High priority
0 = Low priority
bit 4 TXIP: EUSART Transmit Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 SSPIP: Master Synchronous Serial Port Interrupt Priority bit
1 = High priority
0 = Low priority
bit 2 CCP1IP: CCP1 Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR2IP: TMR2 to PR2 Match Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 TMR1IP: TMR1 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
Note 1: This bit is unimplemented on 28-pin devices and will read as ‘0’.© 2008 Microchip Technology Inc. DS39631E-page 101
PIC18F2420/2520/4420/4520
REGISTER 9-9: IPR2: PERIPHERAL INTERRUPT PRIORITY REGISTER 2
R/W-1 R/W-1 U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 OSCFIP: Oscillator Fail Interrupt Priority bit
1 = High priority
0 = Low priority
bit 6 CMIP: Comparator Interrupt Priority bit
1 = High priority
0 = Low priority
bit 5 Unimplemented: Read as ‘0’
bit 4 EEIP: Data EEPROM/Flash Write Operation Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 BCLIP: Bus Collision Interrupt Priority bit
1 = High priority
0 = Low priority
bit 2 HLVDIP: High/Low-Voltage Detect Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR3IP: TMR3 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 CCP2IP: CCP2 Interrupt Priority bit
1 = High priority
0 = Low priorityPIC18F2420/2520/4420/4520
DS39631E-page 102 © 2008 Microchip Technology Inc.
9.5 RCON Register
The RCON register contains flag bits which are used to
determine the cause of the last Reset or wake-up from
Idle or Sleep modes. RCON also contains the IPEN bit
which enables interrupt priorities.
The operation of the SBOREN bit and the Reset flag
bits is discussed in more detail in Section 4.1 “RCON
Register”.
REGISTER 9-10: RCON: RESET CONTROL REGISTER
R/W-0 R/W-1(1) U-0 R/W-1 R-1 R-1 R/W-0(1) R/W-0
IPEN SBOREN — RI TO PD POR BOR
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (PIC16CXXX Compatibility mode)
bit 6 SBOREN: Software BOR Enable bit(1)
For details of bit operation, see Register 4-1.
bit 5 Unimplemented: Read as ‘0’
bit 4 RI: RESET Instruction Flag bit
For details of bit operation, see Register 4-1.
bit 3 TO: Watchdog Timer Time-out Flag bit
For details of bit operation, see Register 4-1.
bit 2 PD: Power-Down Detection Flag bit
For details of bit operation, see Register 4-1.
bit 1 POR: Power-on Reset Status bit(1)
For details of bit operation, see Register 4-1.
bit 0 BOR: Brown-out Reset Status bit
For details of bit operation, see Register 4-1.
Note 1: Actual Reset values are determined by device configuration and the nature of the device Reset. See
Register 4-1 for additional information.© 2008 Microchip Technology Inc. DS39631E-page 103
PIC18F2420/2520/4420/4520
9.6 INTx Pin Interrupts
External interrupts on the RB0/INT0, RB1/INT1 and
RB2/INT2 pins are edge-triggered. If the corresponding
INTEDGx bit in the INTCON2 register is set (= 1), the
interrupt is triggered by a rising edge; if the bit is clear,
the trigger is on the falling edge. When a valid edge
appears on the RBx/INTx pin, the corresponding flag
bit, INTxIF, is set. This interrupt can be disabled by
clearing the corresponding enable bit, INTxIE. Flag bit,
INTxIF, must be cleared in software in the Interrupt
Service Routine before re-enabling the interrupt.
All external interrupts (INT0, INT1 and INT2) can wakeup
the processor from Idle or Sleep modes if bit INTxIE
was set prior to going into those modes. If the Global
Interrupt Enable bit, GIE, is set, the processor will
branch to the interrupt vector following wake-up.
Interrupt priority for INT1 and INT2 is determined by the
value contained in the Interrupt Priority bits, INT1IP
(INTCON3<6>) and INT2IP (INTCON3<7>). There
is no priority bit associated with INT0. It is always a
high-priority interrupt source.
9.7 TMR0 Interrupt
In 8-bit mode (which is the default), an overflow in the
TMR0 register (FFh → 00h) will set flag bit, TMR0IF. In
16-bit mode, an overflow in the TMR0H:TMR0L register
pair (FFFFh → 0000h) will set TMR0IF. The interrupt
can be enabled/disabled by setting/clearing enable bit,
TMR0IE (INTCON<5>). Interrupt priority for Timer0 is
determined by the value contained in the interrupt
priority bit, TMR0IP (INTCON2<2>). See Section 11.0
“Timer0 Module” for further details on the Timer0
module.
9.8 PORTB Interrupt-on-Change
An input change on PORTB<7:4> sets flag bit, RBIF
(INTCON<0>). The interrupt can be enabled/disabled
by setting/clearing enable bit, RBIE (INTCON<3>).
Interrupt priority for PORTB interrupt-on-change is
determined by the value contained in the interrupt
priority bit, RBIP (INTCON2<0>).
9.9 Context Saving During Interrupts
During interrupts, the return PC address is saved on
the stack. Additionally, the WREG, STATUS and BSR
registers are saved on the Fast Return Stack. If a fast
return from interrupt is not used (see Section 5.3
“Data Memory Organization”), the user may need to
save the WREG, STATUS and BSR registers on entry
to the Interrupt Service Routine. Depending on the
user’s application, other registers may also need to be
saved. Example 9-1 saves and restores the WREG,
STATUS and BSR registers during an Interrupt Service
Routine.
EXAMPLE 9-1: SAVING STATUS, WREG AND BSR REGISTERS IN RAM
MOVWF W_TEMP ; W_TEMP is in virtual bank
MOVFF STATUS, STATUS_TEMP ; STATUS_TEMP located anywhere
MOVFF BSR, BSR_TEMP ; BSR_TMEP located anywhere
;
; USER ISR CODE
;
MOVFF BSR_TEMP, BSR ; Restore BSR
MOVF W_TEMP, W ; Restore WREG
MOVFF STATUS_TEMP, STATUS ; Restore STATUSPIC18F2420/2520/4420/4520
DS39631E-page 104 © 2008 Microchip Technology Inc.
NOTES: © 2008 Microchip Technology Inc. DS39631E-page 105
PIC18F2420/2520/4420/4520
10.0 I/O PORTS
Depending on the device selected and features
enabled, there are up to five ports available. Some pins
of the I/O ports are multiplexed with an alternate
function from the peripheral features on the device. In
general, when a peripheral is enabled, that pin may not
be used as a general purpose I/O pin.
Each port has three registers for its operation. These
registers are:
• TRIS register (Data Direction register)
• PORT register (reads the levels on the pins of the
device)
• LAT register (Data Latch register)
The Data Latch (LAT register) is useful for read-modifywrite
operations on the value that the I/O pins are
driving.
A simplified model of a generic I/O port, without the
interfaces to other peripherals, is shown in Figure 10-1.
FIGURE 10-1: GENERIC I/O PORT
OPERATION
10.1 PORTA, TRISA and LATA Registers
PORTA is an 8-bit wide, bidirectional port. The corresponding
Data Direction register is TRISA. Setting a
TRISA bit (= 1) will make the corresponding PORTA pin
an input (i.e., put the corresponding output driver in a
high-impedance mode). Clearing a TRISA bit (= 0) will
make the corresponding PORTA pin an output (i.e., put
the contents of the output latch on the selected pin).
Reading the PORTA register reads the status of the
pins, whereas writing to it, will write to the port latch.
The Data Latch (LATA) register is also memory mapped.
Read-modify-write operations on the LATA register read
and write the latched output value for PORTA.
The RA4 pin is multiplexed with the Timer0 module
clock input and one of the comparator outputs to
become the RA4/T0CKI/C1OUT pin. Pins RA6 and
RA7 are multiplexed with the main oscillator pins; they
are enabled as oscillator or I/O pins by the selection of
the main oscillator in the Configuration register (see
Section 23.1 “Configuration Bits” for details). When
they are not used as port pins, RA6 and RA7 and their
associated TRIS and LAT bits are read as ‘0’.
The other PORTA pins are multiplexed with analog
inputs, the analog VREF+ and VREF- inputs and the comparator
voltage reference output. The operation of pins
RA<3:0> and RA5 as A/D Converter inputs is selected
by clearing or setting the control bits in the ADCON1
register (A/D Control Register 1).
Pins RA0 through RA5 may also be used as comparator
inputs or outputs by setting the appropriate bits in the
CMCON register. To use RA<3:0> as digital inputs, it is
also necessary to turn off the comparators.
The RA4/T0CKI/C1OUT pin is a Schmitt Trigger input.
All other PORTA pins have TTL input levels and full
CMOS output drivers.
The TRISA register controls the direction of the PORTA
pins, even when they are being used as analog inputs.
The user must ensure the bits in the TRISA register are
maintained set when using them as analog inputs.
EXAMPLE 10-1: INITIALIZING PORTA
Data
Bus
WR LAT
WR TRIS
RD Port
Data Latch
TRIS Latch
RD TRIS
Input
Buffer
I/O pin(1)
D Q
CK
D Q
CK
EN
Q D
EN
RD LAT
or Port
Note 1: I/O pins have diode protection to VDD and VSS.
Note: On a Power-on Reset, RA5 and RA<3:0>
are configured as analog inputs and read
as ‘0’. RA4 is configured as a digital input.
CLRF PORTA ; Initialize PORTA by
; clearing output
; data latches
CLRF LATA ; Alternate method
; to clear output
; data latches
MOVLW 07h ; Configure A/D
MOVWF ADCON1 ; for digital inputs
MOVWF 07h ; Configure comparators
MOVWF CMCON ; for digital input
MOVLW 0CFh ; Value used to
; initialize data
; direction
MOVWF TRISA ; Set RA<3:0> as inputs
; RA<5:4> as outputsPIC18F2420/2520/4420/4520
DS39631E-page 106 © 2008 Microchip Technology Inc.
TABLE 10-1: PORTA I/O SUMMARY
Pin Function TRIS
Setting I/O I/O
Type Description
RA0/AN0 RA0 0 O DIG LATA<0> data output; not affected by analog input.
1 I TTL PORTA<0> data input; disabled when analog input enabled.
AN0 1 I ANA A/D input channel 0 and comparator C1- input. Default input
configuration on POR; does not affect digital output.
RA1/AN1 RA1 0 O DIG LATA<1> data output; not affected by analog input.
1 I TTL PORTA<1> data input; disabled when analog input enabled.
AN1 1 I ANA A/D input channel 1 and comparator C2- input. Default input
configuration on POR; does not affect digital output.
RA2/AN2/
VREF-/CVREF
RA2 0 O DIG LATA<2> data output; not affected by analog input. Disabled when
CVREF output enabled.
1 I TTL PORTA<2> data input. Disabled when analog functions enabled;
disabled when CVREF output enabled.
AN2 1 I ANA A/D input channel 2 and comparator C2+ input. Default input
configuration on POR; not affected by analog output.
VREF- 1 I ANA A/D and comparator voltage reference low input.
CVREF x O ANA Comparator voltage reference output. Enabling this feature disables
digital I/O.
RA3/AN3/VREF+ RA3 0 O DIG LATA<3> data output; not affected by analog input.
1 I TTL PORTA<3> data input; disabled when analog input enabled.
AN3 1 I ANA A/D input channel 3 and comparator C1+ input. Default input
configuration on POR.
VREF+ 1 I ANA A/D and comparator voltage reference high input.
RA4/T0CKI/C1OUT RA4 0 O DIG LATA<4> data output.
1 I ST PORTA<4> data input; default configuration on POR.
T0CKI 1 I ST Timer0 clock input.
C1OUT 0 O DIG Comparator 1 output; takes priority over port data.
RA5/AN4/SS/
HLVDIN/C2OUT
RA5 0 O DIG LATA<5> data output; not affected by analog input.
1 I TTL PORTA<5> data input; disabled when analog input enabled.
AN4 1 I ANA A/D input channel 4. Default configuration on POR.
SS 1 I TTL Slave select input for MSSP module.
HLVDIN 1 I ANA High/Low-Voltage Detect external trip point input.
C2OUT 0 O DIG Comparator 2 output; takes priority over port data.
OSC2/CLKO/RA6 RA6 0 O DIG LATA<6> data output. Enabled in RCIO, INTIO2 and ECIO modes only.
1 I TTL PORTA<6> data input. Enabled in RCIO, INTIO2 and ECIO modes
only.
OSC2 x O ANA Main oscillator feedback output connection (XT, HS and LP modes).
CLKO x O DIG System cycle clock output (FOSC/4) in RC, INTIO1 and EC Oscillator
modes.
OSC1/CLKI/RA7 RA7 0 O DIG LATA<7> data output. Disabled in external oscillator modes.
1 I TTL PORTA<7> data input. Disabled in external oscillator modes.
OSC1 x I ANA Main oscillator input connection.
CLKI x I ANA Main clock input connection.
Legend: DIG = Digital level output; TTL = TTL input buffer; ST = Schmitt Trigger input buffer; ANA = Analog level input/output;
x = Don’t care (TRIS bit does not affect port direction or is overridden for this option).© 2008 Microchip Technology Inc. DS39631E-page 107
PIC18F2420/2520/4420/4520
TABLE 10-2: SUMMARY OF REGISTERS ASSOCIATED WITH PORTA
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTA RA7(1) RA6(1) RA5 RA4 RA3 RA2 RA1 RA0 52
LATA LATA7(1) LATA6(1) PORTA Data Latch Register (Read and Write to Data Latch) 52
TRISA TRISA7(1) TRISA6(1) PORTA Data Direction Register 52
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 51
CMCON C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0 51
CVRCON CVREN CVROE CVRR CVRSS CVR3 CVR2 CVR1 CVR0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by PORTA.
Note 1: RA<7:6> and their associated latch and data direction bits are enabled as I/O pins based on oscillator
configuration; otherwise, they are read as ‘0’.PIC18F2420/2520/4420/4520
DS39631E-page 108 © 2008 Microchip Technology Inc.
10.2 PORTB, TRISB and LATB
Registers
PORTB is an 8-bit wide, bidirectional port. The corresponding
Data Direction register is TRISB. Setting a
TRISB bit (= 1) will make the corresponding PORTB
pin an input (i.e., put the corresponding output driver in
a high-impedance mode). Clearing a TRISB bit (= 0)
will make the corresponding PORTB pin an output (i.e.,
put the contents of the output latch on the selected pin).
The Data Latch register (LATB) is also memory
mapped. Read-modify-write operations on the LATB
register read and write the latched output value for
PORTB.
EXAMPLE 10-2: INITIALIZING PORTB
Each of the PORTB pins has a weak internal pull-up. A
single control bit can turn on all the pull-ups. This is
performed by clearing bit, RBPU (INTCON2<7>). The
weak pull-up is automatically turned off when the port
pin is configured as an output. The pull-ups are
disabled on a Power-on Reset.
Four of the PORTB pins (RB<7:4>) have an interrupton-change
feature. Only pins configured as inputs can
cause this interrupt to occur (i.e., any RB<7:4> pin
configured as an output is excluded from the interrupton-change
comparison). The input pins (of RB<7:4>)
are compared with the old value latched on the last
read of PORTB. The “mismatch” outputs of RB<7:4>
are ORed together to generate the RB Port Change
Interrupt with Flag bit, RBIF (INTCON<0>).
This interrupt can wake the device from the Sleep
mode, or any of the Idle modes. The user, in the
Interrupt Service Routine, can clear the interrupt in the
following manner:
a) Any read or write of PORTB (except with the
MOVFF (ANY), PORTB instruction).
b) Clear flag bit, RBIF.
A mismatch condition will continue to set flag bit, RBIF.
Reading PORTB will end the mismatch condition and
allow flag bit, RBIF, to be cleared.
The interrupt-on-change feature is recommended for
wake-up on key depression operation and operations
where PORTB is only used for the interrupt-on-change
feature. Polling of PORTB is not recommended while
using the interrupt-on-change feature.
RB3 can be configured by the Configuration bit,
CCP2MX, as the alternate peripheral pin for the CCP2
module (CCP2MX = 0).
Note: On a Power-on Reset, RB<4:0> are
configured as analog inputs by default and
read as ‘0’; RB<7:5> are configured as
digital inputs.
By programming the Configuration bit,
PBADEN, RB<4:0> will alternatively be
configured as digital inputs on POR.
CLRF PORTB ; Initialize PORTB by
; clearing output
; data latches
CLRF LATB ; Alternate method
; to clear output
; data latches
MOVLW 0Fh ; Set RB<4:0> as
MOVWF ADCON1 ; digital I/O pins
; (required if config bit
; PBADEN is set)
MOVLW 0CFh ; Value used to
; initialize data
; direction
MOVWF TRISB ; Set RB<3:0> as inputs
; RB<5:4> as outputs
; RB<7:6> as inputs© 2008 Microchip Technology Inc. DS39631E-page 109
PIC18F2420/2520/4420/4520
TABLE 10-3: PORTB I/O SUMMARY
Pin Function TRIS
Setting I/O I/O
Type Description
RB0/INT0/FLT0/
AN12
RB0 0 O DIG LATB<0> data output; not affected by analog input.
1 I TTL PORTB<0> data input; weak pull-up when RBPU bit is cleared.
Disabled when analog input enabled.(1)
INT0 1 I ST External interrupt 0 input.
FLT0 1 I ST Enhanced PWM Fault input (ECCP1 module); enabled in software.
AN12 1 I ANA A/D input channel 12.(1)
RB1/INT1/AN10 RB1 0 O DIG LATB<1> data output; not affected by analog input.
1 I TTL PORTB<1> data input; weak pull-up when RBPU bit is cleared.
Disabled when analog input enabled.(1)
INT1 1 I ST External Interrupt 1 input.
AN10 1 I ANA A/D input channel 10.(1)
RB2/INT2/AN8 RB2 0 O DIG LATB<2> data output; not affected by analog input.
1 I TTL PORTB<2> data input; weak pull-up when RBPU bit is cleared.
Disabled when analog input enabled.(1)
INT2 1 I ST External interrupt 2 input.
AN8 1 I ANA A/D input channel 8.(1)
RB3/AN9/CCP2 RB3 0 O DIG LATB<3> data output; not affected by analog input.
1 I TTL PORTB<3> data input; weak pull-up when RBPU bit is cleared.
Disabled when analog input enabled.(1)
AN9 1 I ANA A/D input channel 9.(1)
CCP2(2) 0 O DIG CCP2 compare and PWM output.
1 I ST CCP2 capture input
RB4/KBI0/AN11 RB4 0 O DIG LATB<4> data output; not affected by analog input.
1 I TTL PORTB<4> data input; weak pull-up when RBPU bit is cleared.
Disabled when analog input enabled.(1)
KBI0 1 I TTL Interrupt-on-pin change.
AN11 1 I ANA A/D input channel 11.(1)
RB5/KBI1/PGM RB5 0 O DIG LATB<5> data output.
1 I TTL PORTB<5> data input; weak pull-up when RBPU bit is cleared.
KBI1 1 I TTL Interrupt-on-pin change.
PGM x I ST Single-Supply In-Circuit Serial Programming™ mode entry (ICSP™).
Enabled by LVP Configuration bit; all other pin functions disabled.
RB6/KBI2/PGC RB6 0 O DIG LATB<6> data output.
1 I TTL PORTB<6> data input; weak pull-up when RBPU bit is cleared.
KBI2 1 I TTL Interrupt-on-pin change.
PGC x I ST Serial execution (ICSP) clock input for ICSP and ICD operation.(3)
RB7/KBI3/PGD RB7 0 O DIG LATB<7> data output.
1 I TTL PORTB<7> data input; weak pull-up when RBPU bit is cleared.
KBI3 1 I TTL Interrupt-on-pin change.
PGD x O DIG Serial execution data output for ICSP and ICD operation.(3)
x I ST Serial execution data input for ICSP and ICD operation.(3)
Legend: DIG = Digital level output; TTL = TTL input buffer; ST = Schmitt Trigger input buffer; ANA = Analog level input/output;
x = Don’t care (TRIS bit does not affect port direction or is overridden for this option).
Note 1: Configuration on POR is determined by the PBADEN Configuration bit. Pins are configured as analog inputs by default
when PBADEN is set and digital inputs when PBADEN is cleared.
2: Alternate assignment for CCP2 when the CCP2MX Configuration bit is ‘0’. Default assignment is RC1.
3: All other pin functions are disabled when ICSP or ICD are enabled.PIC18F2420/2520/4420/4520
DS39631E-page 110 © 2008 Microchip Technology Inc.
TABLE 10-4: SUMMARY OF REGISTERS ASSOCIATED WITH PORTB
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 52
LATB PORTB Data Latch Register (Read and Write to Data Latch) 52
TRISB PORTB Data Direction Register 52
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 49
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 49
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by PORTB.© 2008 Microchip Technology Inc. DS39631E-page 111
PIC18F2420/2520/4420/4520
10.3 PORTC, TRISC and LATC
Registers
PORTC is an 8-bit wide, bidirectional port. The corresponding
Data Direction register is TRISC. Setting a
TRISC bit (= 1) will make the corresponding PORTC
pin an input (i.e., put the corresponding output driver in
a high-impedance mode). Clearing a TRISC bit (= 0)
will make the corresponding PORTC pin an output (i.e.,
put the contents of the output latch on the selected pin).
The Data Latch register (LATC) is also memory
mapped. Read-modify-write operations on the LATC
register read and write the latched output value for
PORTC.
PORTC is multiplexed with several peripheral functions
(Table 10-5). The pins have Schmitt Trigger input buffers.
RC1 is normally configured by Configuration bit,
CCP2MX, as the default peripheral pin of the CCP2
module (default/erased state, CCP2MX = 1).
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. The user should refer to the corresponding
peripheral section for additional information.
The contents of the TRISC register are affected by
peripheral overrides. Reading TRISC always returns
the current contents, even though a peripheral device
may be overriding one or more of the pins.
EXAMPLE 10-3: INITIALIZING PORTC
Note: On a Power-on Reset, these pins are
configured as digital inputs.
CLRF PORTC ; Initialize PORTC by
; clearing output
; data latches
CLRF LATC ; Alternate method
; to clear output
; data latches
MOVLW 0CFh ; Value used to
; initialize data
; direction
MOVWF TRISC ; Set RC<3:0> as inputs
; RC<5:4> as outputs
; RC<7:6> as inputsPIC18F2420/2520/4420/4520
DS39631E-page 112 © 2008 Microchip Technology Inc.
TABLE 10-5: PORTC I/O SUMMARY
Pin Function TRIS
Setting I/O I/O
Type Description
RC0/T1OSO/
T13CKI
RC0 0 O DIG LATC<0> data output.
1 I ST PORTC<0> data input.
T1OSO x O ANA Timer1 oscillator output; enabled when Timer1 oscillator enabled.
Disables digital I/O.
T13CKI 1 I ST Timer1/Timer3 counter input.
RC1/T1OSI/CCP2 RC1 0 O DIG LATC<1> data output.
1 I ST PORTC<1> data input.
T1OSI x I ANA Timer1 oscillator input; enabled when Timer1 oscillator enabled.
Disables digital I/O.
CCP2(1) 0 O DIG CCP2 compare and PWM output; takes priority over port data.
1 I ST CCP2 capture input.
RC2/CCP1/P1A RC2 0 O DIG LATC<2> data output.
1 I ST PORTC<2> data input.
CCP1 0 O DIG ECCP1 compare or PWM output; takes priority over port data.
1 I ST ECCP1 capture input.
P1A(2) 0 O DIG ECCP1 Enhanced PWM output, channel A. May be configured for
tri-state during Enhanced PWM shutdown events. Takes priority over
port data.
RC3/SCK/SCL RC3 0 O DIG LATC<3> data output.
1 I ST PORTC<3> data input.
SCK 0 O DIG SPI clock output (MSSP module); takes priority over port data.
1 I ST SPI clock input (MSSP module).
SCL 0 O DIG I2C™ clock output (MSSP module); takes priority over port data.
1 I I2C/SMB I2C clock input (MSSP module); input type depends on module setting.
RC4/SDI/SDA RC4 0 O DIG LATC<4> data output.
1 I ST PORTC<4> data input.
SDI 1 I ST SPI data input (MSSP module).
SDA 1 O DIG I2C data output (MSSP module); takes priority over port data.
1 I I2C/SMB I2C data input (MSSP module); input type depends on module setting.
RC5/SDO RC5 0 O DIG LATC<5> data output.
1 I ST PORTC<5> data input.
SDO 0 O DIG SPI data output (MSSP module); takes priority over port data.
RC6/TX/CK RC6 0 O DIG LATC<6> data output.
1 I ST PORTC<6> data input.
TX 1 O DIG Asynchronous serial transmit data output (EUSART module);
takes priority over port data. User must configure as output.
CK 1 O DIG Synchronous serial clock output (EUSART module); takes priority
over port data.
1 I ST Synchronous serial clock input (EUSART module).
RC7/RX/DT RC7 0 O DIG LATC<7> data output.
1 I ST PORTC<7> data input.
RX 1 I ST Asynchronous serial receive data input (EUSART module).
DT 1 O DIG Synchronous serial data output (EUSART module); takes priority over
port data.
1 I ST Synchronous serial data input (EUSART module). User must
configure as an input.
Legend: DIG = Digital level output; TTL = TTL input buffer; ST = Schmitt Trigger input buffer; ANA = Analog level input/output;
I
2C/SMB = I2C/SMBus input buffer; x = Don’t care (TRIS bit does not affect port direction or is overridden for this option).
Note 1: Default assignment for CCP2 when the CCP2MX Configuration bit is set. Alternate assignment is RB3.
2: Enhanced PWM output is available only on PIC18F4520 devices.© 2008 Microchip Technology Inc. DS39631E-page 113
PIC18F2420/2520/4420/4520
TABLE 10-6: SUMMARY OF REGISTERS ASSOCIATED WITH PORTC
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTC RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0 52
LATC PORTC Data Latch Register (Read and Write to Data Latch) 52
TRISC PORTC Data Direction Register 52PIC18F2420/2520/4420/4520
DS39631E-page 114 © 2008 Microchip Technology Inc.
10.4 PORTD, TRISD and LATD
Registers
PORTD is an 8-bit wide, bidirectional port. The corresponding
Data Direction register is TRISD. Setting a
TRISD bit (= 1) will make the corresponding PORTD
pin an input (i.e., put the corresponding output driver in
a high-impedance mode). Clearing a TRISD bit (= 0)
will make the corresponding PORTD pin an output (i.e.,
put the contents of the output latch on the selected pin).
The Data Latch register (LATD) is also memory
mapped. Read-modify-write operations on the LATD
register read and write the latched output value for
PORTD.
All pins on PORTD are implemented with Schmitt Trigger
input buffers. Each pin is individually configurable
as an input or output.
Three of the PORTD pins are multiplexed with outputs
P1B, P1C and P1D of the Enhanced CCP module. The
operation of these additional PWM output pins is
covered in greater detail in Section 16.0 “Enhanced
Capture/Compare/PWM (ECCP) Module”.
PORTD can also be configured as an 8-bit wide microprocessor
port (Parallel Slave Port) by setting control
bit, PSPMODE (TRISE<4>). In this mode, the input
buffers are TTL. See Section 10.6 “Parallel Slave
Port” for additional information on the Parallel Slave
Port (PSP).
EXAMPLE 10-4: INITIALIZING PORTD
Note: PORTD is only available on 40/44-pin
devices.
Note: On a Power-on Reset, these pins are
configured as digital inputs.
Note: When the enhanced PWM mode is used
with either dual or quad outputs, the PSP
functions of PORTD are automatically
disabled.
CLRF PORTD ; Initialize PORTD by
; clearing output
; data latches
CLRF LATD ; Alternate method
; to clear output
; data latches
MOVLW 0CFh ; Value used to
; initialize data
; direction
MOVWF TRISD ; Set RD<3:0> as inputs
; RD<5:4> as outputs
; RD<7:6> as inputs© 2008 Microchip Technology Inc. DS39631E-page 115
PIC18F2420/2520/4420/4520
TABLE 10-7: PORTD I/O SUMMARY
Pin Function TRIS
Setting I/O I/O
Type Description
RD0/PSP0 RD0 0 O DIG LATD<0> data output.
1 I ST PORTD<0> data input.
PSP0 x O DIG PSP read data output (LATD<0>); takes priority over port data.
x I TTL PSP write data input.
RD1/PSP1 RD1 0 O DIG LATD<1> data output.
1 I ST PORTD<1> data input.
PSP1 x O DIG PSP read data output (LATD<1>); takes priority over port data.
x I TTL PSP write data input.
RD2/PSP2 RD2 0 O DIG LATD<2> data output.
1 I ST PORTD<2> data input.
PSP2 x O DIG PSP read data output (LATD<2>); takes priority over port data.
x I TTL PSP write data input.
RD3/PSP3 RD3 0 O DIG LATD<3> data output.
1 I ST PORTD<3> data input.
PSP3 x O DIG PSP read data output (LATD<3>); takes priority over port data.
x I TTL PSP write data input.
RD4/PSP4 RD4 0 O DIG LATD<4> data output.
1 I ST PORTD<4> data input.
PSP4 x O DIG PSP read data output (LATD<4>); takes priority over port data.
x I TTL PSP write data input.
RD5/PSP5/P1B RD5 0 O DIG LATD<5> data output.
1 I ST PORTD<5> data input.
PSP5 x O DIG PSP read data output (LATD<5>); takes priority over port data.
x I TTL PSP write data input.
P1B 0 O DIG ECCP1 Enhanced PWM output, channel B; takes priority over port and
PSP data. May be configured for tri-state during Enhanced PWM
shutdown events.
RD6/PSP6/P1C RD6 0 O DIG LATD<6> data output.
1 I ST PORTD<6> data input.
PSP6 x O DIG PSP read data output (LATD<6>); takes priority over port data.
x I TTL PSP write data input.
P1C 0 O DIG ECCP1 Enhanced PWM output, channel C; takes priority over port and
PSP data. May be configured for tri-state during Enhanced PWM
shutdown events.
RD7/PSP7/P1D RD7 0 O DIG LATD<7> data output.
1 I ST PORTD<7> data input.
PSP7 x O DIG PSP read data output (LATD<7>); takes priority over port data.
x I TTL PSP write data input.
P1D 0 O DIG ECCP1 Enhanced PWM output, channel D; takes priority over port and
PSP data. May be configured for tri-state during Enhanced PWM
shutdown events.
Legend: DIG = Digital level output; TTL = TTL input buffer; ST = Schmitt Trigger input buffer; x = Don’t care
(TRIS bit does not affect port direction or is overridden for this option).PIC18F2420/2520/4420/4520
DS39631E-page 116 © 2008 Microchip Technology Inc.
TABLE 10-8: SUMMARY OF REGISTERS ASSOCIATED WITH PORTD
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTD RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 52
LATD PORTD Data Latch Register (Read and Write to Data Latch) 52
TRISD PORTD Data Direction Register 52
TRISE(1) IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0 52
CCP1CON P1M1(1) P1M0(1) DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by PORTD.
Note 1: These registers and/or bits are unimplemented on 28-oin devices.© 2008 Microchip Technology Inc. DS39631E-page 117
PIC18F2420/2520/4420/4520
10.5 PORTE, TRISE and LATE
Registers
Depending on the particular PIC18F2420/2520/4420/
4520 device selected, PORTE is implemented in two
different ways.
For 40/44-pin devices, PORTE is a 4-bit wide port.
Three pins (RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/
AN7) are individually configurable as inputs or outputs.
These pins have Schmitt Trigger input buffers. When
selected as an analog input, these pins will read as ‘0’s.
The corresponding Data Direction register is TRISE.
Setting a TRISE bit (= 1) will make the corresponding
PORTE pin an input (i.e., put the corresponding output
driver in a high-impedance mode). Clearing a TRISE bit
(= 0) will make the corresponding PORTE pin an output
(i.e., put the contents of the output latch on the selected
pin).
TRISE controls the direction of the RE pins, even when
they are being used as analog inputs. The user must
make sure to keep the pins configured as inputs when
using them as analog inputs.
The upper four bits of the TRISE register also control
the operation of the Parallel Slave Port. Their operation
is explained in Register 10-1.
The Data Latch register (LATE) is also memory
mapped. Read-modify-write operations on the LATE
register, read and write the latched output value for
PORTE.
The fourth pin of PORTE (MCLR/VPP/RE3) is an input
only pin. Its operation is controlled by the MCLRE Configuration
bit. When selected as a port pin (MCLRE = 0),
it functions as a digital input only pin; as such, it does not
have TRIS or LAT bits associated with its operation.
Otherwise, it functions as the device’s Master Clear
input. In either configuration, RE3 also functions as the
programming voltage input during programming.
EXAMPLE 10-5: INITIALIZING PORTE
10.5.1 PORTE IN 28-PIN DEVICES
For 28-pin devices, PORTE is only available when
Master Clear functionality is disabled (MCLRE = 0). In
these cases, PORTE is a single bit, input only port comprised
of RE3 only. The pin operates as previously
described.
Note: On a Power-on Reset, RE<2:0> are
configured as analog inputs.
Note: On a Power-on Reset, RE3 is enabled as
a digital input only if Master Clear
functionality is disabled.
CLRF PORTE ; Initialize PORTE by
; clearing output
; data latches
CLRF LATE ; Alternate method
; to clear output
; data latches
MOVLW 0Ah ; Configure A/D
MOVWF ADCON1 ; for digital inputs
MOVLW 03h ; Value used to
; initialize data
; direction
MOVWF TRISE ; Set RE<0> as inputs
; RE<1> as outputs
; RE<2> as inputsPIC18F2420/2520/4420/4520
DS39631E-page 118 © 2008 Microchip Technology Inc.
REGISTER 10-1: TRISE REGISTER (40/44-PIN DEVICES ONLY)
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 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 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© 2008 Microchip Technology Inc. DS39631E-page 119
PIC18F2420/2520/4420/4520
TABLE 10-9: PORTE I/O SUMMARY
TABLE 10-10: SUMMARY OF REGISTERS ASSOCIATED WITH PORTE
Pin Function TRIS
Setting I/O I/O
Type Description
RE0/RD/AN5 RE0 0 O DIG LATE<0> data output; not affected by analog input.
1 I ST PORTE<0> data input; disabled when analog input enabled.
RD 1 I TTL PSP read enable input (PSP enabled).
AN5 1 I ANA A/D input channel 5; default input configuration on POR.
RE1/WR/AN6 RE1 0 O DIG LATE<1> data output; not affected by analog input.
1 I ST PORTE<1> data input; disabled when analog input enabled.
WR 1 I TTL PSP write enable input (PSP enabled).
AN6 1 I ANA A/D input channel 6; default input configuration on POR.
RE2/CS/AN7 RE2 0 O DIG LATE<2> data output; not affected by analog input.
1 I ST PORTE<2> data input; disabled when analog input enabled.
CS 1 I TTL PSP write enable input (PSP enabled).
AN7 1 I ANA A/D input channel 7; default input configuration on POR.
MCLR/VPP/RE3(1) MCLR — I ST External Master Clear input; enabled when MCLRE Configuration bit is
set.
VPP — I ANA High-voltage detection; used for ICSP™ mode entry detection. Always
available regardless of pin mode.
RE3 —(2) I ST PORTE<3> data input; enabled when MCLRE Configuration bit is
clear.
Legend: DIG = Digital level output; TTL = TTL input buffer; ST = Schmitt Trigger input buffer; ANA = Analog level input/output;
x = Don’t care (TRIS bit does not affect port direction or is overridden for this option).
Note 1: RE3 is available on both 28-pin and 40/44-pin devices. All other PORTE pins are only implemented on 40/44-pin
devices.
2: RE3 does not have a corresponding TRIS bit to control data direction.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTE — — — — RE3(1,2) RE2 RE1 RE0 52
LATE(2) — — — — — LATE Data Latch Register 52
TRISE IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0 52
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by PORTE.
Note 1: Implemented only when Master Clear functionality is disabled (MCLRE Configuration bit = 0).
2: RE3 is the only PORTE bit implemented on both 28-pin and 40/44-pin devices. All other bits are
implemented only when PORTE is implemented (i.e., 40/44-pin devices).PIC18F2420/2520/4420/4520
DS39631E-page 120 © 2008 Microchip Technology Inc.
10.6 Parallel Slave Port
In addition to its function as a general I/O port, PORTD
can also operate as an 8-bit wide Parallel Slave Port
(PSP) or microprocessor port. PSP operation is controlled
by the 4 upper bits of the TRISE register
(Register 10-1). Setting control bit, PSPMODE
(TRISE<4>), enables PSP operation as long as the
Enhanced CCP module is not operating in dual output
or quad output PWM mode. In Slave mode, the port is
asynchronously readable and writable by the external
world.
The PSP can directly interface to an 8-bit microprocessor
data bus. The external microprocessor can
read or write the PORTD latch as an 8-bit latch. Setting
the control bit, PSPMODE, enables the PORTE I/O
pins to become control inputs for the microprocessor
port. When set, port pin RE0 is the RD input, RE1 is the
WR input and RE2 is the CS (Chip Select) input. For
this functionality, the corresponding data direction bits
of the TRISE register (TRISE<2:0>) must be configured
as inputs (set). The A/D port configuration bits,
PFCG<3:0> (ADCON1<3:0>), must also be set to a
value in the range of ‘1010’ through ‘1111’.
A write to the PSP occurs when both the CS and WR
lines are first detected low and ends when either are
detected high. The PSPIF and IBF flag bits are both set
when the write ends.
A read from the PSP occurs when both the CS and RD
lines are first detected low. The data in PORTD is read
out and the OBF bit is clear. If the user writes new data
to PORTD to set OBF, the data is immediately read out;
however, the OBF bit is not set.
When either the CS or RD lines are detected high, the
PORTD pins return to the input state and the PSPIF bit
is set. User applications should wait for PSPIF to be set
before servicing the PSP; when this happens, the IBF
and OBF bits can be polled and the appropriate action
taken.
The timing for the control signals in Write and Read
modes is shown in Figure 10-3 and Figure 10-4,
respectively.
FIGURE 10-2: PORTD AND PORTE
BLOCK DIAGRAM
(PARALLEL SLAVE PORT)
Note: The Parallel Slave Port is only available on
40/44-pin devices.
Data Bus
WR LATD RDx pin
D Q
CK
EN
Q D
RD PORTD EN
One bit of PORTD
Set Interrupt Flag
PSPIF (PIR1<7>)
Read
Chip Select
Write
RD
CS
WR
TTL
TTL
TTL
TTL
or
WR PORTD
RD LATD
Data Latch
Note: I/O pins have diode protection to VDD and VSS.
PORTE Pins© 2008 Microchip Technology Inc. DS39631E-page 121
PIC18F2420/2520/4420/4520
FIGURE 10-3: PARALLEL SLAVE PORT WRITE WAVEFORMS
FIGURE 10-4: PARALLEL SLAVE PORT READ WAVEFORMS
TABLE 10-11: REGISTERS ASSOCIATED WITH PARALLEL SLAVE PORT
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
PORTD RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 52
LATD PORTD Data Latch Register (Read and Write to Data Latch) 52
TRISD PORTD Data Direction Register 52
PORTE — — — — RE3 RE2 RE1 RE0 52
LATE — — — — — LATE Data Latch Register 52
TRISE IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0 52
INTCON GIE/GIEH PEIE/GIEL TMR0IF INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by the Parallel Slave Port.
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
RD
IBF
OBF
PSPIF
PORTD<7:0>
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
IBF
PSPIF
RD
OBF
PORTD<7:0>PIC18F2420/2520/4420/4520
DS39631E-page 122 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 123
PIC18F2420/2520/4420/4520
11.0 TIMER0 MODULE
The Timer0 module incorporates the following features:
• Software selectable operation as a timer or
counter in both 8-bit or 16-bit modes
• Readable and writable registers
• Dedicated 8-bit, software programmable
prescaler
• Selectable clock source (internal or external)
• Edge select for external clock
• Interrupt-on-overflow
The T0CON register (Register 11-1) controls all
aspects of the module’s operation, including the
prescale selection. It is both readable and writable.
A simplified block diagram of the Timer0 module in 8-bit
mode is shown in Figure 11-1. Figure 11-2 shows a
simplified block diagram of the Timer0 module in 16-bit
mode.
REGISTER 11-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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 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
0 = Internal instruction cycle clock (CLKO)
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 T0PS<2:0>: Timer0 Prescaler Select bits
111 = 1:256 Prescale value
110 = 1:128 Prescale value
101 = 1:64 Prescale value
100 = 1:32 Prescale value
011 = 1:16 Prescale value
010 = 1:8 Prescale value
001 = 1:4 Prescale value
000 = 1:2 Prescale valuePIC18F2420/2520/4420/4520
DS39631E-page 124 © 2008 Microchip Technology Inc.
11.1 Timer0 Operation
Timer0 can operate as either a timer or a counter; the
mode is selected with the T0CS bit (T0CON<5>). In
Timer mode (T0CS = 0), the module increments on
every clock by default unless a different prescaler value
is selected (see Section 11.3 “Prescaler”). If the
TMR0 register is written to, 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.
The Counter mode is selected by setting the T0CS bit
(= 1). In this mode, Timer0 increments either on every
rising or falling edge of pin RA4/T0CKI. The incrementing
edge is determined by the Timer0 Source Edge
Select bit, T0SE (T0CON<4>); clearing this bit selects
the rising edge. Restrictions on the external clock input
are discussed below.
An external clock source can be used to drive Timer0;
however, it must meet certain requirements to ensure
that the external clock can be synchronized with the
internal phase clock (TOSC). There is a delay between
synchronization and the onset of incrementing the
timer/counter.
11.2 Timer0 Reads and Writes in
16-Bit Mode
TMR0H is not the actual high byte of Timer0 in 16-bit
mode; it is actually a buffered version of the real high
byte of Timer0 which is not directly readable nor writable
(refer to Figure 11-2). TMR0H is updated with the
contents of the high byte of Timer0 during a read of
TMR0L. This provides 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.
Similarly, a write to the high byte of Timer0 must also
take place through the TMR0H Buffer register. The high
byte is updated with the contents of TMR0H when a
write occurs to TMR0L. This allows all 16 bits of Timer0
to be updated at once.
FIGURE 11-1: TIMER0 BLOCK DIAGRAM (8-BIT MODE)
FIGURE 11-2: TIMER0 BLOCK DIAGRAM (16-BIT MODE)
Note: Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI max. prescale.
T0CKI pin
T0SE
0
1
0
1
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
Clocks
TMR0L
(2 TCY Delay)
PSA Internal Data Bus
T0PS<2:0>
Set
TMR0IF
on Overflow
3 8
8
Note: Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI max. prescale.
T0CKI pin
T0SE
0
1
0
1
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
Clocks
TMR0L
(2 TCY Delay)
Internal Data Bus
8
PSA
T0PS<2:0>
Set
TMR0IF
on Overflow
3
TMR0
TMR0H
High Byte
8
8
8
Read TMR0L
Write TMR0L
8© 2008 Microchip Technology Inc. DS39631E-page 125
PIC18F2420/2520/4420/4520
11.3 Prescaler
An 8-bit counter is available as a prescaler for the Timer0
module. The prescaler is not directly readable or writable;
its value is set by the PSA and T0PS<2:0> bits
(T0CON<3:0>) which determine the prescaler
assignment and prescale ratio.
Clearing the PSA bit assigns the prescaler to the
Timer0 module. When it is assigned, prescale values
from 1:2 through 1:256 in power-of-2 increments are
selectable.
When assigned to the Timer0 module, all instructions
writing to the TMR0 register (e.g., CLRF TMR0, MOVWF
TMR0, BSF TMR0, etc.) clear the prescaler count.
11.3.1 SWITCHING PRESCALER
ASSIGNMENT
The prescaler assignment is fully under software
control and can be changed “on-the-fly” during program
execution.
11.4 Timer0 Interrupt
The TMR0 interrupt is generated when the TMR0
register overflows from FFh to 00h in 8-bit mode, or
from FFFFh to 0000h in 16-bit mode. This overflow sets
the TMR0IF flag bit. The interrupt can be masked by
clearing the TMR0IE bit (INTCON<5>). Before reenabling
the interrupt, the TMR0IF bit must be cleared
in software by the Interrupt Service Routine.
Since Timer0 is shut down in Sleep mode, the TMR0
interrupt cannot awaken the processor from Sleep.
TABLE 11-1: REGISTERS ASSOCIATED WITH TIMER0
Note: Writing to TMR0 when the prescaler is
assigned to Timer0 will clear the prescaler
count but will not change the prescaler
assignment.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
TMR0L Timer0 Register Low Byte 50
TMR0H Timer0 Register High Byte 50
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 50
TRISA RA7(1) RA6(1) RA5 RA4 RA3 RA2 RA1 RA0 52
Legend: Shaded cells are not used by Timer0.
Note 1: PORTA<7:6> and their direction bits are individually configured as port pins based on various primary
oscillator modes. When disabled, these bits read as ‘0’.PIC18F2420/2520/4420/4520
DS39631E-page 126 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 127
PIC18F2420/2520/4420/4520
12.0 TIMER1 MODULE
The Timer1 timer/counter module incorporates these
features:
• Software selectable operation as a 16-bit timer or
counter
• Readable and writable 8-bit registers (TMR1H
and TMR1L)
• Selectable clock source (internal or external) with
device clock or Timer1 oscillator internal options
• Interrupt-on-overflow
• Reset on CCP Special Event Trigger
• Device clock status flag (T1RUN)
A simplified block diagram of the Timer1 module is
shown in Figure 12-1. A block diagram of the module’s
operation in Read/Write mode is shown in Figure 12-2.
The module incorporates its own low-power oscillator
to provide an additional clocking option. The Timer1
oscillator can also be used as a low-power clock source
for the microcontroller in power-managed operation.
Timer1 can also be used to provide Real-Time Clock
(RTC) functionality to applications with only a minimal
addition of external components and code overhead.
Timer1 is controlled through the T1CON Control
register (Register 12-1). It also contains the Timer1
Oscillator Enable bit (T1OSCEN). Timer1 can be
enabled or disabled by setting or clearing control bit,
TMR1ON (T1CON<0>).
REGISTER 12-1: T1CON: TIMER1 CONTROL REGISTER
R/W-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 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 T1RUN: Timer1 System Clock Status bit
1 = Device clock is derived from Timer1 oscillator
0 = Device clock is derived from another source
bit 5-4 T1CKPS<1:0>: Timer1 Input Clock Prescale Select bits
11 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 3 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 RC0/T1OSO/T13CKI (on the rising edge)
0 = Internal clock (FOSC/4)
bit 0 TMR1ON: Timer1 On bit
1 = Enables Timer1
0 = Stops Timer1PIC18F2420/2520/4420/4520
DS39631E-page 128 © 2008 Microchip Technology Inc.
12.1 Timer1 Operation
Timer1 can operate in one of these modes:
• Timer
• Synchronous Counter
• Asynchronous Counter
The operating mode is determined by the clock select
bit, TMR1CS (T1CON<1>). When TMR1CS is cleared
(= 0), Timer1 increments on every internal instruction
cycle (FOSC/4). When the bit is set, Timer1 increments
on every rising edge of the Timer1 external clock input
or the Timer1 oscillator, if enabled.
When Timer1 is enabled, the RC1/T1OSI and RC0/
T1OSO/T13CKI pins become inputs. This means the
values of TRISC<1:0> are ignored and the pins are
read as ‘0’.
FIGURE 12-1: TIMER1 BLOCK DIAGRAM
FIGURE 12-2: TIMER1 BLOCK DIAGRAM (16-BIT READ/WRITE MODE)
T1SYNC
TMR1CS
T1CKPS<1:0>
Sleep Input
T1OSCEN(1)
FOSC/4
Internal
Clock
On/Off
Prescaler
1, 2, 4, 8
Synchronize
Detect
1
0
2
T1OSO/T13CKI
T1OSI
1
0
TMR1ON
TMR1L
Set
TMR1IF
on Overflow
TMR1
High Byte Clear TMR1
(CCP Special Event Trigger)
Timer1 Oscillator
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
On/Off
Timer1
Timer1 Clock Input
T1SYNC
TMR1CS
T1CKPS<1:0>
Sleep Input
T1OSCEN(1)
FOSC/4
Internal
Clock
Prescaler
1, 2, 4, 8
Synchronize
Detect
1
0
2
T1OSO/T13CKI
T1OSI
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
1
0
TMR1L
Internal Data Bus
8
Set
TMR1IF
on Overflow
TMR1
TMR1H
High Byte
8
8
8
Read TMR1L
Write TMR1L
8
TMR1ON
Clear TMR1
(CCP Special Event Trigger)
Timer1 Oscillator
On/Off
Timer1
Timer1 Clock Input© 2008 Microchip Technology Inc. DS39631E-page 129
PIC18F2420/2520/4420/4520
12.2 Timer1 16-Bit Read/Write Mode
Timer1 can be configured for 16-bit reads and writes
(see Figure 12-2). When the RD16 control bit
(T1CON<7>) 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, has
become invalid due to a rollover between reads.
A write to the high byte of Timer1 must also take place
through the TMR1H Buffer register. The 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.
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.
12.3 Timer1 Oscillator
An on-chip crystal oscillator circuit is incorporated
between pins T1OSI (input) and T1OSO (amplifier output).
It is enabled by setting the Timer1 Oscillator Enable
bit, T1OSCEN (T1CON<3>). The oscillator is a lowpower
circuit rated for 32 kHz crystals. It will continue to
run during all power-managed modes. The circuit for a
typical LP oscillator is shown in Figure 12-3. Table 12-1
shows the capacitor selection for the Timer1 oscillator.
The user must provide a software time delay to ensure
proper start-up of the Timer1 oscillator.
FIGURE 12-3: EXTERNAL COMPONENTS
FOR THE TIMER1 LP
OSCILLATOR
TABLE 12-1: CAPACITOR SELECTION FOR
THE TIMER OSCILLATOR
12.3.1 USING TIMER1 AS A
CLOCK SOURCE
The Timer1 oscillator is also available as a clock source
in power-managed modes. By setting the clock select
bits, SCS<1:0> (OSCCON<1:0>), to ‘01’, the device
switches to SEC_RUN mode; both the CPU and
peripherals are clocked from the Timer1 oscillator. If the
IDLEN bit (OSCCON<7>) is cleared and a SLEEP
instruction is executed, the device enters SEC_IDLE
mode. Additional details are available in Section 3.0
“Power-Managed Modes”.
Whenever the Timer1 oscillator is providing the clock
source, the Timer1 system clock status flag, T1RUN
(T1CON<6>), is set. This can be used to determine the
controller’s current clocking mode. It can also indicate
the clock source being currently used by the Fail-Safe
Clock Monitor. If the Clock Monitor is enabled and the
Timer1 oscillator fails while providing the clock, polling
the T1RUN bit will indicate whether the clock is being
provided by the Timer1 oscillator or another source.
12.3.2 LOW-POWER TIMER1 OPTION
The Timer1 oscillator can operate at two distinct levels
of power consumption based on device configuration.
When the LPT1OSC Configuration bit is set, the Timer1
oscillator operates in a low-power mode. When
LPT1OSC is not set, Timer1 operates at a higher power
level. Power consumption for a particular mode is
relatively constant, regardless of the device’s operating
mode. The default Timer1 configuration is the higher
power mode.
As the low-power Timer1 mode tends to be more
sensitive to interference, high noise environments may
cause some oscillator instability. The low-power option
is, therefore, best suited for low noise applications
where power conservation is an important design
consideration.
Note: See the Notes with Table 12-1 for additional
information about capacitor selection.
C1
C2
XTAL
PIC18FXXXX
T1OSI
T1OSO
32.768 kHz
27 pF
27 pF
Osc Type Freq C1 C2
LP 32 kHz 27 pF(1) 27 pF(1)
Note 1: Microchip suggests these values as a
starting point in validating the oscillator
circuit.
2: Higher capacitance increases the stability
of the oscillator but also increases the
start-up time.
3: Since each resonator/crystal has its own
characteristics, the user should consult
the resonator/crystal manufacturer for
appropriate values of external
components.
4: Capacitor values are for design guidance
only.PIC18F2420/2520/4420/4520
DS39631E-page 130 © 2008 Microchip Technology Inc.
12.3.3 TIMER1 OSCILLATOR LAYOUT
CONSIDERATIONS
The Timer1 oscillator circuit draws very little power
during operation. Due to the low-power nature of the
oscillator, it may also be sensitive to rapidly changing
signals in close proximity.
The oscillator circuit, shown in Figure 12-3, should be
located as close as possible to the microcontroller.
There should be no circuits passing within the oscillator
circuit boundaries other than VSS or VDD.
If a high-speed circuit must be located near the oscillator
(such as the CCP1 pin in Output Compare or PWM
mode, or the primary oscillator using the OSC2 pin), a
grounded guard ring around the oscillator circuit, as
shown in Figure 12-4, may be helpful when used on a
single-sided PCB or in addition to a ground plane.
FIGURE 12-4: OSCILLATOR CIRCUIT
WITH GROUNDED
GUARD RING
12.4 Timer1 Interrupt
The TMR1 register pair (TMR1H:TMR1L) increments
from 0000h to FFFFh and rolls over to 0000h. The
Timer1 interrupt, if enabled, is generated on overflow,
which is latched in interrupt flag bit, TMR1IF
(PIR1<0>). This interrupt can be enabled or disabled
by setting or clearing the Timer1 Interrupt Enable bit,
TMR1IE (PIE1<0>).
12.5 Resetting Timer1 Using the CCP
Special Event Trigger
If either of the CCP modules is configured to use
Timer1 and generate a Special Event Trigger in Compare
mode (CCP1M<3:0> or CCP2M<3:0> = 1011),
this signal will reset Timer1. The trigger from CCP2 will
also start an A/D conversion if the A/D module is
enabled (see Section 15.3.4 “Special Event Trigger”
for more information).
The module must be configured as either a timer or a
synchronous counter to take advantage of this feature.
When used this way, the CCPRxH:CCPRxL register
pair effectively becomes a Period register for Timer1.
If Timer1 is running in Asynchronous Counter mode,
this Reset operation may not work.
In the event that a write to Timer1 coincides with a
Special Event Trigger, the write operation will take
precedence.
12.6 Using Timer1 as a Real-Time Clock
Adding an external LP oscillator to Timer1 (such as the
one described in Section 12.3 “Timer1 Oscillator”)
gives users the option to include RTC functionality to
their applications. This is accomplished with an
inexpensive watch crystal to provide an accurate time
base and several lines of application code to calculate
the time. When operating in Sleep mode and using a
battery or supercapacitor as a power source, it can
completely eliminate the need for a separate RTC
device and battery backup.
The application code routine, RTCisr, shown in
Example 12-1, demonstrates a simple method to
increment a counter at one-second intervals using an
Interrupt Service Routine. Incrementing the TMR1
register pair to overflow triggers the interrupt and calls
the routine, which increments the seconds counter by
one; additional counters for minutes and hours are
incremented as the previous counter overflow.
Since the register pair is 16 bits wide, counting up to
overflow the register directly from a 32.768 kHz clock
would take 2 seconds. To force the overflow at the
required one-second intervals, it is necessary to preload
it. The simplest method is to set the MSb of
TMR1H with a BSF instruction. Note that the TMR1L
register is never preloaded or altered; doing so may
introduce cumulative error over many cycles.
For this method to be accurate, Timer1 must operate in
Asynchronous mode and the Timer1 overflow interrupt
must be enabled (PIE1<0> = 1), as shown in the
routine, RTCinit. The Timer1 oscillator must also be
enabled and running at all times.
VDD
OSC1
VSS
OSC2
RC0
RC1
RC2
Note: Not drawn to scale.
Note: The Special Event Triggers from the CCP2
module will not set the TMR1IF interrupt
flag bit (PIR1<0>). © 2008 Microchip Technology Inc. DS39631E-page 131
PIC18F2420/2520/4420/4520
12.7 Considerations in Asynchronous
Counter Mode
Following a Timer1 interrupt and an update to the
TMR1 registers, the Timer1 module uses a falling edge
on its clock source to trigger the next register update on
the rising edge. If the update is completed after the
clock input has fallen, the next rising edge will not be
counted.
If the application can reliably update TMR1 before the
timer input goes low, no additional action is needed.
Otherwise, an adjusted update can be performed
following a later Timer1 increment. This can be done by
monitoring TMR1L within the interrupt routine until it
increments, and then updating the TMR1H:TMR1L
register pair while the clock is low, or one-half of the
period of the clock source. Assuming that Timer1 is
being used as a Real-Time Clock, the clock source is a
32.768 kHz crystal oscillator; in this case, one half
period of the clock is 15.25 μs.
The Real-Time Clock application code in Example 12-1
shows a typical ISR for Timer1, as well as the optional
code required if the update cannot be done reliably
within the required interval.
EXAMPLE 12-1: IMPLEMENTING A REAL-TIME CLOCK USING A TIMER1 INTERRUPT SERVICE
RTCinit
MOVLW 80h ; Preload TMR1 register pair
MOVWF TMR1H ; for 1 second overflow
CLRF TMR1L
MOVLW b’00001111’ ; Configure for external clock,
MOVWF T1CON ; Asynchronous operation, external oscillator
CLRF secs ; Initialize timekeeping registers
CLRF mins ;
MOVLW .12
MOVWF hours
BSF PIE1, TMR1IE ; Enable Timer1 interrupt
RETURN
RTCisr ; Start ISR here
; Insert the next 4 lines of code when TMR1
; can not be reliably updated before clock pulse goes low
BTFSC TMR1L,0 ; wait for TMR1L<0> to become clear
BRA $-2 ; (may already be clear)
BTFSS TMR1L,0 ; wait for TMR1L<0> to become set
BRA $-2 ; TMR1 has just incremented
; If TMR1 update can be completed before clock pulse goes low
BSF TMR1H, 7 ; Preload for 1 sec overflow
BCF PIR1, TMR1IF ; Clear interrupt flag
INCF secs, F ; Increment seconds
MOVLW .59 ; 60 seconds elapsed?
CPFSGT secs
RETURN ; No, done
CLRF secs ; Clear seconds
INCF mins, F ; Increment minutes
MOVLW .59 ; 60 minutes elapsed?
CPFSGT mins
RETURN ; No, done
CLRF mins ; clear minutes
INCF hours, F ; Increment hours
MOVLW .23 ; 24 hours elapsed?
CPFSGT hours
RETURN ; No, done
CLRF hours ; Reset hours
RETURN ; DonePIC18F2420/2520/4420/4520
DS39631E-page 132 © 2008 Microchip Technology Inc.
TABLE 12-2: REGISTERS ASSOCIATED WITH TIMER1 AS A TIMER/COUNTER
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
TMR1L Timer1 Register Low Byte 50
TMR1H Timer1 Register High Byte 50
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 50
Legend: Shaded cells are not used by the Timer1 module.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.© 2008 Microchip Technology Inc. DS39631E-page 133
PIC18F2420/2520/4420/4520
13.0 TIMER2 MODULE
The Timer2 module timer incorporates the following
features:
• 8-Bit Timer and Period registers (TMR2 and PR2,
respectively)
• Readable and writable (both registers)
• Software programmable prescaler (1:1, 1:4
and 1:16)
• Software programmable postscaler (1:1 through
1:16)
• Interrupt on TMR2 to PR2 match
• Optional use as the shift clock for the MSSP
module
The module is controlled through the T2CON register
(Register 13-1), which enables or disables the timer
and configures the prescaler and postscaler. Timer2
can be shut off by clearing control bit, TMR2ON
(T2CON<2>), to minimize power consumption.
A simplified block diagram of the module is shown in
Figure 13-1.
13.1 Timer2 Operation
In normal operation, TMR2 is incremented from 00h on
each clock (FOSC/4). A 4-bit counter/prescaler on the
clock input gives direct input, divide-by-4 and divide-by-
16 prescale options; these are selected by the prescaler
control bits, T2CKPS<1:0> (T2CON<1:0>). The value of
TMR2 is compared to that of the Period register, PR2, on
each clock cycle. When the two values match, the comparator
generates a match signal as the timer output.
This signal also resets the value of TMR2 to 00h on the
next cycle and drives the output counter/postscaler (see
Section 13.2 “Timer2 Interrupt”).
The TMR2 and PR2 registers are both directly readable
and writable. The TMR2 register is cleared on any
device Reset, while the PR2 register initializes at FFh.
Both the prescaler and postscaler counters are cleared
on the following events:
• a write to the TMR2 register
• a write to the T2CON register
• any device Reset (Power-on Reset, MCLR Reset,
Watchdog Timer Reset or Brown-out Reset)
TMR2 is not cleared when T2CON is written.
REGISTER 13-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
— T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 Unimplemented: Read as ‘0’
bit 6-3 T2OUTPS<3:0>: 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 T2CKPS<1:0>: Timer2 Clock Prescale Select bits
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16PIC18F2420/2520/4420/4520
DS39631E-page 134 © 2008 Microchip Technology Inc.
13.2 Timer2 Interrupt
Timer2 also can generate an optional device interrupt.
The Timer2 output signal (TMR2 to PR2 match) provides
the input for the 4-bit output counter/postscaler.
This counter generates the TMR2 match interrupt flag
which is latched in TMR2IF (PIR1<1>). The interrupt is
enabled by setting the TMR2 Match Interrupt Enable
bit, TMR2IE (PIE1<1>).
A range of 16 postscale options (from 1:1 through 1:16
inclusive) can be selected with the postscaler control
bits, T2OUTPS<3:0> (T2CON<6:3>).
13.3 Timer2 Output
The unscaled output of TMR2 is available primarily to
the CCP modules, where it is used as a time base for
operations in PWM mode.
Timer2 can optionally be used as the shift clock source
for the MSSP module operating in SPI mode. Additional
information is provided in Section 17.0 “Master
Synchronous Serial Port (MSSP) Module”.
FIGURE 13-1: TIMER2 BLOCK DIAGRAM
TABLE 13-1: REGISTERS ASSOCIATED WITH TIMER2 AS A TIMER/COUNTER
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
TMR2 Timer2 Register 50
T2CON — T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0 50
PR2 Timer2 Period Register 50
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by the Timer2 module.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.
Comparator
TMR2 Output
TMR2
Postscaler
Prescaler
PR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4
T2OUTPS<3:0>
T2CKPS<1:0>
Set TMR2IF
Internal Data Bus
8
Reset
TMR2/PR2
8 8
(to PWM or MSSP)
Match© 2008 Microchip Technology Inc. DS39631E-page 135
PIC18F2420/2520/4420/4520
14.0 TIMER3 MODULE
The Timer3 module timer/counter incorporates these
features:
• Software selectable operation as a 16-bit timer or
counter
• Readable and writable 8-bit registers (TMR3H
and TMR3L)
• Selectable clock source (internal or external) with
device clock or Timer1 oscillator internal options
• Interrupt-on-overflow
• Module Reset on CCP Special Event Trigger
A simplified block diagram of the Timer3 module is
shown in Figure 14-1. A block diagram of the module’s
operation in Read/Write mode is shown in Figure 14-2.
The Timer3 module is controlled through the T3CON
register (Register 14-1). It also selects the clock source
options for the CCP modules (see Section 15.1.1
“CCP Modules and Timer Resources” for more
information).
REGISTER 14-1: T3CON: TIMER3 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
RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 RD16: 16-Bit Read/Write Mode Enable bit
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 T3CCP<2:1>: Timer3 and Timer1 to CCPx Enable bits
1x = Timer3 is the capture/compare clock source for the CCP modules
01 = Timer3 is the capture/compare clock source for CCP2;
Timer1 is the capture/compare clock source for CCP1
00 = Timer1 is the capture/compare clock source for the CCP modules
bit 5-4 T3CKPS<1:0>: 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 device 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 Timer1 oscillator or T13CKI (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 Timer3PIC18F2420/2520/4420/4520
DS39631E-page 136 © 2008 Microchip Technology Inc.
14.1 Timer3 Operation
Timer3 can operate in one of three modes:
• Timer
• Synchronous Counter
• Asynchronous Counter
The operating mode is determined by the clock select
bit, TMR3CS (T3CON<1>). When TMR3CS is cleared
(= 0), Timer3 increments on every internal instruction
cycle (FOSC/4). When the bit is set, Timer3 increments
on every rising edge of the Timer1 external clock input
or the Timer1 oscillator, if enabled.
As with Timer1, the RC1/T1OSI and RC0/T1OSO/
T13CKI pins become inputs when the Timer1 oscillator
is enabled. This means the values of TRISC<1:0> are
ignored and the pins are read as ‘0’.
FIGURE 14-1: TIMER3 BLOCK DIAGRAM
FIGURE 14-2: TIMER3 BLOCK DIAGRAM (16-BIT READ/WRITE MODE)
T3SYNC
TMR3CS
T3CKPS<1:0>
Sleep Input
T1OSCEN(1)
FOSC/4
Internal
Clock
Prescaler
1, 2, 4, 8
Synchronize
Detect
1
0
2
T1OSO/T13CKI
T1OSI
1
0
TMR3ON
TMR3L
Set
TMR3IF
on Overflow
TMR3
High Byte
Timer1 Oscillator
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
On/Off
Timer3
CCP1/CCP2 Special Event Trigger
CCP1/CCP2 Select from T3CON<6,3>
Clear TMR3
Timer1 Clock Input
T3SYNC
TMR3CS
T3CKPS<1:0>
Sleep Input
T1OSCEN(1)
FOSC/4
Internal
Clock
Prescaler
1, 2, 4, 8
Synchronize
Detect
1
0
2
T13CKI/T1OSO
T1OSI
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
1
0
TMR3L
Internal Data Bus
8
Set
TMR3IF
on Overflow
TMR3
TMR3H
High Byte
8
8
8
Read TMR1L
Write TMR1L
8
TMR3ON
CCP1/CCP2 Special Event Trigger
Timer1 Oscillator
On/Off
Timer3
Timer1 Clock Input
CCP1/CCP2 Select from T3CON<6,3>
Clear TMR3© 2008 Microchip Technology Inc. DS39631E-page 137
PIC18F2420/2520/4420/4520
14.2 Timer3 16-Bit Read/Write Mode
Timer3 can be configured for 16-bit reads and writes
(see Figure 14-2). When the RD16 control bit
(T3CON<7>) 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 register. 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, has become invalid due to a rollover between
reads.
A write to the high byte of Timer3 must also take place
through the TMR3H Buffer register. The 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.
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.
14.3 Using the Timer1 Oscillator as the
Timer3 Clock Source
The Timer1 internal oscillator may be used as the clock
source for Timer3. The Timer1 oscillator is enabled by
setting the T1OSCEN (T1CON<3>) bit. To use it as the
Timer3 clock source, the TMR3CS bit must also be set.
As previously noted, this also configures Timer3 to
increment on every rising edge of the oscillator source.
The Timer1 oscillator is described in Section 12.0
“Timer1 Module”.
14.4 Timer3 Interrupt
The TMR3 register pair (TMR3H:TMR3L) increments
from 0000h to FFFFh and overflows to 0000h. The
Timer3 interrupt, if enabled, is generated on overflow
and is latched in interrupt flag bit, TMR3IF (PIR2<1>).
This interrupt can be enabled or disabled by setting or
clearing the Timer3 Interrupt Enable bit, TMR3IE
(PIE2<1>).
14.5 Resetting Timer3 Using the CCP
Special Event Trigger
If either of the CCP modules is configured to use Timer3
and to generate a Special Event Trigger in Compare
mode (CCP1M<3:0> or CCP2M<3:0> = 1011), this
signal will reset Timer3. It will also start an A/D conversion
if the A/D module is enabled (see Section 15.3.4
“Special Event Trigger” for more information).
The module must be configured as either a timer or
synchronous counter to take advantage of this feature.
When used this way, the CCPRxH:CCPRxL register
pair effectively becomes a Period register for Timer3.
If Timer3 is running in Asynchronous Counter mode,
the 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.
TABLE 14-1: REGISTERS ASSOCIATED WITH TIMER3 AS A TIMER/COUNTER
Note: The Special Event Triggers from the CCP2
module will not set the TMR3IF interrupt
flag bit (PIR1<0>).
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
TMR3L Timer3 Register Low Byte 51
TMR3H Timer3 Register High Byte 51
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 50
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by the Timer3 module.PIC18F2420/2520/4420/4520
DS39631E-page 138 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 139
PIC18F2420/2520/4420/4520
15.0 CAPTURE/COMPARE/PWM
(CCP) MODULES
PIC18F2420/2520/4420/4520 devices all have two
CCP (Capture/Compare/PWM) modules. Each module
contains a 16-bit register which can operate as a 16-bit
Capture register, a 16-bit Compare register or a PWM
Master/Slave Duty Cycle register.
In 28-pin devices, the two standard CCP modules (CCP1
and CCP2) operate as described in this chapter. In 40/
44-pin devices, CCP1 is implemented as an Enhanced
CCP module with standard Capture and Compare
modes and Enhanced PWM modes. The ECCP implementation
is discussed in Section 16.0 “Enhanced
Capture/Compare/PWM (ECCP) Module”.
The capture and compare operations described in this
chapter apply to all standard and Enhanced CCP
modules.
Note: Throughout this section and Section 16.0
“Enhanced Capture/Compare/PWM (ECCP)
Module”, references to the register and bit
names for CCP modules are referred to generically
by the use of ‘x’ or ‘y’ in place of the
specific module number. Thus, “CCPxCON”
might refer to the control register for CCP1,
CCP2 or ECCP1. “CCPxCON” is used
throughout these sections to refer to the module
control register, regardless of whether the
CCP module is a standard or enhanced
implementation.
REGISTER 15-1: CCPxCON: CCPx CONTROL REGISTER (28-PIN DEVICES)
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — DCxB1 DCxB0 CCPxM3 CCPxM2 CCPxM1 CCPxM0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-6 Unimplemented: Read as ‘0’
bit 5-4 DCxB<1:0>: PWM Duty Cycle bit 1 and bit 0 for CCPx Module
Capture mode:
Unused.
Compare mode:
Unused.
PWM mode:
These bits are the two LSbs (bit 1 and bit 0) of the 10-bit PWM duty cycle. The eight MSbs (DCxB<9:2>)
of the duty cycle are found in CCPRxL.
bit 3-0 CCPxM<3:0>: CCPx Module Mode Select bits
0000 = Capture/Compare/PWM disabled (resets CCPx module)
0001 = Reserved
0010 = Compare mode, toggle output on match (CCPxIF bit is set)
0011 = Reserved
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode, initialize CCPx pin low; on compare match, force CCPx pin high (CCPxIF bit is set)
1001 = Compare mode, initialize CCPx pin high; on compare match, force CCPx pin low (CCPxIF bit is set)
1010 = Compare mode, generate software interrupt on compare match (CCPxIF bit is set, CCPx pin
reflects I/O state)
1011 = Compare mode, trigger special event; reset timer; CCP2 match starts A/D conversion (CCPxIF
bit is set)
11xx = PWM modePIC18F2420/2520/4420/4520
DS39631E-page 140 © 2008 Microchip Technology Inc.
15.1 CCP Module Configuration
Each Capture/Compare/PWM module is associated
with a control register (generically, CCPxCON) and a
data register (CCPRx). The data register, in turn, is
comprised of two 8-bit registers: CCPRxL (low byte)
and CCPRxH (high byte). All registers are both
readable and writable.
15.1.1 CCP MODULES AND TIMER
RESOURCES
The CCP modules utilize Timers 1, 2 or 3, depending
on the mode selected. Timer1 and Timer3 are available
to modules in Capture or Compare modes, while
Timer2 is available for modules in PWM mode.
TABLE 15-1: CCP MODE – TIMER
RESOURCE
The assignment of a particular timer to a module is
determined by the Timer to CCP enable bits in the
T3CON register (Register 14-1). Both modules may be
active at any given time and may share the same timer
resource if they are configured to operate in the same
mode (Capture/Compare or PWM) at the same time. The
interactions between the two modules are summarized in
Figure 15-1 and Figure 15-2. In Timer1 in Asynchronous
Counter mode, the capture operation will not work.
15.1.2 CCP2 PIN ASSIGNMENT
The pin assignment for CCP2 (Capture input, Compare
and PWM output) can change, based on device configuration.
The CCP2MX Configuration bit determines
which pin CCP2 is multiplexed to. By default, it is
assigned to RC1 (CCP2MX = 1). If the Configuration bit
is cleared, CCP2 is multiplexed with RB3.
Changing the pin assignment of CCP2 does not automatically
change any requirements for configuring the
port pin. Users must always verify that the appropriate
TRIS register is configured correctly for CCP2
operation, regardless of where it is located.
TABLE 15-2: INTERACTIONS BETWEEN CCP1 AND CCP2 FOR TIMER RESOURCES
CCP/ECCP Mode Timer Resource
Capture
Compare
PWM
Timer1 or Timer3
Timer1 or Timer3
Timer2
CCP1 Mode CCP2 Mode Interaction
Capture Capture Each module can use TMR1 or TMR3 as the time base. The time base can be different
for each CCP.
Capture Compare CCP2 can be configured for the Special Event Trigger to reset TMR1 or TMR3
(depending upon which time base is used). Automatic A/D conversions on trigger event
can also be done. Operation of CCP1 could be affected if it is using the same timer as a
time base.
Compare Capture CCP1 can be configured for the Special Event Trigger to reset TMR1 or TMR3
(depending upon which time base is used). Operation of CCP2 could be affected if it is
using the same timer as a time base.
Compare Compare Either module can be configured for the Special Event Trigger to reset the time base.
Automatic A/D conversions on CCP2 trigger event can be done. Conflicts may occur if
both modules are using the same time base.
Capture PWM(1) None
Compare PWM(1) None
PWM(1) Capture None
PWM(1) Compare None
PWM(1) PWM(1) Both PWMs will have the same frequency and update rate (TMR2 interrupt).
Note 1: Includes standard and Enhanced PWM operation.© 2008 Microchip Technology Inc. DS39631E-page 141
PIC18F2420/2520/4420/4520
15.2 Capture Mode
In Capture mode, the CCPRxH:CCPRxL register pair
captures the 16-bit value of the TMR1 or TMR3 register
when an event occurs on the corresponding CCPx pin.
An event is defined as one of the following:
• every falling edge
• every rising edge
• every 4th rising edge
• every 16th rising edge
The event is selected by the mode select bits,
CCPxM<3:0> (CCPxCON<3:0>). When a capture is
made, the interrupt request flag bit, CCPxIF, is set; it
must be cleared in software. If another capture occurs
before the value in register CCPRx is read, the old
captured value is overwritten by the new captured value.
15.2.1 CCP PIN CONFIGURATION
In Capture mode, the appropriate CCPx pin should be
configured as an input by setting the corresponding
TRIS direction bit.
15.2.2 TIMER1/TIMER3 MODE SELECTION
The timers that are to be used with the capture feature
(Timer1 and/or Timer3) must be running in Timer mode or
Synchronized Counter mode. In Asynchronous Counter
mode, the capture operation will not work. The timer to be
used with each CCP module is selected in the T3CON
register (see Section 15.1.1 “CCP Modules and Timer
Resources”).
15.2.3 SOFTWARE INTERRUPT
When the Capture mode is changed, a false capture
interrupt may be generated. The user should keep the
CCPxIE interrupt enable bit clear to avoid false interrupts.
The interrupt flag bit, CCPxIF, should also be
cleared following any such change in operating mode.
15.2.4 CCP PRESCALER
There are four prescaler settings in Capture mode; they
are specified as part of the operating mode selected by
the mode select bits (CCPxM<3:0>). Whenever the
CCP module is turned off, or Capture mode is disabled,
the prescaler counter is cleared. This means that any
Reset will clear the prescaler counter.
Switching from one capture prescaler to another may
generate an interrupt. Also, the prescaler counter will
not be cleared; therefore, the first capture may be from
a non-zero prescaler. Example 15-1 shows the
recommended method for switching between capture
prescalers. This example also clears the prescaler
counter and will not generate the “false” interrupt.
EXAMPLE 15-1: CHANGING BETWEEN
CAPTURE PRESCALERS
(CCP2 SHOWN)
FIGURE 15-1: CAPTURE MODE OPERATION BLOCK DIAGRAM
Note: If RB3/CCP2 or RC1/CCP2 is configured
as an output, a write to the port can cause
a capture condition.
CLRF CCP2CON ; Turn CCP module off
MOVLW NEW_CAPT_PS ; Load WREG with the
; new prescaler mode
; value and CCP ON
MOVWF CCP2CON ; Load CCP2CON with
; this value
CCPR1H CCPR1L
TMR1H TMR1L
Set CCP1IF
TMR3
Enable
Q1:Q4
CCP1CON<3:0>
CCP1 pin
Prescaler
÷ 1, 4, 16
and
Edge Detect
TMR1
Enable
T3CCP2
T3CCP2
CCPR2H CCPR2L
TMR1H TMR1L
Set CCP2IF
TMR3
Enable
CCP2CON<3:0>
CCP2 pin
Prescaler
÷ 1, 4, 16
TMR3H TMR3L
TMR1
Enable
T3CCP2
T3CCP1
T3CCP2
T3CCP1
TMR3H TMR3L
and
Edge Detect
4
4
4PIC18F2420/2520/4420/4520
DS39631E-page 142 © 2008 Microchip Technology Inc.
15.3 Compare Mode
In Compare mode, the 16-bit CCPRx register value is
constantly compared against either the TMR1 or TMR3
register pair value. When a match occurs, the CCPx pin
can be:
• driven high
• driven low
• toggled (high-to-low or low-to-high)
• remain unchanged (that is, reflects the state of the
I/O latch)
The action on the pin is based on the value of the mode
select bits (CCPxM<3:0>). At the same time, the
interrupt flag bit, CCPxIF, is set.
15.3.1 CCP PIN CONFIGURATION
The user must configure the CCPx pin as an output by
clearing the appropriate TRIS bit.
15.3.2 TIMER1/TIMER3 MODE SELECTION
Timer1 and/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.
15.3.3 SOFTWARE INTERRUPT MODE
When the Generate Software Interrupt mode is chosen
(CCPxM<3:0> = 1010), the corresponding CCPx pin is
not affected. A CCP interrupt is generated when the
CCPxIF interrupt flag is set while the CCPxIE bit is set.
15.3.4 SPECIAL EVENT TRIGGER
Both CCP modules are equipped with a Special Event
Trigger. This is an internal hardware signal generated
in Compare mode to trigger actions by other modules.
The Special Event Trigger is enabled by selecting
the Compare Special Event Trigger mode
(CCPxM<3:0> = 1011).
For either CCP module, the Special Event Trigger resets
the Timer register pair for whichever timer resource is
currently assigned as the module’s time base. This
allows the CCPRx registers to serve as a programmable
Period register for either timer.
The Special Event Trigger for CCP2 can also start an
A/D conversion. In order to do this, the A/D Converter
must already be enabled.
FIGURE 15-2: COMPARE MODE OPERATION BLOCK DIAGRAM
Note: Clearing the CCP2CON register will force
the RB3 or RC1 compare output latch
(depending on device configuration) to the
default low level. This is not the PORTB or
PORTC I/O data latch.
CCPR1H CCPR1L
TMR1H TMR1L
Comparator
S Q
R
Output
Logic
Special Event Trigger
Set CCP1IF
CCP1 pin
TRIS
CCP1CON<3:0>
Output Enable
TMR3H TMR3L
CCPR2H CCPR2L
Comparator
1
0
T3CCP2
T3CCP1
Set CCP2IF
1
0
Compare
4
(Timer1/Timer3 Reset)
S Q
R
Output
Logic
Special Event Trigger
CCP2 pin
TRIS
CCP2CON<3:0>
4 Output Enable
(Timer1/Timer3 Reset, A/D Trigger)
Match
Compare
Match© 2008 Microchip Technology Inc. DS39631E-page 143
PIC18F2420/2520/4420/4520
TABLE 15-3: REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, TIMER1 AND TIMER3
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
RCON IPEN SBOREN — RI TO PD POR BOR 48
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
TRISB PORTB Data Direction Register 52
TRISC PORTC Data Direction Register 52
TMR1L Timer1 Register Low Byte 50
TMR1H Timer1 Register High Byte 50
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 50
TMR3H Timer3 Register High Byte 51
TMR3L Timer3 Register Low Byte 51
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 51
CCPR1L Capture/Compare/PWM Register 1 Low Byte 51
CCPR1H Capture/Compare/PWM Register 1 High Byte 51
CCP1CON P1M1(1) P1M0(1) DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 51
CCPR2L Capture/Compare/PWM Register 2 Low Byte 51
CCPR2H Capture/Compare/PWM Register 2 High Byte 51
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by Capture/Compare, Timer1 or Timer3.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.PIC18F2420/2520/4420/4520
DS39631E-page 144 © 2008 Microchip Technology Inc.
15.4 PWM Mode
In Pulse-Width Modulation (PWM) mode, the CCPx pin
produces up to a 10-bit resolution PWM output. Since
the CCP2 pin is multiplexed with a PORTB or PORTC
data latch, the appropriate TRIS bit must be cleared to
make the CCP2 pin an output.
Figure 15-3 shows a simplified block diagram of the
CCP module in PWM mode.
For a step-by-step procedure on how to set up the CCP
module for PWM operation, see Section 15.4.4
“Setup for PWM Operation”.
FIGURE 15-3: SIMPLIFIED PWM BLOCK
DIAGRAM
A PWM output (Figure 15-4) has a time base (period)
and a time that the output stays high (duty cycle). The
frequency of the PWM is the inverse of the period
(1/period).
FIGURE 15-4: PWM OUTPUT
15.4.1 PWM PERIOD
The PWM period is specified by writing to the PR2
register. The PWM period can be calculated using the
following formula:
EQUATION 15-1:
PWM frequency is defined as 1/[PWM period].
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
15.4.2 PWM DUTY CYCLE
The PWM duty cycle is specified by writing to the
CCPRxL register and to the CCPxCON<5:4> bits. Up
to 10-bit resolution is available. The CCPRxL contains
the eight MSbs and the CCPxCON<5:4> bits contain
the two LSbs. This 10-bit value is represented by
CCPRxL:CCPxCON<5:4>. The following equation is
used to calculate the PWM duty cycle in time:
EQUATION 15-2:
CCPRxL and CCPxCON<5:4> 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 (i.e., the period is complete). In PWM mode,
CCPRxH is a read-only register.
Note: Clearing the CCP2CON register will force
the RB3 or RC1 output latch (depending on
device configuration) to the default low
level. This is not the PORTB or PORTC I/O
data latch.
CCPRxL
CCPRxH (Slave)
Comparator
TMR2
Comparator
PR2
(Note 1)
R Q
S
Duty Cycle Registers CCPxCON<5:4>
Clear Timer,
CCPx pin and
latch D.C.
Note 1: The 8-bit TMR2 value is concatenated with the 2-bit
internal Q clock, or 2 bits of the prescaler, to create the
10-bit time base.
CCPx Output
Corresponding
TRIS bit
Period
Duty Cycle
TMR2 = PR2
TMR2 = Duty Cycle
TMR2 = PR2
Note: The Timer2 postscalers (see Section 13.0
“Timer2 Module”) are not used in the
determination of the PWM frequency. The
postscaler could be used to have a servo
update rate at a different frequency than
the PWM output.
PWM Period = [(PR2) + 1] • 4 • TOSC •
(TMR2 Prescale Value)
PWM Duty Cycle = (CCPRXL:CCPXCON<5:4>) •
TOSC • (TMR2 Prescale Value)© 2008 Microchip Technology Inc. DS39631E-page 145
PIC18F2420/2520/4420/4520
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 the CCPRxH and 2-bit latch match TMR2,
concatenated with an internal 2-bit Q clock or 2 bits of
the TMR2 prescaler, the CCPx pin is cleared.
The maximum PWM resolution (bits) for a given PWM
frequency is given by the equation:
EQUATION 15-3:
TABLE 15-4: EXAMPLE PWM FREQUENCIES AND RESOLUTIONS AT 40 MHz
15.4.3 PWM AUTO-SHUTDOWN
(CCP1 ONLY)
The PWM auto-shutdown features of the Enhanced CCP
module are also available to CCP1 in 28-pin devices. The
operation of this feature is discussed in detail in
Section 16.4.7 “Enhanced PWM Auto-Shutdown”.
Auto-shutdown features are not available for CCP2.
15.4.4 SETUP FOR PWM OPERATION
The following steps should be taken when configuring
the CCP module for PWM operation:
1. Set the PWM period by writing to the PR2
register.
2. Set the PWM duty cycle by writing to the
CCPRxL register and CCPxCON<5:4> bits.
3. Make the CCPx pin an output by clearing the
appropriate TRIS bit.
4. Set the TMR2 prescale value, then enable
Timer2 by writing to T2CON.
5. Configure the CCPx module for PWM operation.
Note: If the PWM duty cycle value is longer than
the PWM period, the CCPx pin will not be
cleared.
FOSC
FPWM
--------------- ⎝ ⎠ ⎛ ⎞ log
log( ) 2 PWM Resolution (max) = -----------------------------bits
PWM Frequency 2.44 kHz 9.77 kHz 39.06 kHz 156.25 kHz 312.50 kHz 416.67 kHz
Timer Prescaler (1, 4, 16) 16 4 1 1 1 1
PR2 Value FFh FFh FFh 3Fh 1Fh 17h
Maximum Resolution (bits) 10 10 10 8 7 6.58PIC18F2420/2520/4420/4520
DS39631E-page 146 © 2008 Microchip Technology Inc.
TABLE 15-5: REGISTERS ASSOCIATED WITH PWM AND TIMER2
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
RCON IPEN SBOREN — RI TO PD POR BOR 48
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
TRISB PORTB Data Direction Register 52
TRISC PORTC Data Direction Register 52
TMR2 Timer2 Register 50
PR2 Timer2 Period Register 50
T2CON — T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0 50
CCPR1L Capture/Compare/PWM Register 1 Low Byte 51
CCPR1H Capture/Compare/PWM Register 1 High Byte 51
CCP1CON P1M1(1) P1M0(1) DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 51
CCPR2L Capture/Compare/PWM Register 2 Low Byte 51
CCPR2H Capture/Compare/PWM Register 2 High Byte 51
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 51
ECCP1AS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1(1) PSSBD0(1) 51
PWM1CON PRSEN PDC6(1) PDC5(1) PDC4(1) PDC3(1) PDC2(1) PDC1(1) PDC0(1) 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by PWM or Timer2.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.© 2008 Microchip Technology Inc. DS39631E-page 147
PIC18F2420/2520/4420/4520
16.0 ENHANCED CAPTURE/
COMPARE/PWM (ECCP)
MODULE
In PIC18F4420/4520 devices, CCP1 is implemented as
a standard CCP module with Enhanced PWM
capabilities. These include the provision for 2 or 4 output
channels, user-selectable polarity, dead-band control
and automatic shutdown and restart. The enhanced
features are discussed in detail in Section 16.4
“Enhanced PWM Mode”. Capture, Compare and
single output PWM functions of the ECCP module are
the same as described for the standard CCP module.
The control register for the Enhanced CCP module is
shown in Register 16-2. It differs from the CCPxCON
registers in PIC18F2420/2520 devices in that the two
Most Significant bits are implemented to control PWM
functionality.
Note: The ECCP module is implemented only in
40/44-pin devices.
REGISTER 16-1: CCP1CON: ECCP CONTROL REGISTER (40/44-PIN DEVICES)
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-6 P1M<1:0>: Enhanced PWM Output Configuration bits
If CCP1M3:CCP1M2 = 00, 01, 10:
xx = P1A assigned as capture/compare input/output; P1B, P1C, P1D assigned as port pins
If CCP1M3:CCP1M2 = 11:
00 = Single output, P1A modulated; P1B, P1C, P1D assigned as port pins
01 = Full-bridge output forward, P1D modulated; P1A active; P1B, P1C inactive
10 = Half-bridge output, P1A, P1B modulated with dead-band control; P1C, P1D assigned as port pins
11 = Full-bridge output reverse, P1B modulated; P1C active; P1A, P1D inactive
bit 5-4 DC1B<1:0>: PWM Duty Cycle bit 1 and bit 0
Capture mode:
Unused.
Compare mode:
Unused.
PWM mode:
These bits are the two LSbs of the 10-bit PWM duty cycle. The eight MSbs of the duty cycle are found in
CCPR1L.
bit 3-0 CCP1M<3:0>: Enhanced CCP Mode Select bits
0000 = Capture/Compare/PWM off (resets ECCP module)
0001 = Reserved
0010 = Compare mode, toggle output on match
0011 = Capture mode
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode, initialize CCP1 pin low; set output on compare match (set CCP1IF)
1001 = Compare mode, initialize CCP1 pin high; clear output on compare match (set CCP1IF)
1010 = Compare mode, generate software interrupt only; CCP1 pin reverts to I/O state
1011 = Compare mode, trigger special event (ECCP resets TMR1 or TMR3, sets CCP1IF bit)
1100 = PWM mode, P1A, P1C active-high; P1B, P1D active-high
1101 = PWM mode, P1A, P1C active-high; P1B, P1D active-low
1110 = PWM mode, P1A, P1C active-low; P1B, P1D active-high
1111 = PWM mode, P1A, P1C active-low; P1B, P1D active-lowPIC18F2420/2520/4420/4520
DS39631E-page 148 © 2008 Microchip Technology Inc.
In addition to the expanded range of modes available
through the CCP1CON register and ECCP1AS
register, the ECCP module has an additional register
associated with Enhanced PWM operation and
auto-shutdown features. It is:
• PWM1CON (PWM Dead-Band Delay)
16.1 ECCP Outputs and Configuration
The Enhanced CCP module may have up to four PWM
outputs, depending on the selected operating mode.
These outputs, designated P1A through P1D, are
multiplexed with I/O pins on PORTC and PORTD. The
outputs that are active depend on the CCP operating
mode selected. The pin assignments are summarized
in Table 16-1.
To configure the I/O pins as PWM outputs, the proper
PWM mode must be selected by setting the P1M<1:0>
and CCP1M<3:0> bits. The appropriate TRISC and
TRISD direction bits for the port pins must also be set
as outputs.
16.1.1 ECCP MODULES AND TIMER
RESOURCES
Like the standard CCP modules, the ECCP module can
utilize Timers 1, 2 or 3, depending on the mode
selected. Timer1 and Timer3 are available for modules
in Capture or Compare modes, while Timer2 is available
for modules in PWM mode. Interactions between
the standard and Enhanced CCP modules are identical
to those described for standard CCP modules.
Additional details on timer resources are provided in
Section 15.1.1 “CCP Modules and Timer
Resources”.
16.2 Capture and Compare Modes
Except for the operation of the Special Event Trigger
discussed below, the Capture and Compare modes of
the ECCP module are identical in operation to that of
CCP2. These are discussed in detail in Section 15.2
“Capture Mode” and Section 15.3 “Compare
Mode”. No changes are required when moving
between 28-pin and 40/44-pin devices.
16.2.1 SPECIAL EVENT TRIGGER
The Special Event Trigger output of ECCP resets the
TMR1 or TMR3 register pair, depending on which timer
resource is currently selected. This allows the CCPR1
register to effectively be a 16-Bit Programmable Period
register for Timer1 or Timer3.
16.3 Standard PWM Mode
When configured in Single Output mode, the ECCP
module functions identically to the standard CCP
module in PWM mode, as described in Section 15.4
“PWM Mode”. This is also sometimes referred to as
“Compatible CCP” mode, as in Table 16-1.
TABLE 16-1: PIN ASSIGNMENTS FOR VARIOUS ECCP MODES
Note: When setting up single output PWM
operations, users are free to use either of
the processes described in Section 15.4.4
“Setup for PWM Operation” or
Section 16.4.9 “Setup for PWM Operation”.
The latter is more generic and will
work for either single or multi-output PWM.
ECCP Mode CCP1CON
Configuration RC2 RD5 RD6 RD7
All 40/44-Pin Devices:
Compatible CCP 00xx 11xx CCP1 RD5/PSP5 RD6/PSP6 RD7/PSP7
Dual PWM 10xx 11xx P1A P1B RD6/PSP6 RD7/PSP7
Quad PWM x1xx 11xx P1A P1B P1C P1D
Legend: x = Don’t care. Shaded cells indicate pin assignments not used by ECCP in a given mode.© 2008 Microchip Technology Inc. DS39631E-page 149
PIC18F2420/2520/4420/4520
16.4 Enhanced PWM Mode
The Enhanced PWM mode provides additional PWM
output options for a broader range of control applications.
The module is a backward compatible version of
the standard CCP module and offers up to four outputs,
designated P1A through P1D. Users are also able to
select the polarity of the signal (either active-high or
active-low). The module’s output mode and polarity are
configured by setting the P1M<1:0> and CCP1M<3:0>
bits of the CCP1CON register.
Figure 16-1 shows a simplified block diagram of PWM
operation. All control registers are double-buffered and
are loaded at the beginning of a new PWM cycle (the
period boundary when Timer2 resets) in order to prevent
glitches on any of the outputs. The exception is the
PWM Dead-Band Delay register, PWM1CON, which is
loaded at either the duty cycle boundary or the period
boundary (whichever comes first). Because of the buffering,
the module waits until the assigned timer resets
instead of starting immediately. This means that
Enhanced PWM waveforms do not exactly match the
standard PWM waveforms, but are instead offset by
one full instruction cycle (4 TOSC).
As before, the user must manually configure the
appropriate TRIS bits for output.
16.4.1 PWM PERIOD
The PWM period is specified by writing to the PR2
register. The PWM period can be calculated using the
following equation.
EQUATION 16-1:
PWM frequency is defined as 1/[PWM period]. When
TMR2 is equal to PR2, the following three events occur
on the next increment cycle:
• TMR2 is cleared
• The CCP1 pin is set (if PWM duty cycle = 0%, the
CCP1 pin will not be set)
• The PWM duty cycle is copied from CCPR1L into
CCPR1H
FIGURE 16-1: SIMPLIFIED BLOCK DIAGRAM OF THE ENHANCED PWM MODULE
Note: The Timer2 postscaler (see Section 13.0
“Timer2 Module”) is not used in the
determination of the PWM frequency. The
postscaler could be used to have a servo
update rate at a different frequency than
the PWM output.
PWM Period = [(PR2) + 1] • 4 • TOSC •
(TMR2 Prescale Value)
CCPR1L
CCPR1H (Slave)
Comparator
TMR2
Comparator
PR2
(Note 1)
R Q
S
Duty Cycle Registers
CCP1CON<5:4>
Clear Timer,
set CCP1 pin and
latch D.C.
Note: The 8-bit TMR2 register is concatenated with the 2-bit internal Q clock, or 2 bits of the prescaler, to create the 10-bit
time base.
TRISx
CCP1/P1A
TRISx
P1B
TRISx
TRISx
P1D
Output
Controller
P1M1<1:0>
2
CCP1M<3:0>
4
PWM1CON
CCP1/P1A
P1B
P1C
P1D
P1CPIC18F2420/2520/4420/4520
DS39631E-page 150 © 2008 Microchip Technology Inc.
16.4.2 PWM DUTY CYCLE
The PWM duty cycle is specified by writing to the
CCPR1L register and to the CCP1CON<5:4> bits. Up
to 10-bit resolution is available. The CCPR1L contains
the eight MSbs and the CCP1CON<5:4> bits contain
the two LSbs. This 10-bit value is represented by
CCPR1L:CCP1CON<5:4>. The PWM duty cycle is
calculated by the following equation.
EQUATION 16-2:
CCPR1L and CCP1CON<5:4> can be written to at any
time, but the duty cycle value is not copied into
CCPR1H until a match between PR2 and TMR2 occurs
(i.e., the period is complete). In PWM mode, CCPR1H
is a read-only register.
The CCPR1H register and a 2-bit internal latch are
used to double-buffer the PWM duty cycle. This
double-buffering is essential for glitchless PWM operation.
When the CCPR1H and 2-bit latch match TMR2,
concatenated with an internal 2-bit Q clock or two bits
of the TMR2 prescaler, the CCP1 pin is cleared. The
maximum PWM resolution (bits) for a given PWM
frequency is given by the following equation.
EQUATION 16-3:
16.4.3 PWM OUTPUT CONFIGURATIONS
The P1M<1:0> bits in the CCP1CON register allow one
of four configurations:
• Single Output
• Half-Bridge Output
• Full-Bridge Output, Forward mode
• Full-Bridge Output, Reverse mode
The Single Output mode is the standard PWM mode
discussed in Section 16.4 “Enhanced PWM Mode”.
The Half-Bridge and Full-Bridge Output modes are
covered in detail in the sections that follow.
The general relationship of the outputs in all
configurations is summarized in Figure 16-2 and
Figure 16-3.
TABLE 16-2: EXAMPLE PWM FREQUENCIES AND RESOLUTIONS AT 40 MHz
PWM Duty Cycle = (CCPR1L:CCP1CON<5:4>) •
TOSC • (TMR2 Prescale Value)
Note: If the PWM duty cycle value is longer than
the PWM period, the CCP1 pin will not be
cleared.
( ) PWM Resolution (max) =
FOSC
FPWM
log
log(2)
bits
PWM Frequency 2.44 kHz 9.77 kHz 39.06 kHz 156.25 kHz 312.50 kHz 416.67 kHz
Timer Prescaler (1, 4, 16) 16 4 1 1 1 1
PR2 Value FFh FFh FFh 3Fh 1Fh 17h
Maximum Resolution (bits) 10 10 10 8 7 6.58© 2008 Microchip Technology Inc. DS39631E-page 151
PIC18F2420/2520/4420/4520
FIGURE 16-2: PWM OUTPUT RELATIONSHIPS (ACTIVE-HIGH STATE)
FIGURE 16-3: PWM OUTPUT RELATIONSHIPS (ACTIVE-LOW STATE)
0
Period
00
10
01
11
SIGNAL PR2 + 1
CCP1CON<7:6>
P1A Modulated
P1A Modulated
P1B Modulated
P1A Active
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
P1B Modulated
P1C Active
P1D Inactive
Duty
Cycle
(Single Output)
(Half-Bridge)
(Full-Bridge,
Forward)
(Full-Bridge,
Reverse)
Delay(1) Delay(1)
0
Period
00
10
01
11
SIGNAL PR2 + 1 CCP1CON<7:6>
P1A Modulated
P1A Modulated
P1B Modulated
P1A Active
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
P1B Modulated
P1C Active
P1D Inactive
Duty
Cycle
(Single Output)
(Half-Bridge)
(Full-Bridge,
Forward)
(Full-Bridge,
Reverse)
Delay(1) Delay(1)
Relationships:
• Period = 4 * TOSC * (PR2 + 1) * (TMR2 Prescale Value)
• Duty Cycle = TOSC * (CCPR1L<7:0>:CCP1CON<5:4>) * (TMR2 Prescale Value)
• Delay = 4 * TOSC * (PWM1CON<6:0>)
Note 1: Dead-band delay is programmed using the PWM1CON register (see Section 16.4.6 “Programmable
Dead-Band Delay”).PIC18F2420/2520/4420/4520
DS39631E-page 152 © 2008 Microchip Technology Inc.
16.4.4 HALF-BRIDGE MODE
In the Half-Bridge Output mode, two pins are used as
outputs to drive push-pull loads. The PWM output signal
is output on the P1A pin, while the complementary PWM
output signal is output on the P1B pin (Figure 16-4). This
mode can be used for half-bridge applications, as shown
in Figure 16-5, or for full-bridge applications where four
power switches are being modulated with two PWM
signals.
In Half-Bridge Output mode, the programmable deadband
delay can be used to prevent shoot-through
current in half-bridge power devices. The value of bits,
PDC<6:0>, sets the number of instruction cycles before
the output is driven active. If the value is greater than
the duty cycle, the corresponding output remains
inactive during the entire cycle. See Section 16.4.6
“Programmable Dead-Band Delay” for more details
of the dead-band delay operations.
Since the P1A and P1B outputs are multiplexed with
the PORTC<2> and PORTD<5> data latches, the
TRISC<2> and TRISD<5> bits must be cleared to
configure P1A and P1B as outputs.
FIGURE 16-4: HALF-BRIDGE PWM
OUTPUT
FIGURE 16-5: EXAMPLES OF HALF-BRIDGE OUTPUT MODE APPLICATIONS
Period
Duty Cycle
td
td
(1)
P1A(2)
P1B(2)
td = Dead-Band Delay
Period
(1) (1)
Note 1: At this time, the TMR2 register is equal to the
PR2 register.
2: Output signals are shown as active-high.
PIC18F4X2X
P1A
P1B
FET
Driver
FET
Driver
V+
V-
Load
+
V
-
+
V
-
FET
Driver
FET
Driver
V+
V-
Load
FET
Driver
FET
Driver
PIC18F4X2X
P1A
P1B
Standard Half-Bridge Circuit (“Push-Pull”)
Half-Bridge Output Driving a Full-Bridge Circuit© 2008 Microchip Technology Inc. DS39631E-page 153
PIC18F2420/2520/4420/4520
16.4.5 FULL-BRIDGE MODE
In Full-Bridge Output mode, four pins are used as
outputs; however, only two outputs are active at a time.
In the Forward mode, pin P1A is continuously active
and pin P1D is modulated. In the Reverse mode, pin
P1C is continuously active and pin P1B is modulated.
These are illustrated in Figure 16-6.
P1A, P1B, P1C and P1D outputs are multiplexed with
the PORTC<2> and PORTD<7:5> data latches. The
TRISC<2> and TRISD<7:5> bits must be cleared to
make the P1A, P1B, P1C and P1D pins outputs.
FIGURE 16-6: FULL-BRIDGE PWM OUTPUT
Period
Duty Cycle
P1A(2)
P1B(2)
P1C(2)
P1D(2)
Forward Mode
(1)
Period
Duty Cycle
P1A(2)
P1C(2)
P1D(2)
P1B(2)
Reverse Mode
(1)
(1) (1)
Note 1: At this time, the TMR2 register is equal to the PR2 register.
Note 2: Output signal is shown as active-high.PIC18F2420/2520/4420/4520
DS39631E-page 154 © 2008 Microchip Technology Inc.
FIGURE 16-7: EXAMPLE OF FULL-BRIDGE OUTPUT MODE APPLICATION
16.4.5.1 Direction Change in Full-Bridge Mode
In the Full-Bridge Output mode, the P1M1 bit in the
CCP1CON register allows user to control the forward/
reverse direction. When the application firmware
changes this direction control bit, the module will
assume the new direction on the next PWM cycle.
Just before the end of the current PWM period, the
modulated outputs (P1B and P1D) are placed in their
inactive state, while the unmodulated outputs (P1A and
P1C) are switched to drive in the opposite direction.
This occurs in a time interval of 4 TOSC * (Timer2
Prescale Value) before the next PWM period begins.
The Timer2 prescaler will be either 1, 4 or 16, depending
on the value of the T2CKPS<1:0> bits
(T2CON<1:0>). During the interval from the switch of
the unmodulated outputs to the beginning of the next
period, the modulated outputs (P1B and P1D) remain
inactive. This relationship is shown in Figure 16-8.
Note that in the Full-Bridge Output mode, the CCP1
module does not provide any dead-band delay. In general,
since only one output is modulated at all times,
dead-band delay is not required. However, there is a
situation where a dead-band delay might be required.
This situation occurs when both of the following
conditions are true:
1. The direction of the PWM output changes when
the duty cycle of the output is at or near 100%.
2. The turn-off time of the power switch, including
the power device and driver circuit, is greater
than the turn-on time.
Figure 16-9 shows an example where the PWM
direction changes from forward to reverse at a near
100% duty cycle. At time t1, the outputs P1A and P1D
become inactive, while output P1C becomes active. In
this example, since the turn-off time of the power
devices is longer than the turn-on time, a shoot-through
current may flow through power devices, QC and QD
(see Figure 16-7), for the duration of ‘t’. The same
phenomenon will occur to power devices, QA and QB,
for PWM direction change from reverse to forward.
If changing PWM direction at high duty cycle is required
for an application, one of the following requirements
must be met:
1. Reduce PWM for a PWM period before
changing directions.
2. Use switch drivers that can drive the switches off
faster than they can drive them on.
Other options to prevent shoot-through current may
exist.
P1A
P1C
FET
Driver
FET
Driver
V+
V-
Load
FET
Driver
FET
Driver
P1B
P1D
QA
QB QD
QC PIC18F4X2X© 2008 Microchip Technology Inc. DS39631E-page 155
PIC18F2420/2520/4420/4520
FIGURE 16-8: PWM DIRECTION CHANGE
FIGURE 16-9: PWM DIRECTION CHANGE AT NEAR 100% DUTY CYCLE
DC
Period(1)
SIGNAL
Note 1: The direction bit in the CCP1 Control register (CCP1CON<7>) is written any time during the PWM cycle.
2: When changing directions, the P1A and P1C signals switch before the end of the current PWM cycle at intervals
of 4 TOSC, 16 TOSC or 64 TOSC, depending on the Timer2 prescaler value. The modulated P1B and P1D signals
are inactive at this time.
Period
(Note 2)
P1A (Active-High)
P1B (Active-High)
P1C (Active-High)
P1D (Active-High)
DC
Forward Period Reverse Period
P1A(1)
tON(2)
tOFF(3)
t = tOFF – tON(2,3)
P1B(1)
P1C(1)
P1D(1)
External Switch D(1)
Potential
Shoot-Through
Current(1)
Note 1: All signals are shown as active-high.
2: tON is the turn-on delay of power switch, QC, and its driver.
3: tOFF is the turn-off delay of power switch, QD, and its driver.
External Switch C(1)
t1
DC
DCPIC18F2420/2520/4420/4520
DS39631E-page 156 © 2008 Microchip Technology Inc.
16.4.6 PROGRAMMABLE DEAD-BAND
DELAY
In half-bridge applications where all power switches are
modulated at the PWM frequency at all times, the
power switches normally require more time to turn off
than to turn on. If both the upper and lower power
switches are switched at the same time (one turned on
and the other turned off), both switches may be on for
a short period of time until one switch completely turns
off. During this brief interval, a very high current (shootthrough
current) may flow through both power
switches, shorting the bridge supply. To avoid this
potentially destructive shoot-through current from flowing
during switching, turning on either of the power
switches is normally delayed to allow the other switch
to completely turn off.
In the Half-Bridge Output mode, a digitally programmable
dead-band delay is available to avoid shoot-through
current from destroying the bridge power switches. The
delay occurs at the signal transition from the nonactive
state to the active state (see Figure 16-4 for illustration).
Bits, PDC<6:0>, of the PWM1CON register
(Register 16-2) set the delay period in terms of microcontroller
instruction cycles (TCY or 4 TOSC). These bits
are not available on 28-pin devices as the standard CCP
module does not support half-bridge operation.
16.4.7 ENHANCED PWM AUTO-SHUTDOWN
When the CCP1 is programmed for any of the Enhanced
PWM modes, the active output pins may be configured
for auto-shutdown. Auto-shutdown immediately places
the Enhanced PWM output pins into a defined shutdown
state when a shutdown event occurs.
A shutdown event can be caused by either of the
comparator modules, a low level on the Fault input pin
(FLT0) or any combination of these three sources. The
comparators may be used to monitor a voltage input
proportional to a current being monitored in the bridge
circuit. If the voltage exceeds a threshold, the
comparator switches state and triggers a shutdown.
Alternatively, a low digital signal on FLT0 can also trigger
a shutdown. The auto-shutdown feature can be disabled
by not selecting any auto-shutdown sources. The autoshutdown
sources to be used are selected using the
ECCPAS<2:0> bits (ECCP1AS<6:4>).
When a shutdown occurs, the output pins are
asynchronously placed in their shutdown states,
specified by the PSSAC<1:0> and PSSBD<1:0> bits
(ECCPAS<2:0>). Each pin pair (P1A/P1C and P1B/
P1D) may be set to drive high, drive low or be tri-stated
(not driving). The ECCPASE bit (ECCP1AS<7>) is also
set to hold the Enhanced PWM outputs in their
shutdown states.
The ECCPASE bit is set by hardware when a shutdown
event occurs. If automatic restarts are not enabled, the
ECCPASE bit is cleared by firmware when the cause of
the shutdown clears. If automatic restarts are enabled,
the ECCPASE bit is automatically cleared when the
cause of the auto-shutdown has cleared.
If the ECCPASE bit is set when a PWM period begins,
the PWM outputs remain in their shutdown state for that
entire PWM period. When the ECCPASE bit is cleared,
the PWM outputs will return to normal operation at the
beginning of the next PWM period.
Note: Programmable dead-band delay is not
implemented in 28-pin devices with
standard CCP modules.
Note: Writing to the ECCPASE bit is disabled
while a shutdown condition is active.
REGISTER 16-2: PWM1CON: PWM DEAD-BAND DELAY 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
PRSEN PDC6(1) PDC5(1) PDC4(1) PDC3(1) PDC2(1) PDC1(1) PDC0(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 PRSEN: PWM Restart Enable bit
1 = Upon auto-shutdown, the ECCPASE bit clears automatically once the shutdown event goes away;
the PWM restarts automatically
0 = Upon auto-shutdown, ECCPASE must be cleared in software to restart the PWM
bit 6-0 PDC6:PDC0: PWM Delay Count bits(1)
Delay time, in number of FOSC/4 (4 * TOSC) cycles, between the scheduled and actual time for a PWM
signal to transition to active.
Note 1: Reserved on 28-pin devices; maintain these bits clear.© 2008 Microchip Technology Inc. DS39631E-page 157
PIC18F2420/2520/4420/4520
REGISTER 16-3: ECCP1AS: ECCP AUTO-SHUTDOWN 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
ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1(1) PSSBD0(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 ECCPASE: ECCP Auto-Shutdown Event Status bit
1 = A shutdown event has occurred; ECCP outputs are in shutdown state
0 = ECCP outputs are operating
bit 6-4 ECCPAS<2:0>: ECCP Auto-Shutdown Source Select bits
111 = FLT0 or Comparator 1 or Comparator 2
110 = FLT0 or Comparator 2
101 = FLT0 or Comparator 1
100 = FLT0
011 = Either Comparator 1 or 2
010 = Comparator 2 output
001 = Comparator 1 output
000 = Auto-shutdown is disabled
bit 3-2 PSSAC<1:0>: Pins A and C Shutdown State Control bits
1x = Pins A and C are tri-state (40/44-pin devices); PWM output is tri-state (28-pin devices)
01 = Drive Pins A and C to ‘1’
00 = Drive Pins A and C to ‘0’
bit 1-0 PSSBD<1:0>: Pins B and D Shutdown State Control bits(1)
1x = Pins B and D tri-state
01 = Drive Pins B and D to ‘1’
00 = Drive Pins B and D to ‘0’
Note 1: Reserved on 28-pin devices; maintain these bits clear.PIC18F2420/2520/4420/4520
DS39631E-page 158 © 2008 Microchip Technology Inc.
16.4.7.1 Auto-Shutdown and Automatic
Restart
The auto-shutdown feature can be configured to allow
automatic restarts of the module following a shutdown
event. This is enabled by setting the PRSEN bit of the
PWM1CON register (PWM1CON<7>).
In Shutdown mode with PRSEN = 1 (Figure 16-10), the
ECCPASE bit will remain set for as long as the cause
of the shutdown continues. When the shutdown condition
clears, the ECCPASE bit is cleared. If PRSEN = 0
(Figure 16-11), once a shutdown condition occurs, the
ECCPASE bit will remain set until it is cleared by firmware.
Once ECCPASE is cleared, the Enhanced PWM
will resume at the beginning of the next PWM period.
Independent of the PRSEN bit setting, if the autoshutdown
source is one of the comparators, the
shutdown condition is a level. The ECCPASE bit
cannot be cleared as long as the cause of the shutdown
persists.
The Auto-Shutdown mode can be forced by writing a ‘1’
to the ECCPASE bit.
16.4.8 START-UP CONSIDERATIONS
When the ECCP module is used in the PWM mode, the
application hardware must use the proper external pullup
and/or pull-down resistors on the PWM output pins.
When the microcontroller is released from Reset, all of
the I/O pins are in the high-impedance state. The
external circuits must keep the power switch devices in
the OFF state until the microcontroller drives the I/O
pins with the proper signal levels or activates the PWM
output(s).
The CCP1M<1:0> bits (CCP1CON<1:0>) allow the
user to choose whether the PWM output signals are
active-high or active-low for each pair of PWM output
pins (P1A/P1C and P1B/P1D). The PWM output
polarities must be selected before the PWM pins are
configured as outputs. Changing the polarity configuration
while the PWM pins are configured as outputs is
not recommended, since it may result in damage to the
application circuits.
The P1A, P1B, P1C and P1D output latches may not be
in the proper states when the PWM module is initialized.
Enabling the PWM pins for output at the same time as
the ECCP module may cause damage to the application
circuit. The ECCP module must be enabled in the
proper output mode and complete a full PWM cycle
before configuring the PWM pins as outputs. The completion
of a full PWM cycle is indicated by the TMR2IF
bit being set as the second PWM period begins.
FIGURE 16-10: PWM AUTO-SHUTDOWN (PRSEN = 1, AUTO-RESTART ENABLED)
FIGURE 16-11: PWM AUTO-SHUTDOWN (PRSEN = 0, AUTO-RESTART DISABLED)
Note: Writing to the ECCPASE bit is disabled
while a shutdown condition is active.
Shutdown
PWM
ECCPASE bit
Activity
Event
Shutdown
Event Occurs
Shutdown
Event Clears
PWM
Resumes
Normal PWM
Start of
PWM Period
PWM Period
Shutdown
PWM
ECCPASE bit
Activity
Event
Shutdown
Event Occurs
Shutdown
Event Clears
PWM
Resumes
Normal PWM
Start of
PWM Period
ECCPASE
Cleared by
Firmware
PWM Period© 2008 Microchip Technology Inc. DS39631E-page 159
PIC18F2420/2520/4420/4520
16.4.9 SETUP FOR PWM OPERATION
The following steps should be taken when configuring
the ECCP module for PWM operation:
1. Configure the PWM pins, P1A and P1B (and
P1C and P1D, if used), as inputs by setting the
corresponding TRIS bits.
2. Set the PWM period by loading the PR2 register.
3. If auto-shutdown is required:
• Disable auto-shutdown (ECCPASE = 0)
• Configure source (FLT0, Comparator 1 or
Comparator 2)
• Wait for non-shutdown condition
4. Configure the ECCP module for the desired
PWM mode and configuration by loading the
CCP1CON register with the appropriate values:
• Select one of the available output
configurations and direction with the
P1M<1:0> bits.
• Select the polarities of the PWM output
signals with the CCP1M<3:0> bits.
5. Set the PWM duty cycle by loading the CCPR1L
register and CCP1CON<5:4> bits.
6. For Half-Bridge Output mode, set the deadband
delay by loading PWM1CON<6:0> with
the appropriate value.
7. If auto-shutdown operation is required, load the
ECCP1AS register:
• Select the auto-shutdown sources using the
ECCPAS<2:0> bits.
• Select the shutdown states of the PWM
output pins using the PSSAC<1:0> and
PSSBD<1:0> bits.
• Set the ECCPASE bit (ECCP1AS<7>).
• Configure the comparators using the CMCON
register.
• Configure the comparator inputs as analog
inputs.
8. If auto-restart operation is required, set the
PRSEN bit (PWM1CON<7>).
9. Configure and start TMR2:
• Clear the TMR2 interrupt flag bit by clearing
the TMR2IF bit (PIR1<1>).
• Set the TMR2 prescale value by loading the
T2CKPS bits (T2CON<1:0>).
• Enable Timer2 by setting the TMR2ON bit
(T2CON<2>).
10. Enable PWM outputs after a new PWM cycle
has started:
• Wait until TMRx overflows (TMRxIF bit is set).
• Enable the CCP1/P1A, P1B, P1C and/or P1D
pin outputs by clearing the respective TRIS
bits.
• Clear the ECCPASE bit (ECCP1AS<7>).
16.4.10 OPERATION IN POWER-MANAGED
MODES
In Sleep mode, all clock sources are disabled. Timer2
will not increment and the state of the module will not
change. If the ECCP pin is driving a value, it will continue
to drive that value. When the device wakes up, it
will continue from this state. If Two-Speed Start-ups are
enabled, the initial start-up frequency from INTOSC
and the postscaler may not be stable immediately.
In PRI_IDLE mode, the primary clock will continue to
clock the ECCP module without change. In all other
power-managed modes, the selected power-managed
mode clock will clock Timer2. Other power-managed
mode clocks will most likely be different than the
primary clock frequency.
16.4.10.1 Operation with Fail-Safe
Clock Monitor
If the Fail-Safe Clock Monitor is enabled, a clock failure
will force the device into the power-managed RC_RUN
mode and the OSCFIF bit (PIR2<7>) will be set. The
ECCP will then be clocked from the internal oscillator
clock source, which may have a different clock
frequency than the primary clock.
See the previous section for additional details.
16.4.11 EFFECTS OF A RESET
Both Power-on Reset and subsequent Resets will force
all ports to Input mode and the CCP registers to their
Reset states.
This forces the Enhanced CCP module to reset to a
state compatible with the standard CCP module.PIC18F2420/2520/4420/4520
DS39631E-page 160 © 2008 Microchip Technology Inc.
TABLE 16-3: REGISTERS ASSOCIATED WITH ECCP MODULE AND TIMER1 TO TIMER3
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
RCON IPEN SBOREN — RI TO PD POR BOR 48
PIR1 PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
TRISB PORTB Data Direction Register 52
TRISC PORTC Data Direction Register 52
TRISD PORTD Data Direction Register 52
TMR1L Timer1 Register Low Byte 50
TMR1H Timer1 Register High Byte 50
T1CON RD16 T1RUN T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 50
TMR2 Timer2 Register 50
T2CON — T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0 50
PR2 Timer2 Period Register 50
TMR3L Timer3 Register Low Byte 51
TMR3H Timer3 Register High Byte 51
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 51
CCPR1L Capture/Compare/PWM Register 1 Low Byte 51
CCPR1H Capture/Compare/PWM Register 1 High Byte 51
CCP1CON P1M1(1) P1M0(1) DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 51
ECCP1AS ECCPASE ECCPAS2 ECCPAS1 ECCPAS0 PSSAC1 PSSAC0 PSSBD1(1) PSSBD0(1) 51
PWM1CON PRSEN PDC6(1) PDC5(1) PDC4(1) PDC3(1) PDC2(1) PDC1(1) PDC0(1) 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used during ECCP operation.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.© 2008 Microchip Technology Inc. DS39631E-page 161
PIC18F2420/2520/4420/4520
17.0 MASTER SYNCHRONOUS
SERIAL PORT (MSSP)
MODULE
17.1 Master SSP (MSSP) Module
Overview
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 (I2C)
- Full Master mode
- Slave mode (with general address call)
The I2C interface supports the following modes in
hardware:
• Master mode
• Multi-Master mode
• Slave mode
17.2 Control Registers
The MSSP module has three associated registers.
These include a status register (SSPSTAT) and two
control registers (SSPCON1 and SSPCON2). The use
of these registers and their individual configuration bits
differ significantly depending on whether the MSSP
module is operated in SPI or I2C mode.
Additional details are provided under the individual
sections.
17.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) – RC5/SDO
• Serial Data In (SDI) – RC4/SDI/SDA
• Serial Clock (SCK) – RC3/SCK/SCL
Additionally, a fourth pin may be used when in a Slave
mode of operation:
• Slave Select (SS) – RA5/SS
Figure 17-1 shows the block diagram of the MSSP
module when operating in SPI mode.
FIGURE 17-1: MSSP BLOCK DIAGRAM
(SPI MODE)
( )
Read Write
Internal
Data Bus
SSPSR reg
SSPM<3:0>
bit 0 Shift
Clock
SS Control
Enable
Edge
Select
Clock Select
TMR2 Output
Prescaler TOSC
4, 16, 64
2
Edge
Select
2
4
Data to TX/RX in SSPSR
TRIS bit
2
SMP:CKE
RC5/SDO
SSPBUF reg
RC4/SDI/SDA
RA5/AN4/SS/
RC3/SCK/
SCL
HLVDIN/C2OUTPIC18F2420/2520/4420/4520
DS39631E-page 162 © 2008 Microchip Technology Inc.
17.3.1 REGISTERS
The MSSP module has four registers for SPI mode
operation. These are:
• MSSP Control Register 1 (SSPCON1)
• MSSP Status Register (SSPSTAT)
• Serial Receive/Transmit Buffer Register
(SSPBUF)
• MSSP Shift Register (SSPSR) – Not directly
accessible
SSPCON1 and SSPSTAT are the control and status
registers in SPI mode operation. The SSPCON1 register
is readable and writable. The lower 6 bits of the
SSPSTAT are read-only. The upper two bits of the
SSPSTAT are read/write.
SSPSR is the shift register used for shifting data in or
out. SSPBUF is the buffer register to which data bytes
are written to or read from.
In receive operations, SSPSR and SSPBUF together
create a double-buffered receiver. When SSPSR
receives a complete byte, it is transferred to SSPBUF
and the SSPIF interrupt is set.
During transmission, the SSPBUF is not doublebuffered.
A write to SSPBUF will write to both SSPBUF
and SSPSR.
REGISTER 17-1: SSPSTAT: MSSP STATUS REGISTER (SPI MODE)
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE(1) D/A P S R/W UA BF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 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.
bit 6 CKE: SPI Clock Select bit(1)
1 = Transmit occurs on transition from active to Idle clock state
0 = Transmit occurs on transition from Idle to active clock state
bit 5 D/A: Data/Address bit
Used in I2C™ mode only.
bit 4 P: Stop bit
Used in I2C mode only. This bit is cleared when the MSSP module is disabled, SSPEN is cleared.
bit 3 S: Start bit
Used in I2C mode only.
bit 2 R/W: Read/Write Information bit
Used in I2C mode only.
bit 1 UA: Update Address bit
Used in I2C mode only.
bit 0 BF: Buffer Full Status bit (Receive mode only)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Note 1: Polarity of clock state is set by the CKP bit (SSPCON1<4>).© 2008 Microchip Technology Inc. DS39631E-page 163
PIC18F2420/2520/4420/4520
REGISTER 17-2: SSPCON1: MSSP CONTROL REGISTER 1 (SPI MODE)
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(1) SSPEN(2) CKP SSPM3(3) SSPM2(3) SSPM1(3) SSPM0(3)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 WCOL: Write Collision Detect bit
1 = The SSPxBUF 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(1)
SPI Slave 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. The user must read the
SSPBUF, even if only transmitting data, to avoid setting overflow (must be cleared in software).
0 = No overflow
bit 5 SSPEN: Master Synchronous Serial Port Enable bit(2)
1 = Enables serial port and configures SCK, SDO, SDI and SS as serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4 CKP: Clock Polarity Select bit
1 = Idle state for clock is a high level
0 = Idle state for clock is a low level
bit 3-0 SSPM<3:0>: Master Synchronous Serial Port Mode Select bits(3)
0101 = SPI Slave mode, clock = SCK pin; SS pin control disabled; SS can be used as I/O pin
0100 = SPI Slave mode, clock = SCK pin; SS pin control enabled
0011 = SPI Master mode, clock = TMR2 output/2
0010 = SPI Master mode, clock = FOSC/64
0001 = SPI Master mode, clock = FOSC/16
0000 = SPI Master mode, clock = FOSC/4
Note 1: In Master mode, the overflow bit is not set since each new reception (and transmission) is initiated by
writing to the SSPBUF register.
2: When enabled, these pins must be properly configured as input or output.
3: Bit combinations not specifically listed here are either reserved or implemented in I2C™ mode only.PIC18F2420/2520/4420/4520
DS39631E-page 164 © 2008 Microchip Technology Inc.
17.3.2 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)
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<0>) 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<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. The
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 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 17-1 shows the
loading of the SSPBUF (SSPSR) for data transmission.
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.
EXAMPLE 17-1: LOADING THE SSPBUF (SSPSR) REGISTER
Note: The SSPBUF register cannot be used with
read-modify-write instructions such as
BCF, BTFSC and COMF, etc.
LOOP BTFSS SSPSTAT, BF ;Has data been received (transmit complete)?
BRA LOOP ;No
MOVF SSPBUF, W ;WREG reg = contents of SSPBUF
MOVWF RXDATA ;Save in user RAM, if data is meaningful
MOVF TXDATA, W ;W reg = contents of TXDATA
MOVWF SSPBUF ;New data to xmit
Note: To avoid lost data in Master mode, a read
of the SSPBUF must be performed to clear
the Buffer Full (BF) detect bit
(SSPSTAT<0>) between each
transmission.© 2008 Microchip Technology Inc. DS39631E-page 165
PIC18F2420/2520/4420/4520
17.3.3 ENABLING SPI I/O
To enable the serial port, MSSP Enable bit, SSPEN
(SSPCON1<5>), must be set. To reset or reconfigure
SPI mode, clear the SSPEN bit, reinitialize 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 as follows:
• SDI is automatically controlled by the SPI module
• SDO must have TRISC<5> bit cleared
• SCK (Master mode) must have TRISC<3> bit
cleared
• SCK (Slave mode) must have TRISC<3> bit set
• SS must have TRISA<5> 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.
17.3.4 TYPICAL CONNECTION
Figure 17-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 opposite edge
of the clock. Both processors should be programmed to
the 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 17-2: SPI MASTER/SLAVE CONNECTION
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDO
SDI
PROCESSOR 1
SCK
SPI Master SSPM<3:0> = 00xxb
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDI
SDO
PROCESSOR 2
SCK
SPI Slave SSPM<3:0> = 010xb
Serial ClockPIC18F2420/2520/4420/4520
DS39631E-page 166 © 2008 Microchip Technology Inc.
17.3.5 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 17-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 the CKP bit (SSPCON1<4>). This, then,
would give waveforms for SPI communication as
shown in Figure 17-3, Figure 17-5 and Figure 17-6,
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 TCY)
• FOSC/16 (or 4 • TCY)
• FOSC/64 (or 16 • TCY)
• Timer2 output/2
This allows a maximum data rate (at 40 MHz) of
10.00 Mbps.
Figure 17-3 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 17-3: SPI MODE WAVEFORM (MASTER MODE)
SCK
(CKP = 0
SCK
(CKP = 1
SCK
(CKP = 0
SCK
(CKP = 1
4 Clock
Modes
Input
Sample
Input
Sample
SDI
bit 7 bit 0
SDO bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
bit 7
SDI
SSPIF
(SMP = 1)
(SMP = 0)
(SMP = 1)
CKE = 1)
CKE = 0)
CKE = 1)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SDO bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
(CKE = 0)
(CKE = 1)
Next Q4 Cycle
after Q2↓
bit 0© 2008 Microchip Technology Inc. DS39631E-page 167
PIC18F2420/2520/4420/4520
17.3.6 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.
Before enabling the module in SPI Slave mode, the
clock line must match the proper Idle state. The clock
line can be observed by reading the SCK pin. The Idle
state is determined by the CKP bit (SSPCON1<4>).
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.
17.3.7 SLAVE SELECT
SYNCHRONIZATION
The SS pin allows a Synchronous Slave mode. The
SPI must be in Slave mode with SS pin control enabled
(SSPCON1<3:0> = 04h). The pin must not be driven
low for the SS pin to function as an input. The data latch
must be high. 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 module resets, the bit counter is forced
to ‘0’. This can be done by either 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.
FIGURE 17-4: SLAVE SYNCHRONIZATION WAVEFORM
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.
2: If the SPI is used in Slave mode with CKE
set, then the SS pin control must be
enabled.
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit 7
SDO bit 7 bit 6 bit 7
SSPIF
Interrupt
(SMP = 0)
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
bit 0
bit 7
bit 0
Next Q4 Cycle
after Q2↓PIC18F2420/2520/4420/4520
DS39631E-page 168 © 2008 Microchip Technology Inc.
FIGURE 17-5: SPI MODE WAVEFORM (SLAVE MODE WITH CKE = 0)
FIGURE 17-6: SPI MODE WAVEFORM (SLAVE MODE WITH CKE = 1)
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit 7
SDO bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
SSPIF
Interrupt
(SMP = 0)
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
Optional
Next Q4 Cycle
after Q2↓
bit 0
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit 7 bit 0
SDO bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
SSPIF
Interrupt
(SMP = 0)
CKE = 1)
CKE = 1)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
Not Optional
Next Q4 Cycle
after Q2↓© 2008 Microchip Technology Inc. DS39631E-page 169
PIC18F2420/2520/4420/4520
17.3.8 OPERATION IN POWER-MANAGED
MODES
In SPI Master mode, module clocks may be operating
at a different speed than when in full-power mode; in
the case of Sleep mode, all clocks are halted.
In most Idle modes, a clock is provided to the peripherals.
That clock should be from the primary clock
source, the secondary clock (Timer1 oscillator at
32.768 kHz) or the INTOSC source. See Section 2.7
“Clock Sources and Oscillator Switching” for
additional information.
In most cases, the speed that the master clocks SPI
data is not important; however, this should be
evaluated for each system.
If MSSP interrupts are enabled, they can wake the controller
from Sleep mode, or one of the Idle modes, when
the master completes sending data. If an exit from
Sleep or Idle mode is not desired, MSSP interrupts
should be disabled.
If the Sleep mode is selected, all module clocks are
halted and the transmission/reception will remain in
that state until the devices wakes. After the device
returns to Run mode, the module will resume
transmitting and receiving data.
In SPI Slave mode, the SPI Transmit/Receive Shift
register operates asynchronously to the device. This
allows the device to be placed in any power-managed
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, and if
enabled, will wake the device.
17.3.9 EFFECTS OF A RESET
A Reset disables the MSSP module and terminates the
current transfer.
17.3.10 BUS MODE COMPATIBILITY
Table 17-1 shows the compatibility between the
standard SPI modes and the states of the CKP and
CKE control bits.
TABLE 17-1: SPI BUS MODES
There is also an SMP bit which controls when the data
is sampled.
TABLE 17-2: REGISTERS ASSOCIATED WITH SPI OPERATION
Standard SPI Mode
Terminology
Control Bits State
CKP CKE
0, 0 0 1
0, 1 0 0
1, 0 1 1
1, 1 1 0
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
TRISA TRISA7(2) TRISA6(2) PORTA Data Direction Register 52
TRISC PORTC Data Direction Register 52
SSPBUF MSSP Receive Buffer/Transmit Register 50
SSPCON1 WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 50
SSPSTAT SMP CKE D/A P S R/W UA BF 50
Legend: Shaded cells are not used by the MSSP in SPI mode.
Note 1: These bits are unimplemented in 28-pin devices; always maintain these bits clear.
2: PORTA<7:6> and their direction bits are individually configured as port pins based on various primary
oscillator modes. When disabled, these bits read as ‘0’.PIC18F2420/2520/4420/4520
DS39631E-page 170 © 2008 Microchip Technology Inc.
17.4 I2C Mode
The MSSP module in I2C 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 modes.
Two pins are used for data transfer:
• Serial clock (SCL) – RC3/SCK/SCL
• Serial data (SDA) – RC4/SDI/SDA
The user must configure these pins as inputs or outputs
through the TRISC<4:3> bits.
FIGURE 17-7: MSSP BLOCK DIAGRAM
(I2C MODE)
17.4.1 REGISTERS
The MSSP module has six registers for I2C operation.
These are:
• MSSP Control Register 1 (SSPCON1)
• MSSP Control Register 2 (SSPCON2)
• MSSP Status Register (SSPSTAT)
• Serial Receive/Transmit Buffer Register
(SSPBUF)
• MSSP Shift Register (SSPSR) – Not directly
accessible
• MSSP Address Register (SSPADD)
SSPCON1, SSPCON2 and SSPSTAT are the control
and status registers in I2C mode operation. The
SSPCON1 and SSPCON2 registers are readable and
writable. The lower 6 bits of the SSPSTAT are read-only.
The upper two bits of the SSPSTAT are read/write.
SSPSR is the shift register used for shifting data in or
out. SSPBUF is the buffer register to which data bytes
are written to or read from.
SSPADD register holds the slave device address when
the MSSP is configured in I2C Slave mode. When the
MSSP is configured in Master mode, the lower seven
bits of SSPADD act as the Baud Rate Generator reload
value.
In receive operations, SSPSR and SSPBUF together
create a double-buffered receiver. When SSPSR
receives a complete byte, it is transferred to SSPBUF
and the SSPIF interrupt is set.
During transmission, the SSPBUF is not doublebuffered.
A write to SSPBUF will write to both SSPBUF
and SSPSR.
Read Write
SSPSR reg
Match Detect
SSPADD reg
Start and
Stop bit Detect
SSPBUF reg
Internal
Data Bus
Addr Match
Set, Reset
S, P bits
(SSPSTAT reg)
RC3/SCK/SCL
RC4/SDI/
Shift
Clock
MSb
SDA
LSb© 2008 Microchip Technology Inc. DS39631E-page 171
PIC18F2420/2520/4420/4520
REGISTER 17-3: SSPSTAT: MSSP STATUS REGISTER (I2C™ MODE)
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE D/A P(1) S(1) R/W(2,3) UA BF
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 SMP: Slew Rate Control bit
In 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: SMBus Select bit
In Master or Slave mode:
1 = Enable SMBus specific inputs
0 = Disable SMBus specific inputs
bit 5 D/A: Data/Address bit
In Master mode:
Reserved.
In Slave mode:
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(1)
1 = Indicates that a Stop bit has been detected last
0 = Stop bit was not detected last
bit 3 S: Start bit(1)
1 = Indicates that a Start bit has been detected last
0 = Start bit was not detected last
bit 2 R/W: Read/Write Information bit (I2C mode only)(2,3)
In Slave mode:
1 = Read
0 = Write
In Master mode:
1 = Transmit is in progress
0 = Transmit is not in progress
bit 1 UA: Update Address bit (10-Bit Slave mode only)
1 = Indicates that the user needs to update the address in the SSPADD register
0 = Address does not need to be updated
bit 0 BF: Buffer Full Status bit
In Transmit mode:
1 = SSPBUF is full
0 = SSPBUF is empty
In Receive mode:
1 = SSPBUF is full (does not include the ACK and Stop bits)
0 = SSPBUF is empty (does not include the ACK and Stop bits)
Note 1: This bit is cleared on Reset and when SSPEN is cleared.
2: 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.
3: ORing this bit with SEN, RSEN, PEN, RCEN or ACKEN will indicate if the MSSP is in Active mode.PIC18F2420/2520/4420/4520
DS39631E-page 172 © 2008 Microchip Technology Inc.
REGISTER 17-4: SSPCON1: MSSP CONTROL REGISTER 1 (I2C™ MODE)
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(1) CKP SSPM3 SSPM2 SSPM1 SSPM0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 WCOL: Write Collision Detect bit
In Master Transmit mode:
1 = A write to the SSPBUF register was attempted while the I2C conditions were not valid for a
transmission to be started (must be cleared in software)
0 = No collision
In Slave Transmit mode:
1 = The SSPBUF register is written while it is still transmitting the previous word (must be cleared in
software)
0 = No collision
In Receive mode (Master or Slave modes):
This is a “don’t care” bit.
bit 6 SSPOV: Receive Overflow Indicator bit
In Receive mode:
1 = A byte is received while the SSPBUF register is still holding the previous byte (must be cleared in
software)
0 = No overflow
In Transmit mode:
This is a “don’t care” bit in Transmit mode.
bit 5 SSPEN: Master Synchronous Serial Port Enable bit(1)
1 = Enables the serial port and configures the SDA and SCL pins as the serial port pins
0 = Disables serial port and configures these pins as I/O port pins
bit 4 CKP: SCK Release Control bit
In Slave mode:
1 = Releases clock
0 = Holds clock low (clock stretch), used to ensure data setup time
In Master mode:
Unused in this mode.
bit 3-0 SSPM<3:0>: Master Synchronous Serial Port Mode Select bits(2)
1111 = I2C Slave mode, 10-bit address with Start and Stop bit interrupts enabled
1110 = I2C Slave mode, 7-bit address with Start and Stop bit interrupts enabled
1011 = I2C Firmware Controlled Master mode (Slave Idle)
1000 = I2C Master mode, clock = FOSC/(4 * (SSPADD + 1))
0111 = I2C Slave mode, 10-bit address
0110 = I2C Slave mode, 7-bit address
Bit combinations not specifically listed here are either reserved or implemented in SPI mode only.
Note 1: When enabled, the SDA and SCL pins must be properly configured as inputs or outputs.© 2008 Microchip Technology Inc. DS39631E-page 173
PIC18F2420/2520/4420/4520
REGISTER 17-5: SSPCON2: MSSP CONTROL REGISTER 2 (I2C™ MODE)
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
GCEN ACKSTAT ACKDT(2) ACKEN(1) RCEN(1) PEN(1) RSEN(1) SEN(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 GCEN: General Call Enable bit (Slave mode only)
1 = Enables interrupt when a general call address (0000h) is received in the SSPSR
0 = General call address disabled.
bit 6 ACKSTAT: Acknowledge Status bit (Master Transmit mode only)
1 = Acknowledge was not received from slave
0 = Acknowledge was received from slave
bit 5 ACKDT: Acknowledge Data bit (Master Receive mode only)(2)
1 = Not Acknowledge
0 = Acknowledge
bit 4 ACKEN: Acknowledge Sequence Enable bit (Master Receive mode only)(1)
1 = Initiates 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 (Master mode only)(1)
1 = Enables Receive mode for I2C
0 = Receive Idle
bit 2 PEN: Stop Condition Enable bit (Master mode only)(1)
1 = Initiates Stop condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Stop condition Idle
bit 1 RSEN: Repeated Start Condition Enable bit (Master mode only)(1)
1 = Initiates Repeated Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Repeated Start condition Idle
bit 0 SEN: Start Condition Enable/Stretch Enable bit(1)
In Master mode:
1 = Initiates Start condition on SDA and SCL pins. Automatically cleared by hardware.
0 = Start condition Idle
In Slave mode:
1 = Clock stretching is enabled for both slave transmit and slave receive (stretch enabled)
0 = Clock stretching is disabled
Note 1: For bits ACKEN, RCEN, PEN, RSEN, SEN: If the I2C module is not in the Idle mode, these bits may not be
set (no spooling) and the SSPBUF may not be written (or writes to the SSPBUF are disabled).
2: Value that will be transmitted when the user initiates an Acknowledge sequence at the end of a receive.PIC18F2420/2520/4420/4520
DS39631E-page 174 © 2008 Microchip Technology Inc.
17.4.2 OPERATION
The MSSP module functions are enabled by setting the
MSSP Enable bit, SSPEN (SSPCON1<5>).
The SSPCON1 register allows control of the I2C
operation. Four mode selection bits (SSPCON1<3:0>)
allow one of the following I2C modes to be selected:
• I2C Master mode, clock = (FOSC/4) x (SSPADD + 1)
• I2C Slave mode (7-bit addressing)
• I2C Slave mode (10-bit addressing)
• I2C Slave mode (7-bit addressing) with Start and
Stop bit interrupts enabled
• I2C Slave mode (10-bit addressing) with Start and
Stop bit interrupts enabled
• I2C Firmware Controlled Master mode, slave is
Idle
Selection of any I2C mode, with the SSPEN bit set,
forces the SCL and SDA pins to be open-drain,
provided these pins are programmed to inputs by
setting the appropriate TRISC bits. To ensure proper
operation of the module, pull-up resistors must be
provided externally to the SCL and SDA pins.
17.4.3 SLAVE MODE
In Slave mode, the SCL and SDA pins must be configured
as inputs (TRISC<4:3> set). The MSSP module
will override the input state with the output data when
required (slave-transmitter).
The I2C Slave mode hardware will always generate an
interrupt on an address match. Through the mode
select bits, the user can also choose to interrupt on
Start and Stop bits
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
load the SSPBUF register with the received value
currently in the SSPSR register.
Any combination of the following conditions will cause
the MSSP module not to give this ACK pulse:
• The Buffer Full bit, BF (SSPSTAT<0>), was set
before the transfer was received.
• The overflow bit, SSPOV (SSPCON2<6>), was
set before the transfer was received.
In this case, the SSPSR register value is not loaded
into the SSPBUF, but bit, SSPIF (PIR1<3>), is set. 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 for proper operation. The high and low times of the
I
2C specification, as well as the requirement of the
MSSP module, are shown in timing parameter 100 and
parameter 101.
17.4.3.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. 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:
1. The SSPSR register value is loaded into the
SSPBUF register.
2. The Buffer Full bit, BF, is set.
3. An ACK pulse is generated.
4. MSSP Interrupt Flag bit, SSPIF (PIR1<3>), is
set (interrupt is generated, if enabled) on the
falling edge of the ninth SCL pulse.
In 10-Bit Addressing 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. Bit, R/W (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 ‘11110 A9 A8 0’, where ‘A9’ and ‘A8’ are the
two MSbs of the address. The sequence of events for
10-Bit Addressing mode is as follows, with steps 7
through 9 for the slave-transmitter:
1. Receive first (high) byte of address (bits, SSPIF,
BF and UA (SSPSTAT<1>), are set).
2. Update the SSPADD register with second (low)
byte of address (clears UA bit and releases the
SCL line).
3. Read the SSPBUF register (clears BF bit) and
clear flag bit, SSPIF.
4. Receive second (low) byte of address (bits,
SSPIF, BF and UA, are set).
5. Update the SSPADD register with the first (high)
byte of address. If match releases SCL line, this
will clear bit, UA.
6. Read the SSPBUF register (clears BF bit) and
clear flag bit, SSPIF.
7. Receive Repeated Start condition.
8. Receive first (high) byte of address (bits, SSPIF
and BF, are set).
9. Read the SSPBUF register (clears BF bit) and
clear flag bit, SSPIF.© 2008 Microchip Technology Inc. DS39631E-page 175
PIC18F2420/2520/4420/4520
17.4.3.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 and the SDA line is held low
(ACK).
When the address byte overflow condition exists, then
the no Acknowledge (ACK) pulse is given. An overflow
condition is defined as either bit, BF (SSPSTAT<0>), is
set, or bit, SSPOV (SSPCON1<6>), is set.
An MSSP interrupt is generated for each data transfer
byte. Flag bit, SSPIF (PIR1<3>), must be cleared in
software. The SSPSTAT register is used to determine
the status of the byte.
If SEN is enabled (SSPCON2<0> = 1), RC3/SCK/SCL
will be held low (clock stretch) following each data
transfer. The clock must be released by setting bit,
CKP (SSPCON<4>). See Section 17.4.4 “Clock
Stretching” for more details.
17.4.3.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 RC3/SCK/SCL pin is
held low regardless of SEN (see Section 17.4.4
“Clock Stretching” for more detail). By stretching the
clock, the master will be unable to assert another clock
pulse until the slave is done preparing the transmit
data. The transmit data must be loaded into the
SSPBUF register which also loads the SSPSR register.
Then the RC3/SCK/SCL pin should be enabled by setting
bit, CKP (SSPCON1<4>). 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 17-9).
The ACK pulse from the master-receiver is latched on
the rising edge of the ninth SCL input pulse. If the SDA
line is high (not ACK), then the data transfer is complete.
In this case, when the ACK is latched by the
slave, the slave logic is reset (resets SSPSTAT register)
and the slave monitors for another occurrence of
the Start bit. If the SDA line was low (ACK), the next
transmit data must be loaded into the SSPBUF register.
Again, the RC3/SCK/SCL pin must be enabled by
setting bit, CKP.
An MSSP interrupt is generated for each data transfer
byte. The SSPIF bit must be cleared in software and
the SSPSTAT register is used to determine the status
of the byte. The SSPIF bit is set on the falling edge of
the ninth clock pulse.PIC18F2420/2520/4420/4520
DS39631E-page 176 © 2008 Microchip Technology Inc.
FIGURE 17-8: I2C™ SLAVE MODE TIMING WITH SEN = 0 (RECEPTION, 7-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>) SSPOV (SSPCON1<6>)
S 1 2 34 56 7 89 1 2 34 5 67 89 1 23 45 7 89 P
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D1 D0
ACK Receiving Data ACK Receiving Data R/W = 0
ACK
Receiving Address
Cleared in software
SSPBUF is read
Bus master
terminates
transfer
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
D2
6
(PIR1<3>)
CKP (SSPCON1<4>)
(CKP does not reset to ‘0’ when SEN = 0)© 2008 Microchip Technology Inc. DS39631E-page 177
PIC18F2420/2520/4420/4520
FIGURE 17-9: I2C™ SLAVE MODE TIMING (TRANSMISSION, 7-BIT ADDRESSING) SDA SCL SSPIF (PIR1<3>) BF (SSPSTAT<0>) A6 A5 A4 A3 A2 A1 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9
SSPBUF is written in software
Cleared in software
Data in
sampled
S
ACK Transmitting Data R/W = 1
ACK
Receiving Address
A7 D7
9 1
D6 D5 D4 D3 D2 D1 D0
2 3 4 5 6 7 8 9
SSPBUF is written in software
Cleared in software
From SSPIF ISR
Transmitting Data
D7
1
CKP
P
ACK
CKP is set in software CKP is set in software
SCL held low
while CPU
responds to SSPIF
Clear by reading
From SSPIF ISRPIC18F2420/2520/4420/4520
DS39631E-page 178 © 2008 Microchip Technology Inc.
FIGURE 17-10: I2C™ SLAVE MODE TIMING WITH SEN = 0 (RECEPTION, 10-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1234 567 89 12 345 67 89 1 2345 7 89 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0
Receive Data Byte
ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
D2
6
(PIR1<3>)
Cleared in software
Receive Second Byte of Address
Cleared by hardware
when SSPADD is updated
with low byte of address
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
ACK
CKP (SSPCON1<4>)
D7 D6 D5 D4 D3 D1 D0
12345 789
Receive Data Byte
Bus master
terminates
transfer
D2
6
ACK
Cleared in software Cleared in software
SSPOV (SSPCON1<6>)
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
(CKP does not reset to ‘0’ when SEN = 0)
Clock is held low until
update of SSPADD has
taken place© 2008 Microchip Technology Inc. DS39631E-page 179
PIC18F2420/2520/4420/4520
FIGURE 17-11: I2C™ SLAVE MODE TIMING (TRANSMISSION, 10-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1234 5 6789 1 23 45 678 9 12345 7 89 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 1 1 1 1 0 A8
R/W=1
ACK ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
Bus master
terminates
transfer
A9
6
(PIR1<3>)
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated with low
byte of address
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address.
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
Receive First Byte of Address
D7 D6 D5 D4 D3 D1
12345 789
ACK
D2
6
Transmitting Data Byte
D0
Dummy read of SSPBUF
to clear BF flag
Sr
Cleared in software
Write of SSPBUF
initiates transmit
Cleared in software
Completion of
clears BF flag
CKP (SSPCON1<4>)
CKP is set in software
CKP is automatically cleared in hardware, holding SCL low
Clock is held low until
update of SSPADD has
taken place
data transmission
Clock is held low until
CKP is set to ‘1’
BF flag is clear
at the end of the
third address sequencePIC18F2420/2520/4420/4520
DS39631E-page 180 © 2008 Microchip Technology Inc.
17.4.4 CLOCK STRETCHING
Both 7-Bit and 10-Bit Slave modes implement
automatic clock stretching during a transmit sequence.
The SEN bit (SSPCON2<0>) allows clock stretching to
be enabled during receives. Setting SEN will cause
the SCL pin to be held low at the end of each data
receive sequence.
17.4.4.1 Clock Stretching for 7-Bit Slave
Receive Mode (SEN = 1)
In 7-Bit Slave Receive mode, on the falling edge of the
ninth clock at the end of the ACK sequence if the BF
bit is set, the CKP bit in the SSPCON1 register is
automatically cleared, forcing the SCL output to be
held low. The CKP being cleared to ‘0’ will assert the
SCL line low. The CKP bit must be set in the user’s
Interrupt Service Routine (ISR) before reception is
allowed to continue. By holding the SCL line low, the
user has time to service the ISR and read the contents
of the SSPBUF before the master device can initiate
another receive sequence. This will prevent buffer
overruns from occurring (see Figure 17-13).
17.4.4.2 Clock Stretching for 10-Bit Slave
Receive Mode (SEN = 1)
In 10-Bit Slave Receive mode during the address
sequence, clock stretching automatically takes place
but CKP is not cleared. During this time, if the UA bit is
set after the ninth clock, clock stretching is initiated.
The UA bit is set after receiving the upper byte of the
10-bit address and following the receive of the second
byte of the 10-bit address with the R/W bit cleared to
‘0’. The release of the clock line occurs upon updating
SSPADD. Clock stretching will occur on each data
receive sequence as described in 7-bit mode.
17.4.4.3 Clock Stretching for 7-Bit Slave
Transmit Mode
7-Bit Slave Transmit mode implements clock stretching
by clearing the CKP bit after the falling edge of the
ninth clock if the BF bit is clear. This occurs regardless
of the state of the SEN bit.
The user’s ISR must set the CKP bit before transmission
is allowed to continue. By holding the SCL line
low, the user has time to service the ISR and load the
contents of the SSPBUF before the master device can
initiate another transmit sequence (see Figure 17-9).
17.4.4.4 Clock Stretching for 10-Bit Slave
Transmit Mode
In 10-Bit Slave Transmit mode, clock stretching is controlled
during the first two address sequences by the
state of the UA bit, just as it is in 10-Bit Slave Receive
mode. The first two addresses are followed by a third
address sequence which contains the high-order bits
of the 10-bit address and the R/W bit set to ‘1’. After
the third address sequence is performed, the UA bit is
not set, the module is now configured in Transmit
mode and clock stretching is controlled by the BF flag
as in 7-Bit Slave Transmit mode (see Figure 17-11).
Note 1: If the user reads the contents of the
SSPBUF before the falling edge of the
ninth clock, thus clearing the BF bit, the
CKP bit will not be cleared and clock
stretching will not occur.
2: The CKP bit can be set in software regardless
of the state of the BF bit. The user
should be careful to clear the BF bit in the
ISR before the next receive sequence in
order to prevent an overflow condition.
Note: If the user polls the UA bit and clears it by
updating the SSPADD register before the
falling edge of the ninth clock occurs and if
the user hasn’t cleared the BF bit by reading
the SSPBUF register before that time,
then the CKP bit will still NOT be asserted
low. Clock stretching on the basis of the
state of the BF bit only occurs during a
data sequence, not an address sequence.
Note 1: If the user loads the contents of SSPBUF,
setting the BF bit before the falling edge of
the ninth clock, the CKP bit will not be
cleared and clock stretching will not occur.
2: The CKP bit can be set in software
regardless of the state of the BF bit.© 2008 Microchip Technology Inc. DS39631E-page 181
PIC18F2420/2520/4420/4520
17.4.4.5 Clock Synchronization and
the CKP bit
When the CKP bit is cleared, the SCL output is forced
to ‘0’. However, clearing the CKP bit will not assert the
SCL output low until the SCL output is already sampled
low. Therefore, the CKP bit will not assert the
SCL line until an external I2C master device has
already asserted the SCL line. The SCL output will
remain low until the CKP bit is set and all other
devices on the I2C bus have deasserted SCL. This
ensures that a write to the CKP bit will not violate the
minimum high time requirement for SCL (see
Figure 17-12).
FIGURE 17-12: CLOCK SYNCHRONIZATION TIMING
SDA
SCL
DX DX – 1
WR
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
SSPCONx
CKP
Master device
deasserts clock
Master device
asserts clockPIC18F2420/2520/4420/4520
DS39631E-page 182 © 2008 Microchip Technology Inc.
FIGURE 17-13: I2C™ SLAVE MODE TIMING WITH SEN = 1 (RECEPTION, 7-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>) SSPOV (SSPCON1<6>)
S 1 2 34 56 7 8 9 1 234 5 67 89 1 23 45 7 89 P
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D1 D0
ACK Receiving Data ACK Receiving Data R/W = 0
ACK
Receiving Address
Cleared in software
SSPBUF is read
Bus master
terminates
transfer
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
D2
6
(PIR1<3>)
CKP (SSPCON1<4>)
CKP
written
to ‘1’ in
If BF is cleared
prior to the falling
edge of the 9th clock,
CKP will not be reset
to ‘0’ and no clock
stretching will occur
software
Clock is held low until
CKP is set to ‘1’
Clock is not held low
because buffer full bit is
clear prior to falling edge
of 9th clock
Clock is not held low
because ACK = 1
BF is set after falling
edge of the 9th clock,
CKP is reset to ‘0’ and
clock stretching occurs© 2008 Microchip Technology Inc. DS39631E-page 183
PIC18F2420/2520/4420/4520
FIGURE 17-14: I2C™ SLAVE MODE TIMING WITH SEN = 1 (RECEPTION, 10-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1 234 56 7 89 12345 67 89 1 2345 78 9 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0
Receive Data Byte
ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
D2
6
(PIR1<3>)
Cleared in software
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated with low
byte of address after falling edge
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address after falling edge
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
ACK
CKP (SSPCON1<4>)
D7 D6 D5 D4 D3 D1 D0
12345 789
Receive Data Byte
Bus master
terminates
transfer
D2
6
ACK
Cleared in software Cleared in software
SSPOV (SSPCON1<6>)
CKP written to ‘1’
Note: An update of the SSPADD register before
the falling edge of the ninth clock will have
no effect on UA and UA will remain set.
Note: An update of the SSPADD
register before the falling
edge of the ninth clock will
have no effect on UA and
UA will remain set.
in software
Clock is held low until
update of SSPADD has
taken place
of ninth clock of ninth clock
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
Dummy read of SSPBUF
to clear BF flag
Clock is held low until
CKP is set to ‘1’
Clock is not held low
because ACK = 1PIC18F2420/2520/4420/4520
DS39631E-page 184 © 2008 Microchip Technology Inc.
17.4.5 GENERAL CALL ADDRESS
SUPPORT
The addressing procedure for the I2C 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, in theory, respond with an
Acknowledge.
The general call address is one of eight addresses
reserved for specific purposes by the I2C 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 enabled (SSPCON2<7>
is set). Following a Start bit detect, 8 bits are shifted into
the SSPSR and the address is compared against the
SSPADD. It is also compared to the general call
address and fixed in hardware.
If the general call address matches, the SSPSR is
transferred to the SSPBUF, the BF flag bit is set (eighth
bit) and on the falling edge of the ninth bit (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. The value can be used to determine if the
address was device specific or a general call address.
In 10-bit mode, the SSPADD is required to be updated
for the second half of the address to match and the UA
bit is set (SSPSTAT<1>). If the general call address is
sampled when the GCEN bit is set, while the slave is
configured in 10-Bit Addressing mode, then the second
half of the address is not necessary, the UA bit will not
be set and the slave will begin receiving data after the
Acknowledge (Figure 17-15).
FIGURE 17-15: SLAVE MODE GENERAL CALL ADDRESS SEQUENCE
(7 OR 10-BIT ADDRESSING MODE)
SDA
SCL
S
SSPIF
BF (SSPSTAT<0>)
SSPOV (SSPCON1<6>)
Cleared in software
SSPBUF is read
R/W = 0
ACK General Call Address
Address is compared to General Call Address
GCEN (SSPCON2<7>)
Receiving Data ACK
1 2 34 56 7891 2 34 56 789
D7 D6 D5 D4 D3 D2 D1 D0
after ACK, set interrupt
‘0’
‘1’© 2008 Microchip Technology Inc. DS39631E-page 185
PIC18F2420/2520/4420/4520
17.4.6 MASTER MODE
Master mode is enabled by setting and clearing the
appropriate SSPM bits in SSPCON1 and by setting the
SSPEN bit. In Master mode, the SCL and SDA lines
are manipulated by the MSSP hardware.
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 MSSP module is disabled. Control
of the I2C bus may be taken when the P bit is set, or the
bus is Idle, with both the S and P bits clear.
In Firmware Controlled Master mode, user code
conducts all I2C bus operations based on Start and
Stop bit conditions.
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. Configure the I2C port to receive data.
5. Generate an Acknowledge condition at the end
of a received byte of data.
6. Generate a Stop condition on SDA and SCL.
The following events will cause the MSSP Interrupt
Flag bit, SSPIF, to be set (MSSP interrupt, if enabled):
• Start condition
• Stop condition
• Data transfer byte transmitted/received
• Acknowledge transmit
• Repeated Start
FIGURE 17-16: MSSP BLOCK DIAGRAM (I2C™ MASTER MODE)
Note: The MSSP module, when configured in
I
2C 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
initiate 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 a write to the
SSPBUF did not occur.
Read Write
SSPSR
Start bit, Stop bit,
SSPBUF
Internal
Data Bus
Set/Reset, S, P, WCOL (SSPSTAT);
Shift
Clock
MSb LSb
SDA
Acknowledge
Generate
Stop bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
end of XMIT/RCV
SCL
SCL In
Bus Collision
SDA In Receive Enable
Clock Cntl
Clock Arbitrate/WCOL Detect
(hold off clock source)
SSPADD<6:0>
Baud
Set SSPIF, BCLIF;
Reset ACKSTAT, PEN (SSPCON2)
Rate
Generator
SSPM<3:0>
Start bit DetectPIC18F2420/2520/4420/4520
DS39631E-page 186 © 2008 Microchip Technology Inc.
17.4.6.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 the receive bit.
Serial data is received via SDA, while SCL 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 the SPI mode
operation is used to set the SCL clock frequency for
either 100 kHz, 400 kHz or 1 MHz I2C operation. See
Section 17.4.7 “Baud Rate” for more detail.
A typical transmit sequence would go as follows:
1. The user generates a Start condition by setting
the Start Enable bit, SEN (SSPCON2<0>).
2. SSPIF is set. The MSSP module will wait the
required start time before any other operation
takes place.
3. The user loads the SSPBUF with the slave
address to transmit.
4. Address is shifted out the SDA pin until all 8 bits
are transmitted.
5. The MSSP module shifts in the ACK bit from the
slave device and writes its value into the
SSPCON2 register (SSPCON2<6>).
6. The MSSP module generates an interrupt at the
end of the ninth clock cycle by setting the SSPIF
bit.
7. The user loads the SSPBUF with eight bits of
data.
8. Data is shifted out the SDA pin until all 8 bits are
transmitted.
9. The MSSP module shifts in the ACK bit from the
slave device and writes its value into the
SSPCON2 register (SSPCON2<6>).
10. The MSSP module generates an interrupt at the
end of the ninth clock cycle by setting the SSPIF
bit.
11. The user generates a Stop condition by setting
the Stop Enable bit, PEN (SSPCON2<2>).
12. Interrupt is generated once the Stop condition is
complete.© 2008 Microchip Technology Inc. DS39631E-page 187
PIC18F2420/2520/4420/4520
17.4.7 BAUD RATE
In I2C Master mode, the Baud Rate Generator (BRG)
reload value is placed in the lower 7 bits of the
SSPADD register (Figure 17-17). When a write occurs
to SSPBUF, the Baud Rate Generator will automatically
begin counting. The BRG counts down to 0 and stops
until another reload has taken place. The BRG count is
decremented twice per instruction cycle (TCY) on the
Q2 and Q4 clocks. In I2C Master mode, the BRG is
reloaded automatically.
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.
Table 17-3 demonstrates clock rates based on
instruction cycles and the BRG value loaded into
SSPADD.
FIGURE 17-17: BAUD RATE GENERATOR BLOCK DIAGRAM
TABLE 17-3: I2C™ CLOCK RATE W/BRG
SSPM<3:0>
CLKO BRG Down Counter FOSC/4
SSPADD<6:0>
SSPM<3:0>
SCL
Reload
Control
Reload
FCY FCY * 2 BRG Value FSCL
(2 Rollovers of BRG)
10 MHz 20 MHz 18h 400 kHz(1)
10 MHz 20 MHz 1Fh 312.5 kHz
10 MHz 20 MHz 63h 100 kHz
4 MHz 8 MHz 09h 400 kHz(1)
4 MHz 8 MHz 0Ch 308 kHz
4 MHz 8 MHz 27h 100 kHz
1 MHz 2 MHz 02h 333 kHz(1)
1 MHz 2 MHz 09h 100 kHz
1 MHz 2 MHz 00h 1 MHz(1)
Note 1: The I2C interface does not conform to the 400 kHz I2C specification (which applies to rates greater than
100 kHz) in all details, but may be used with care where higher rates are required by the application.PIC18F2420/2520/4420/4520
DS39631E-page 188 © 2008 Microchip Technology Inc.
17.4.7.1 Clock Arbitration
Clock arbitration occurs when the master, during any
receive, transmit or Repeated Start/Stop condition,
deasserts 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 17-18).
FIGURE 17-18: BAUD RATE GENERATOR TIMING WITH CLOCK ARBITRATION
SDA
SCL
SCL deasserted but slave holds
DX DX – 1
BRG
SCL is sampled high, reload takes
place and BRG starts its count
03h 02h 01h 00h (hold off) 03h 02h
Reload
BRG
Value
SCL low (clock arbitration)
SCL allowed to transition high
BRG decrements on
Q2 and Q4 cycles© 2008 Microchip Technology Inc. DS39631E-page 189
PIC18F2420/2520/4420/4520
17.4.8 I2C MASTER MODE START
CONDITION TIMING
To initiate a Start condition, the user sets the Start
Enable bit, SEN (SSPCON2<0>). If the SDA and SCL
pins are sampled high, the Baud Rate Generator is
reloaded with the contents of SSPADD<6:0> and starts
its count. If SCL and SDA are both sampled high when
the Baud Rate Generator times out (TBRG), the SDA
pin is driven low. The action of the SDA being driven
low while SCL is high is the Start condition and causes
the S bit (SSPSTAT<3>) 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 (TBRG), the SEN bit
(SSPCON2<0>) will be automatically cleared by
hardware; the Baud Rate Generator is suspended,
leaving the SDA line held low and the Start condition is
complete.
17.4.8.1 WCOL Status Flag
If the user writes the SSPBUF when a Start sequence
is in progress, the WCOL is set and the contents of the
buffer are unchanged (the write doesn’t occur).
FIGURE 17-19: FIRST START BIT TIMING
Note: If, at the beginning of the Start condition,
the SDA and SCL pins are already sampled
low, or if during the Start condition, the
SCL line is sampled low before the SDA
line 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.
Note: Because queueing of events is not
allowed, writing to the lower 5 bits of
SSPCON2 is disabled until the Start
condition is complete.
SDA
SCL
S
TBRG
1st bit 2nd bit
TBRG
SDA = 1, At completion of Start bit, SCL = 1
TBRG Write to SSPBUF occurs here
hardware clears SEN bit
TBRG
Write to SEN bit occurs here Set S bit (SSPSTAT<3>)
and sets SSPIF bitPIC18F2420/2520/4420/4520
DS39631E-page 190 © 2008 Microchip Technology Inc.
17.4.9 I2C MASTER MODE REPEATED
START CONDITION TIMING
A Repeated Start condition occurs when the RSEN bit
(SSPCON2<1>) 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 deasserted (brought high). When SCL is sampled
high, the Baud Rate Generator is reloaded with the
contents of SSPADD<6:0> and begins counting. SDA
and SCL must be sampled high for one TBRG. This
action is then followed by assertion of the SDA pin
(SDA = 0) for one TBRG while SCL is high. Following
this, the RSEN bit (SSPCON2<1>) will be automatically
cleared and the Baud Rate Generator will not be
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<3>) will be set. The SSPIF bit will
not be set until the Baud Rate Generator has timed out.
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).
17.4.9.1 WCOL Status Flag
If the user writes the SSPBUF when a Repeated Start
sequence is in progress, the WCOL is set and the
contents of the buffer are unchanged (the write doesn’t
occur).
FIGURE 17-20: REPEATED START CONDITION WAVEFORM
Note 1: If RSEN is programmed while any other
event is in progress, it will not take effect.
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’.
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.
SDA
SCL
Sr = Repeated Start
Write to SSPCON2
Write to SSPBUF occurs here on falling edge of ninth clock,
end of Xmit
At completion of Start bit,
hardware clears RSEN bit
1st bit
S bit set by hardware
TBRG
TBRG
SDA = 1,
SDA = 1,
SCL (no change).
SCL = 1 occurs here.
TBRG TBRG TBRG
and sets SSPIF
RSEN bit set by hardware© 2008 Microchip Technology Inc. DS39631E-page 191
PIC18F2420/2520/4420/4520
17.4.10 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 the 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). SCL is held low for one Baud Rate
Generator rollover count (TBRG). Data should be valid
before SCL is released high (see data setup time specification
parameter 107). When the SCL pin is released
high, it is held that way for TBRG. 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 flag is cleared and the master releases SDA.
This allows the slave device being addressed to
respond with an ACK bit during the ninth bit time if an
address match occurred, 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 SCL low and SDA
unchanged (Figure 17-21).
After the write to the SSPBUF, each bit of the 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
deassert 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<6>). 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.
17.4.10.1 BF Status Flag
In Transmit mode, the BF bit (SSPSTAT<0>) is set
when the CPU writes to SSPBUF and is cleared when
all 8 bits are shifted out.
17.4.10.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), the WCOL is set and the contents of the
buffer are unchanged (the write doesn’t occur).
WCOL must be cleared in software.
17.4.10.3 ACKSTAT Status Flag
In Transmit mode, the ACKSTAT bit (SSPCON2<6>) 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.
17.4.11 I2C MASTER MODE RECEPTION
Master mode reception is enabled by programming the
Receive Enable bit, RCEN (SSPCON2<3>).
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<4>).
17.4.11.1 BF Status Flag
In receive operation, 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.
17.4.11.2 SSPOV Status Flag
In receive operation, 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.
17.4.11.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), the WCOL bit is set and the contents of the buffer
are unchanged (the write doesn’t occur).
Note: The MSSP module must be in an Idle state
before the RCEN bit is set or the RCEN bit
will be disregarded. PIC18F2420/2520/4420/4520
DS39631E-page 192 © 2008 Microchip Technology Inc.
FIGURE 17-21: I2C MASTER MODE WAVEFORM (TRANSMISSION, 7 OR 10-BIT ADDRESSING) SDA SCL SSPIF BF (SSPSTAT<0>) SEN A7 A6 A5 A4 A3 A2 A1 ACK = ‘0’ D7 D6 D5 D4 D3 D2 D1 D0 ACK Transmitting Data or Second Half R/W = 0 Transmit Address to Slave 123456789 123456789 P Cleared in software service routine from MSSP interrupt SSPBUF is written in software After Start condition, SEN cleared by hardware
S
SSPBUF written with 7-bit address and R/W
start transmit
SCL held low
while CPU
responds to SSPIF
SEN = 0
of 10-Bit Address
Write SSPCON2<0> SEN = 1
Start condition begins From slave, clear ACKSTAT bit SSPCON2<6>
ACKSTAT in
SSPCON2 = 1
Cleared in software
SSPBUF written
PEN
R/W
Cleared in software© 2008 Microchip Technology Inc. DS39631E-page 193
PIC18F2420/2520/4420/4520
FIGURE 17-22: I2C MASTER MODE WAVEFORM (RECEPTION, 7-BIT ADDRESSING)
P 9 8 7 6 5
D0 D1 D2 D3 D4 D5 D6 D7
S
A7 A6 A5 A4 A3 A2 A1 SDA
SCL 1 2 3 4 5 6 7 8 9 1 2 3 4 5 678 9 1234
Bus master
terminates
transfer
ACK
Receiving Data from Slave Receiving Data from Slave
D0 D1 D2 D3 D4 D5 D6 D7 ACK
R/W = 0 Transmit Address to Slave
SSPIF
BF
ACK is not sent
Write to SSPCON2<0> (SEN = 1),
Write to SSPBUF occurs here, ACK from Slave
Master configured as a receiver
by programming SSPCON2<3> (RCEN = 1)
PEN bit = 1
written here
Data shifted in on falling edge of CLK
Cleared in software
start XMIT
SEN = 0
SSPOV
SDA = 0, SCL = 1
while CPU
(SSPSTAT<0>)
ACK
Cleared in software Cleared in software
Set SSPIF interrupt
at end of receive
Set P bit
(SSPSTAT<4>)
and SSPIF
Cleared in
software
ACK from Master
Set SSPIF at end
Set SSPIF interrupt
at end of Acknowledge
sequence
Set SSPIF interrupt
at end of Acknowledge
sequence
of receive
Set ACKEN, start Acknowledge sequence
SSPOV is set because
SSPBUF is still full
SDA = ACKDT = 1
RCEN cleared
automatically
RCEN = 1, start
next receive
Write to SSPCON2<4>
to start Acknowledge sequence
SDA = ACKDT (SSPCON2<5>) = 0
RCEN cleared
automatically
responds to SSPIF
ACKEN
begin Start condition
Cleared in software
SDA = ACKDT = 0
Last bit is shifted into SSPSR and
contents are unloaded into SSPBUFPIC18F2420/2520/4420/4520
DS39631E-page 194 © 2008 Microchip Technology Inc.
17.4.12 ACKNOWLEDGE SEQUENCE
TIMING
An Acknowledge sequence is enabled by setting the
Acknowledge Sequence Enable bit, ACKEN
(SSPCON2<4>). When this bit is set, the SCL pin is
pulled low and the contents of the Acknowledge data bit
are 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 (TBRG)
and the SCL pin is deasserted (pulled high). When the
SCL pin is sampled high (clock arbitration), the Baud
Rate Generator counts for TBRG. 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 17-23).
17.4.12.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).
17.4.13 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<2>). At the end of a receive/
transmit, the SCL line 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
TBRG (Baud Rate Generator rollover count) later, the
SDA pin will be deasserted. When the SDA pin is
sampled high while SCL is high, the P bit
(SSPSTAT<4>) is set. A TBRG later, the PEN bit is
cleared and the SSPIF bit is set (Figure 17-24).
17.4.13.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 17-23: ACKNOWLEDGE SEQUENCE WAVEFORM
FIGURE 17-24: STOP CONDITION RECEIVE OR TRANSMIT MODE
Note: TBRG = one Baud Rate Generator period.
SDA
SCL
SSPIF set at
Acknowledge sequence starts here,
write to SSPCON2 ACKEN automatically cleared
Cleared in
TBRG TBRG
the end of receive
8
ACKEN = 1, ACKDT = 0
D0
9
SSPIF
software SSPIF set at the end
of Acknowledge sequence
Cleared in
software
ACK
SCL
SDA
SDA asserted low before rising edge of clock
Write to SSPCON2,
set PEN
Falling edge of
SCL = 1 for TBRG, followed by SDA = 1 for TBRG
9th clock
SCL brought high after TBRG
Note: TBRG = one Baud Rate Generator period.
TBRG TBRG
after SDA sampled high. P bit (SSPSTAT<4>) is set.
TBRG
to setup Stop condition
ACK
P
TBRG
PEN bit (SSPCON2<2>) is cleared by
hardware and the SSPIF bit is set© 2008 Microchip Technology Inc. DS39631E-page 195
PIC18F2420/2520/4420/4520
17.4.14 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 MSSP interrupt is enabled).
17.4.15 EFFECTS OF A RESET
A Reset disables the MSSP module and terminates the
current transfer.
17.4.16 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 I2C 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 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:
• Address Transfer
• Data Transfer
• A Start Condition
• A Repeated Start Condition
• An Acknowledge Condition
17.4.17 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 17-25).
If a transmit was in progress when the bus collision
occurred, the transmission is halted, the BF flag is
cleared, the SDA and SCL lines are deasserted 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 deasserted
and the respective control bits in the SSPCON2
register are cleared. 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.
The master will continue to monitor the SDA and SCL
pins. 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 the 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 I2C 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 17-25: BUS COLLISION TIMING FOR TRANSMIT AND ACKNOWLEDGE
SDA
SCL
BCLIF
SDA released
SDA line pulled low
by another source
Sample SDA. While SCL is high,
data doesn’t match what is driven
Bus collision has occurred.
Set bus collision
interrupt (BCLIF)
by the master.
by master
Data changes
while SCL = 0PIC18F2420/2520/4420/4520
DS39631E-page 196 © 2008 Microchip Technology Inc.
17.4.17.1 Bus Collision During a Start
Condition
During a Start condition, a bus collision occurs if:
a) SDA or SCL is sampled low at the beginning of
the Start condition (Figure 17-26).
b) SCL is sampled low before SDA is asserted low
(Figure 17-27).
During a Start condition, both the SDA and the SCL
pins are monitored.
If the SDA pin is already low, or the SCL pin is already
low, then all of the following occur:
• the Start condition is aborted,
• the BCLIF flag is set and
• the MSSP module is reset to its Idle state
(Figure 17-26).
The Start condition begins with the SDA and SCL pins
deasserted. When the SDA pin is sampled high, the
Baud Rate Generator is loaded from SSPADD<6:0>
and counts down to 0. 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 17-28). 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 0; if the SCL pin is sampled as ‘0’
during this time, a bus collision does not occur. At the
end of the BRG count, the SCL pin is asserted low.
FIGURE 17-26: BUS COLLISION DURING START CONDITION (SDA ONLY)
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. If the address is
the same, arbitration must be allowed to
continue into the data portion, Repeated
Start or Stop conditions.
SDA
SCL
SEN
SDA sampled low before
SDA goes low before the SEN bit is set.
S bit and SSPIF set because
MSSP module reset into Idle state.
SEN cleared automatically because of bus collision.
S bit and SSPIF set because
Set SEN, enable Start
condition if SDA = 1, SCL = 1
SDA = 0, SCL = 1.
BCLIF
S
SSPIF
SDA = 0, SCL = 1.
SSPIF and BCLIF are
cleared in software
SSPIF and BCLIF are
cleared in software
Set BCLIF,
Start condition. Set BCLIF.© 2008 Microchip Technology Inc. DS39631E-page 197
PIC18F2420/2520/4420/4520
FIGURE 17-27: BUS COLLISION DURING START CONDITION (SCL = 0)
FIGURE 17-28: BRG RESET DUE TO SDA ARBITRATION DURING START CONDITION
SDA
SCL
SEN bus collision occurs. Set BCLIF.
SCL = 0 before SDA = 0,
Set SEN, enable Start
sequence if SDA = 1, SCL = 1
TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
Interrupt cleared
in software
bus collision occurs. Set BCLIF.
SCL = 0 before BRG time-out,
‘0’ ‘0’
‘0’ ‘0’
SDA
SCL
SEN
Set S
Less than TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
S
Interrupts cleared
set SSPIF in software
SDA = 0, SCL = 1,
SCL pulled low after BRG
time-out
Set SSPIF
‘0’
SDA pulled low by other master.
Reset BRG and assert SDA.
Set SEN, enable Start
sequence if SDA = 1, SCL = 1PIC18F2420/2520/4420/4520
DS39631E-page 198 © 2008 Microchip Technology Inc.
17.4.17.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 deasserts 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 deasserted 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’, Figure 17-29).
If SDA is sampled high, the BRG is reloaded and begins
counting. If SDA 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.
If SCL goes from high-to-low before the BRG times out
and SDA has not already been asserted, a bus collision
occurs. In this case, another master is attempting to
transmit a data ‘1’ during the Repeated Start condition,
see Figure 17-30.
If, at the end of the BRG time-out, both SCL and SDA
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 17-29: BUS COLLISION DURING A REPEATED START CONDITION (CASE 1)
FIGURE 17-30: BUS COLLISION DURING REPEATED START CONDITION (CASE 2)
SDA
SCL
RSEN
BCLIF
S
SSPIF
Sample SDA when SCL goes high.
If SDA = 0, set BCLIF and release SDA and SCL.
Cleared in software
‘0’
‘0’
SDA
SCL
BCLIF
RSEN
S
SSPIF
Interrupt cleared
in software
SCL goes low before SDA,
set BCLIF. Release SDA and SCL.
TBRG TBRG
‘0’© 2008 Microchip Technology Inc. DS39631E-page 199
PIC18F2420/2520/4420/4520
17.4.17.3 Bus Collision During a Stop
Condition
Bus collision occurs during a Stop condition if:
a) After the SDA pin has been deasserted and
allowed to float high, SDA is sampled low after
the BRG has timed out.
b) After the SCL pin is deasserted, 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 allowed 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 17-31). 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 17-32).
FIGURE 17-31: BUS COLLISION DURING A STOP CONDITION (CASE 1)
FIGURE 17-32: BUS COLLISION DURING A STOP CONDITION (CASE 2)
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
SDA asserted low
SDA sampled
low after TBRG,
set BCLIF
‘0’
‘0’
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
Assert SDA SCL goes low before SDA goes high,
set BCLIF
‘0’
‘0’PIC18F2420/2520/4420/4520
DS39631E-page 200 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 201
PIC18F2420/2520/4420/4520
18.0 ENHANCED UNIVERSAL
SYNCHRONOUS
ASYNCHRONOUS RECEIVER
TRANSMITTER (EUSART)
The Enhanced Universal Synchronous Asynchronous
Receiver Transmitter (EUSART) module is one of the
two serial I/O modules. (Generically, the USART is also
known as a Serial Communications Interface or SCI.)
The EUSART can be configured as a full-duplex
asynchronous system that can communicate with
peripheral devices, such as CRT terminals and
personal computers. It can also be configured as a halfduplex,
synchronous system that can communicate
with peripheral devices, such as A/D or D/A integrated
circuits, serial EEPROMs, etc.
The Enhanced USART module implements additional
features, including automatic baud rate detection and
calibration, automatic wake-up on Sync Break reception
and 12-bit Break character transmit. These make it
ideally suited for use in Local Interconnect Network bus
(LIN bus) systems.
The EUSART can be configured in the following
modes:
• Asynchronous (full duplex) with:
- Auto-wake-up on character reception
- Auto-baud calibration
- 12-bit Break character transmission
• Synchronous – Master (half duplex) with
selectable clock polarity
• Synchronous – Slave (half duplex) with selectable
clock polarity
The pins of the Enhanced USART are multiplexed
with PORTC. In order to configure RC6/TX/CK and
RC7/RX/DT as an EUSART:
• bit SPEN (RCSTA<7>) must be set (= 1)
• bit TRISC<7> must be set (= 1)
• bit TRISC<6> must be set (= 1)
The operation of the Enhanced USART module is
controlled through three registers:
• Transmit Status and Control (TXSTA)
• Receive Status and Control (RCSTA)
• Baud Rate Control (BAUDCON)
These are detailed on the following pages in
Register 18-1, Register 18-2 and Register 18-3,
respectively.
Note: The EUSART control will automatically
reconfigure the pin from input to output as
needed.PIC18F2420/2520/4420/4520
DS39631E-page 202 © 2008 Microchip Technology Inc.
REGISTER 18-1: TXSTA: TRANSMIT STATUS AND CONTROL REGISTER
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-1 R/W-0
CSRC TX9 TXEN(1) SYNC SENDB BRGH TRMT TX9D
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 CSRC: Clock Source Select bit
Asynchronous mode:
Don’t care.
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)
1 = Transmit enabled
0 = Transmit disabled
bit 4 SYNC: EUSART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
bit 3 SENDB: Send Break Character bit
Asynchronous mode:
1 = Send Sync Break on next transmission (cleared by hardware upon completion)
0 = Sync Break transmission completed
Synchronous mode:
Don’t care.
bit 2 BRGH: High Baud Rate Select bit
Asynchronous mode:
1 = High speed
0 = Low speed
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
Can be address/data bit or a parity bit.
Note 1: SREN/CREN overrides TXEN in Sync mode.© 2008 Microchip Technology Inc. DS39631E-page 203
PIC18F2420/2520/4420/4520
REGISTER 18-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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 SPEN: Serial Port Enable bit
1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled (held in Reset)
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
Asynchronous mode:
Don’t care.
Synchronous mode – Master:
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception is complete.
Synchronous mode – Slave:
Don’t care.
bit 4 CREN: Continuous Receive Enable bit
Asynchronous mode:
1 = Enables receiver
0 = Disables receiver
Synchronous mode:
1 = Enables continuous receive until enable bit, CREN, is cleared (CREN overrides SREN)
0 = Disables continuous receive
bit 3 ADDEN: Address Detect Enable bit
Asynchronous mode 9-Bit (RX9 = 1):
1 = Enables address detection, enables interrupt and loads 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
Asynchronous mode 9-Bit (RX9 = 0):
Don’t care.
bit 2 FERR: Framing Error bit
1 = Framing error (can be cleared by reading RCREG register and receiving 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
This can be address/data bit or a parity bit and must be calculated by user firmware.PIC18F2420/2520/4420/4520
DS39631E-page 204 © 2008 Microchip Technology Inc.
REGISTER 18-3: BAUDCON: BAUD RATE CONTROL REGISTER
R/W-0 R-1 R/W-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0
ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 ABDOVF: Auto-Baud Acquisition Rollover Status bit
1 = A BRG rollover has occurred during Auto-Baud Rate Detect mode (must be cleared in software)
0 = No BRG rollover has occurred
bit 6 RCIDL: Receive Operation Idle Status bit
1 = Receive operation is Idle
0 = Receive operation is active
bit 5 RXDTP: Data/Receive Polarity Select bit
Asynchronous mode:
1 = Receive data (RX) is inverted (active-low)
0 = Receive data (RX) is not inverted (active-high)
Synchronous mode:
1 = Data (DT) is inverted (active-low)
0 = Data (DT) is not inverted (active-high)
bit 4 TXCKP: Clock and Data Polarity Select bit
Asynchronous mode:
1 = Idle state for transmit (TX) is a low level
0 = Idle state for transmit (TX) is a high level
Synchronous mode:
1 = Idle state for clock (CK) is a high level
0 = Idle state for clock (CK) is a low level
bit 3 BRG16: 16-Bit Baud Rate Register Enable bit
1 = 16-bit Baud Rate Generator – SPBRGH and SPBRG
0 = 8-bit Baud Rate Generator – SPBRG only (Compatible mode), SPBRGH value ignored
bit 2 Unimplemented: Read as ‘0’
bit 1 WUE: Wake-up Enable bit
Asynchronous mode:
1 = EUSART will continue to sample the RX pin – interrupt generated on falling edge; bit cleared in
hardware on following rising edge
0 = RX pin not monitored or rising edge detected
Synchronous mode:
Unused in this mode.
bit 0 ABDEN: Auto-Baud Detect Enable bit
Asynchronous mode:
1 = Enable baud rate measurement on the next character. Requires reception of a Sync field (55h);
cleared in hardware upon completion.
0 = Baud rate measurement disabled or completed
Synchronous mode:
Unused in this mode.© 2008 Microchip Technology Inc. DS39631E-page 205
PIC18F2420/2520/4420/4520
18.1 Baud Rate Generator (BRG)
The BRG is a dedicated, 8-bit or 16-bit generator that
supports both the Asynchronous and Synchronous
modes of the EUSART. By default, the BRG operates
in 8-bit mode; setting the BRG16 bit (BAUDCON<3>)
selects 16-bit mode.
The SPBRGH:SPBRG register pair controls the period
of a free-running timer. In Asynchronous mode, bits,
BRGH (TXSTA<2>) and BRG16 (BAUDCON<3>), also
control the baud rate. In Synchronous mode, BRGH is
ignored. Table 18-1 shows the formula for computation
of the baud rate for different EUSART modes which
only apply in Master mode (internally generated clock).
Given the desired baud rate and FOSC, the nearest
integer value for the SPBRGH:SPBRG registers can be
calculated using the formulas in Table 18-1. From this,
the error in baud rate can be determined. An example
calculation is shown in Example 18-1. Typical baud
rates and error values for the various Asynchronous
modes are shown in Table 18-2. It may be
advantageous to use the high baud rate (BRGH = 1) or
the 16-bit BRG to reduce the baud rate error, or
achieve a slow baud rate for a fast oscillator frequency.
Writing a new value to the SPBRGH:SPBRG registers
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.
18.1.1 OPERATION IN POWER-MANAGED
MODES
The device clock is used to generate the desired baud
rate. When one of the power-managed modes is
entered, the new clock source may be operating at a
different frequency. This may require an adjustment to
the value in the SPBRG register pair.
18.1.2 SAMPLING
The data on the RX 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.
TABLE 18-1: BAUD RATE FORMULAS
Configuration Bits BRG/EUSART Mode Baud Rate Formula
SYNC BRG16 BRGH
000 8-Bit/Asynchronous FOSC/[64 (n + 1)]
001 8-Bit/Asynchronous FOSC/[16 (n + 1)] 010 16-Bit/Asynchronous
011 16-Bit/Asynchronous
10x 8-Bit/Synchronous FOSC/[4 (n + 1)]
11x 16-Bit/Synchronous
Legend: x = Don’t care, n = value of SPBRGH:SPBRG register pairPIC18F2420/2520/4420/4520
DS39631E-page 206 © 2008 Microchip Technology Inc.
EXAMPLE 18-1: CALCULATING BAUD RATE ERROR
TABLE 18-2: REGISTERS ASSOCIATED WITH BAUD RATE GENERATOR
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Reset Values
on page
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by the BRG.
For a device with FOSC of 16 MHz, desired baud rate of 9600, Asynchronous mode, 8-bit BRG:
Desired Baud Rate = FOSC/(64 ([SPBRGH:SPBRG] + 1))
Solving for SPBRGH:SPBRG:
X = ((FOSC/Desired Baud Rate)/64) – 1
= ((16000000/9600)/64) – 1
= [25.042] = 25
Calculated Baud Rate = 16000000/(64 (25 + 1))
= 9615
Error = (Calculated Baud Rate – Desired Baud Rate)/Desired Baud Rate
= (9615 – 9600)/9600 = 0.16% © 2008 Microchip Technology Inc. DS39631E-page 207
PIC18F2420/2520/4420/4520
TABLE 18-3: BAUD RATES FOR ASYNCHRONOUS MODES
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 0
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 — — — — — — — — — — — —
1.2 — — — 1.221 1.73 255 1.202 0.16 129 1.201 -0.16 103
2.4 2.441 1.73 255 2.404 0.16 129 2.404 0.16 64 2.403 -0.16 51
9.6 9.615 0.16 64 9.766 1.73 31 9.766 1.73 15 9.615 -0.16 12
19.2 19.531 1.73 31 19.531 1.73 15 19.531 1.73 7 — — —
57.6 56.818 -1.36 10 62.500 8.51 4 52.083 -9.58 2 — — —
115.2 125.000 8.51 4 104.167 -9.58 2 78.125 -32.18 1 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 0
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 0.300 0.16 207 0.300 -0.16 103 0.300 -0.16 51
1.2 1.202 0.16 51 1.201 -0.16 25 1.201 -0.16 12
2.4 2.404 0.16 25 2.403 -0.16 12 — — —
9.6 8.929 -6.99 6 — — — — — —
19.2 20.833 8.51 2 — — — — — —
57.6 62.500 8.51 0 — — — — — —
115.2 62.500 -45.75 0 — — — — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 0
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 — — — — — — — — — — — —
1.2 — — — — — — — — — — — —
2.4 — — — — — — 2.441 1.73 255 2.403 -0.16 207
9.6 9.766 1.73 255 9.615 0.16 129 9.615 0.16 64 9.615 -0.16 51
19.2 19.231 0.16 129 19.231 0.16 64 19.531 1.73 31 19.230 -0.16 25
57.6 58.140 0.94 42 56.818 -1.36 21 56.818 -1.36 10 55.555 3.55 8
115.2 113.636 -1.36 21 113.636 -1.36 10 125.000 8.51 4 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 0
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 — — — — — — 0.300 -0.16 207
1.2 1.202 0.16 207 1.201 -0.16 103 1.201 -0.16 51
2.4 2.404 0.16 103 2.403 -0.16 51 2.403 -0.16 25
9.6 9.615 0.16 25 9.615 -0.16 12 — — —
19.2 19.231 0.16 12 — — — — — —
57.6 62.500 8.51 3 — — — — — —
115.2 125.000 8.51 1 — — — — — —PIC18F2420/2520/4420/4520
DS39631E-page 208 © 2008 Microchip Technology Inc.
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 1
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 0.300 0.00 8332 0.300 0.02 4165 0.300 0.02 2082 0.300 -0.04 1665
1.2 1.200 0.02 2082 1.200 -0.03 1041 1.200 -0.03 520 1.201 -0.16 415
2.4 2.402 0.06 1040 2.399 -0.03 520 2.404 0.16 259 2.403 -0.16 207
9.6 9.615 0.16 259 9.615 0.16 129 9.615 0.16 64 9.615 -0.16 51
19.2 19.231 0.16 129 19.231 0.16 64 19.531 1.73 31 19.230 -0.16 25
57.6 58.140 0.94 42 56.818 -1.36 21 56.818 -1.36 10 55.555 3.55 8
115.2 113.636 -1.36 21 113.636 -1.36 10 125.000 8.51 4 — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 0, BRG16 = 1
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 0.300 0.04 832 0.300 -0.16 415 0.300 -0.16 207
1.2 1.202 0.16 207 1.201 -0.16 103 1.201 -0.16 51
2.4 2.404 0.16 103 2.403 -0.16 51 2.403 -0.16 25
9.6 9.615 0.16 25 9.615 -0.16 12 — — —
19.2 19.231 0.16 12 — — — — — —
57.6 62.500 8.51 3 — — — — — —
115.2 125.000 8.51 1 — — — — — —
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 1 or SYNC = 1, BRG16 = 1
FOSC = 40.000 MHz FOSC = 20.000 MHz FOSC = 10.000 MHz FOSC = 8.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 0.300 0.00 33332 0.300 0.00 16665 0.300 0.00 8332 0.300 -0.01 6665
1.2 1.200 0.00 8332 1.200 0.02 4165 1.200 0.02 2082 1.200 -0.04 1665
2.4 2.400 0.02 4165 2.400 0.02 2082 2.402 0.06 1040 2.400 -0.04 832
9.6 9.606 0.06 1040 9.596 -0.03 520 9.615 0.16 259 9.615 -0.16 207
19.2 19.193 -0.03 520 19.231 0.16 259 19.231 0.16 129 19.230 -0.16 103
57.6 57.803 0.35 172 57.471 -0.22 86 58.140 0.94 42 57.142 0.79 34
115.2 114.943 -0.22 86 116.279 0.94 42 113.636 -1.36 21 117.647 -2.12 16
BAUD
RATE
(K)
SYNC = 0, BRGH = 1, BRG16 = 1 or SYNC = 1, BRG16 = 1
FOSC = 4.000 MHz FOSC = 2.000 MHz FOSC = 1.000 MHz
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
Actual
Rate
(K)
%
Error
SPBRG
Value
(decimal)
0.3 0.300 0.01 3332 0.300 -0.04 1665 0.300 -0.04 832
1.2 1.200 0.04 832 1.201 -0.16 415 1.201 -0.16 207
2.4 2.404 0.16 415 2.403 -0.16 207 2.403 -0.16 103
9.6 9.615 0.16 103 9.615 -0.16 51 9.615 -0.16 25
19.2 19.231 0.16 51 19.230 -0.16 25 19.230 -0.16 12
57.6 58.824 2.12 16 55.555 3.55 8 — — —
115.2 111.111 -3.55 8 — — — — — —
TABLE 18-3: BAUD RATES FOR ASYNCHRONOUS MODES (CONTINUED)© 2008 Microchip Technology Inc. DS39631E-page 209
PIC18F2420/2520/4420/4520
18.1.3 AUTO-BAUD RATE DETECT
The Enhanced USART module supports the automatic
detection and calibration of baud rate. This feature is
active only in Asynchronous mode and while the WUE
bit is clear.
The automatic baud rate measurement sequence
(Figure 18-1) begins whenever a Start bit is received
and the ABDEN bit is set. The calculation is
self-averaging.
In the Auto-Baud Rate Detect (ABD) mode, the clock to
the BRG is reversed. Rather than the BRG clocking the
incoming RX signal, the RX signal is timing the BRG. In
ABD mode, the internal Baud Rate Generator is used
as a counter to time the bit period of the incoming serial
byte stream.
Once the ABDEN bit is set, the state machine will clear
the BRG and look for a Start bit. The Auto-Baud Rate
Detect must receive a byte with the value 55h (ASCII
“U”, which is also the LIN bus Sync character) in order to
calculate the proper bit rate. The measurement is taken
over both a low and a high bit time in order to minimize
any effects caused by asymmetry of the incoming signal.
After a Start bit, the SPBRG begins counting up, using
the preselected clock source on the first rising edge of
RX. After eight bits on the RX pin or the fifth rising edge,
an accumulated value totalling the proper BRG period is
left in the SPBRGH:SPBRG register pair. Once the 5th
edge is seen (this should correspond to the Stop bit), the
ABDEN bit is automatically cleared.
If a rollover of the BRG occurs (an overflow from FFFFh
to 0000h), the event is trapped by the ABDOVF status
bit (BAUDCON<7>). It is set in hardware by BRG rollovers
and can be set or cleared by the user in software.
ABD mode remains active after rollover events and the
ABDEN bit remains set (Figure 18-2).
While calibrating the baud rate period, the BRG registers
are clocked at 1/8th the preconfigured clock rate.
Note that the BRG clock will be configured by the
BRG16 and BRGH bits. Independent of the BRG16 bit
setting, both the SPBRG and SPBRGH will be used as
a 16-bit counter. This allows the user to verify that no
carry occurred for 8-bit modes by checking for 00h in
the SPBRGH register. Refer to Table 18-4 for counter
clock rates to the BRG.
While the ABD sequence takes place, the EUSART
state machine is held in Idle. The RCIF interrupt is set
once the fifth rising edge on RX is detected. The value
in the RCREG needs to be read to clear the RCIF
interrupt. The contents of RCREG should be discarded.
TABLE 18-4: BRG COUNTER
CLOCK RATES
18.1.3.1 ABD and EUSART Transmission
Since the BRG clock is reversed during ABD acquisition,
the EUSART transmitter cannot be used during
ABD. This means that whenever the ABDEN bit is set,
TXREG cannot be written to. Users should also ensure
that ABDEN does not become set during a transmit
sequence. Failing to do this may result in unpredictable
EUSART operation.
Note 1: If the WUE bit is set with the ABDEN bit,
Auto-Baud Rate Detection will occur on
the byte following the Break character.
2: It is up to the user to determine that the
incoming character baud rate is within the
range of the selected BRG clock source.
Some combinations of oscillator frequency
and EUSART baud rates are not possible
due to bit error rates. Overall system timing
and communication baud rates must
be taken into consideration when using the
Auto-Baud Rate Detection feature.
BRG16 BRGH BRG Counter Clock
0 0 FOSC/512
0 1 FOSC/128
1 0 FOSC/128
1 1 FOSC/32
Note: During the ABD sequence, SPBRG and
SPBRGH are both used as a 16-bit counter,
independent of BRG16 setting.PIC18F2420/2520/4420/4520
DS39631E-page 210 © 2008 Microchip Technology Inc.
FIGURE 18-1: AUTOMATIC BAUD RATE CALCULATION
FIGURE 18-2: BRG OVERFLOW SEQUENCE
BRG Value
RX pin
ABDEN bit
RCIF bit
Bit 0 Bit 1
(Interrupt)
Read
RCREG
BRG Clock
Start
Set by User Auto-Cleared
XXXXh 0000h
Edge #1
Bit 2 Bit 3
Edge #2
Bit 4 Bit 5
Edge #3
Bit 6 Bit 7
Edge #4
Stop Bit
Edge #5
001Ch
Note: The ABD sequence requires the EUSART module to be configured in Asynchronous mode and WUE = 0.
SPBRG XXXXh 1Ch
SPBRGH XXXXh 00h
Start Bit 0
XXXXh 0000h 0000h
FFFFh
BRG Clock
ABDEN bit
RX pin
ABDOVF bit
BRG Value© 2008 Microchip Technology Inc. DS39631E-page 211
PIC18F2420/2520/4420/4520
18.2 EUSART Asynchronous Mode
The Asynchronous mode of operation is selected by
clearing the SYNC bit (TXSTA<4>). In this mode, the
EUSART uses standard Non-Return-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/16-bit Baud Rate Generator can be used
to derive standard baud rate frequencies from the
oscillator.
The EUSART transmits and receives the LSb first. The
EUSART’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
and BRG16 bits (TXSTA<2> and BAUDCON<3>). Parity
is not supported by the hardware but can be
implemented in software and stored as the 9th data bit.
When operating in Asynchronous mode, the EUSART
module consists of the following important elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
• Auto-Wake-up on Sync Break Character
• 12-Bit Break Character Transmit
• Auto-Baud Rate Detection
18.2.1 EUSART ASYNCHRONOUS
TRANSMITTER
The EUSART transmitter block diagram is shown in
Figure 18-3. The heart of the transmitter is the Transmit
(Serial) Shift Register (TSR). The Shift register obtains
its data from the Read/Write Transmit Buffer register,
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the 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 (PIR1<4>) is set. This interrupt can
be enabled or disabled by setting or clearing the interrupt
enable bit, TXIE (PIE1<4>). TXIF will be set regardless of
the state of TXIE; it cannot be cleared in software. TXIF
is also not cleared immediately upon loading TXREG, but
becomes valid in the second instruction cycle following
the load instruction. Polling TXIF immediately following a
load of TXREG will return invalid results.
While TXIF indicates the status of the TXREG register,
another bit, TRMT (TXSTA<1>), shows the status of
the TSR register. TRMT is a read-only bit which is set
when the TSR 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.
To set up an Asynchronous Transmission:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
bit, SYNC, and setting bit, SPEN.
3. If interrupts are desired, set enable bit, TXIE.
4. If 9-bit transmission is desired, set transmit bit,
TX9. Can be used as address/data bit.
5. Enable the transmission by setting bit, TXEN,
which will also set bit, TXIF.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit, TX9D.
7. Load data to the TXREG register (starts
transmission).
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
FIGURE 18-3: EUSART TRANSMIT BLOCK DIAGRAM
Note 1: The TSR register is not mapped in data
memory so it is not available to the user.
2: Flag bit, TXIF, is set when enable bit,
TXEN, is set.
TXIF
TXIE
Interrupt
TXEN Baud Rate CLK
SPBRG
Baud Rate Generator TX9D
MSb LSb
Data Bus
TXREG Register
TSR Register
(8) 0
TX9
TRMT SPEN
TX pin
Pin Buffer
and Control
8
• • •
BRG16 SPBRGHPIC18F2420/2520/4420/4520
DS39631E-page 212 © 2008 Microchip Technology Inc.
FIGURE 18-4: ASYNCHRONOUS TRANSMISSION
FIGURE 18-5: ASYNCHRONOUS TRANSMISSION (BACK TO BACK)
TABLE 18-5: REGISTERS ASSOCIATED WITH ASYNCHRONOUS TRANSMISSION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
TXREG EUSART Transmit Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented locations read as ‘0’. Shaded cells are not used for asynchronous transmission.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.
Word 1
Word 1
Transmit Shift Reg
Start bit bit 0 bit 1 bit 7/8
Write to TXREG
BRG Output
(Shift Clock)
TX (pin)
TXIF bit
(Transmit Buffer
Reg. Empty Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
1 TCY
Stop bit
Word 1
Transmit Shift Reg.
Write to TXREG
BRG Output
(Shift Clock)
TX (pin)
TXIF bit
(Interrupt Reg. Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
Word 1 Word 2
Word 1 Word 2
Stop bit Start bit
Transmit Shift Reg.
Word 1 Word 2
bit 0 bit 1 bit 7/8 bit 0
Note: This timing diagram shows two consecutive transmissions.
1 TCY
1 TCY
Start bit© 2008 Microchip Technology Inc. DS39631E-page 213
PIC18F2420/2520/4420/4520
18.2.2 EUSART ASYNCHRONOUS
RECEIVER
The receiver block diagram is shown in Figure 18-6.
The data is received on the RX 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.
To set up an Asynchronous Reception:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
bit, SYNC, and setting bit, SPEN.
3. If interrupts are desired, set enable bit, RCIE.
4. If 9-bit reception is desired, set bit, RX9.
5. Enable the reception by setting bit, CREN.
6. Flag bit, RCIF, will be set when reception is
complete and an interrupt will be generated if
enable bit, RCIE, was set.
7. Read the RCSTA register to get the 9th 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
enable bit, CREN.
10. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
18.2.3 SETTING UP 9-BIT MODE WITH
ADDRESS DETECT
This mode would typically be used in RS-485 systems.
To set up an Asynchronous Reception with Address
Detect Enable:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRGH
and BRG16 bits, as required, to achieve the
desired baud rate.
2. Enable the asynchronous serial port by clearing
the SYNC bit and setting the SPEN bit.
3. If interrupts are required, set the RCEN bit and
select the desired priority level with the RCIP bit.
4. Set the RX9 bit to enable 9-bit reception.
5. Set the ADDEN bit to enable address detect.
6. Enable reception by setting the CREN bit.
7. The RCIF bit will be set when reception is
complete. The interrupt will be Acknowledged if
the RCIE and GIE bits are set.
8. Read the RCSTA register to determine if any
error occurred during reception, as well as read
bit 9 of data (if applicable).
9. Read RCREG to determine if the device is being
addressed.
10. If any error occurred, clear the CREN bit.
11. If the device has been addressed, clear the
ADDEN bit to allow all received data into the
receive buffer and interrupt the CPU.
FIGURE 18-6: EUSART RECEIVE BLOCK DIAGRAM
x64 Baud Rate CLK
Baud Rate Generator
RX
Pin Buffer
and Control
SPEN
Data
Recovery
CREN OERR FERR
MSb RSR Register LSb
RX9D RCREG Register
FIFO
Interrupt RCIF
RCIE
Data Bus
8
÷ 64
÷ 16
or
Stop (8) 7 1 0 Start
RX9
• • •
BRG16 SPBRGH SPBRG
or
÷ 4PIC18F2420/2520/4420/4520
DS39631E-page 214 © 2008 Microchip Technology Inc.
FIGURE 18-7: ASYNCHRONOUS RECEPTION
TABLE 18-6: REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION
18.2.4 AUTO-WAKE-UP ON SYNC BREAK
CHARACTER
During Sleep mode, all clocks to the EUSART are
suspended. Because of this, the Baud Rate Generator
is inactive and a proper byte reception cannot be performed.
The auto-wake-up feature allows the controller
to wake-up due to activity on the RX/DT line while the
EUSART is operating in Asynchronous mode.
The auto-wake-up feature is enabled by setting the
WUE bit (BAUDCON<1>). Once set, the typical receive
sequence on RX/DT is disabled and the EUSART
remains in an Idle state, monitoring for a wake-up event
independent of the CPU mode. A wake-up event consists
of a high-to-low transition on the RX/DT line. (This
coincides with the start of a Sync Break or a Wake-up
Signal character for the LIN protocol.)
Following a wake-up event, the module generates an
RCIF interrupt. The interrupt is generated synchronously
to the Q clocks in normal operating modes
(Figure 18-8) and asynchronously, if the device is in
Sleep mode (Figure 18-9). The interrupt condition is
cleared by reading the RCREG register.
The WUE bit is automatically cleared once a low-tohigh
transition is observed on the RX line following the
wake-up event. At this point, the EUSART module is in
Idle mode and returns to normal operation. This signals
to the user that the Sync Break event is over.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
RCREG EUSART Receive Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented locations read as ‘0’. Shaded cells are not used for asynchronous reception.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.
Start
bit bit 0 bit 7/8 bit 1 Stop bit 0 bit 7/8
bit
Start
bit
Start
bit 7/8 Stop bit
bit
RX (pin)
Rcv Buffer Reg
Rcv Shift Reg
Read Rcv
Buffer Reg
RCREG
RCIF
(Interrupt Flag)
OERR bit
CREN
Word 1
RCREG
Word 2
RCREG
Stop
bit
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.© 2008 Microchip Technology Inc. DS39631E-page 215
PIC18F2420/2520/4420/4520
18.2.4.1 Special Considerations Using
Auto-Wake-up
Since auto-wake-up functions by sensing rising edge
transitions on RX/DT, information with any state
changes before the Stop bit may signal a false End-ofCharacter
(EOC) and cause data or framing errors. To
work properly, therefore, the initial character in the
transmission must be all ‘0’s. This can be 00h (8 bytes)
for standard RS-232 devices or 000h (12 bits) for LIN
bus.
Oscillator start-up time must also be considered,
especially in applications using oscillators with longer
start-up intervals (i.e., XT or HS mode). The Sync
Break (or Wake-up Signal) character must be of
sufficient length and be followed by a sufficient interval
to allow enough time for the selected oscillator to start
and provide proper initialization of the EUSART.
18.2.4.2 Special Considerations Using
the WUE Bit
The timing of WUE and RCIF events may cause some
confusion when it comes to determining the validity of
received data. As noted, setting the WUE bit places the
EUSART in an Idle mode. The wake-up event causes a
receive interrupt by setting the RCIF bit. The WUE bit is
cleared after this when a rising edge is seen on RX/DT.
The interrupt condition is then cleared by reading the
RCREG register. Ordinarily, the data in RCREG will be
dummy data and should be discarded.
The fact that the WUE bit has been cleared (or is still
set) and the RCIF flag is set should not be used as an
indicator of the integrity of the data in RCREG. Users
should consider implementing a parallel method in
firmware to verify received data integrity.
To assure that no actual data is lost, check the RCIDL
bit to verify that a receive operation is not in process. If
a receive operation is not occurring, the WUE bit may
then be set just prior to entering the Sleep mode.
FIGURE 18-8: AUTO-WAKE-UP BIT (WUE) TIMINGS DURING NORMAL OPERATION
FIGURE 18-9: AUTO-WAKE-UP BIT (WUE) TIMINGS DURING SLEEP
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
WUE bit(1)
RX/DT Line
RCIF
Note 1: The EUSART remains in Idle while the WUE bit is set.
Bit Set by User
Cleared Due to User Read of RCREG
Auto-Cleared
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
WUE bit(2)
RX/DT Line
RCIF
Bit Set by User
Cleared Due to User Read of RCREG
Sleep Command Executed
Note 1: If the wake-up event requires long oscillator warm-up time, the auto-clear of the WUE bit can occur before the oscillator is ready. This
sequence should not depend on the presence of Q clocks.
2: The EUSART remains in Idle while the WUE bit is set.
Sleep Ends
Note 1
Auto-ClearedPIC18F2420/2520/4420/4520
DS39631E-page 216 © 2008 Microchip Technology Inc.
18.2.5 BREAK CHARACTER SEQUENCE
The EUSART module has the capability of sending the
special Break character sequences that are required by
the LIN bus standard. The Break character transmit
consists of a Start bit, followed by twelve ‘0’ bits and a
Stop bit. The frame Break character is sent whenever
the SENDB and TXEN bits (TXSTA<3> and
TXSTA<5>) are set while the Transmit Shift register is
loaded with data. Note that the value of data written to
TXREG will be ignored and all ‘0’s will be transmitted.
The SENDB bit is automatically reset by hardware after
the corresponding Stop bit is sent. This allows the user
to preload the transmit FIFO with the next transmit byte
following the Break character (typically, the Sync
character in the LIN specification).
Note that the data value written to the TXREG for the
Break character is ignored. The write simply serves the
purpose of initiating the proper sequence.
The TRMT bit indicates when the transmit operation is
active or Idle, just as it does during normal transmission.
See Figure 18-10 for the timing of the Break
character sequence.
18.2.5.1 Break and Sync Transmit Sequence
The following sequence will send a message frame
header made up of a Break, followed by an Auto-Baud
Sync byte. This sequence is typical of a LIN bus
master.
1. Configure the EUSART for the desired mode.
2. Set the TXEN and SENDB bits to set up the
Break character.
3. Load the TXREG with a dummy character to
initiate transmission (the value is ignored).
4. Write ‘55h’ to TXREG to load the Sync character
into the transmit FIFO buffer.
5. After the Break has been sent, the SENDB bit is
reset by hardware. The Sync character now
transmits in the preconfigured mode.
When the TXREG becomes empty, as indicated by the
TXIF, the next data byte can be written to TXREG.
18.2.6 RECEIVING A BREAK CHARACTER
The Enhanced USART module can receive a Break
character in two ways.
The first method forces configuration of the baud rate
at a frequency of 9/13 the typical speed. This allows for
the Stop bit transition to be at the correct sampling location
(13 bits for Break versus Start bit and 8 data bits for
typical data).
The second method uses the auto-wake-up feature
described in Section 18.2.4 “Auto-Wake-up on Sync
Break Character”. By enabling this feature, the
EUSART will sample the next two transitions on RX/DT,
cause an RCIF interrupt and receive the next data byte
followed by another interrupt.
Note that following a Break character, the user will
typically want to enable the Auto-Baud Rate Detect
feature. For both methods, the user can set the ABD bit
once the TXIF interrupt is observed.
FIGURE 18-10: SEND BREAK CHARACTER SEQUENCE
Write to TXREG
BRG Output
(Shift Clock)
Start Bit Bit 0 Bit 1 Bit 11 Stop Bit
Break
TXIF bit
(Transmit Buffer
Reg. Empty Flag)
TX (pin)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
SENDB
(Transmit Shift
Reg. Empty Flag)
SENDB Sampled Here Auto-Cleared
Dummy Write © 2008 Microchip Technology Inc. DS39631E-page 217
PIC18F2420/2520/4420/4520
18.3 EUSART Synchronous
Master Mode
The Synchronous Master mode is entered by setting
the CSRC bit (TXSTA<7>). In this 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 bit,
SYNC (TXSTA<4>). In addition, enable bit, SPEN
(RCSTA<7>), is set in order to configure the TX and RX
pins to CK (clock) and DT (data) lines, respectively.
The Master mode indicates that the processor transmits
the master clock on the CK line. Clock polarity is
selected with the TXCKP bit (BAUDCON<4>); setting
TXCKP sets the Idle state on CK as high, while clearing
the bit sets the Idle state as low. This option is provided
to support Microwire devices with this module.
18.3.1 EUSART SYNCHRONOUS MASTER
TRANSMISSION
The EUSART transmitter block diagram is shown in
Figure 18-3. The heart of the transmitter is the Transmit
(Serial) Shift Register (TSR). The Shift register obtains
its data from the Read/Write Transmit Buffer register,
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the last
bit has been transmitted from the previous load. As
soon as the last bit is transmitted, the TSR is loaded
with new data from the TXREG (if available).
Once the TXREG register transfers the data to the TSR
register (occurs in one TCY), the TXREG is empty and
the TXIF flag bit (PIR1<4>) is set. The interrupt can be
enabled or disabled by setting or clearing the interrupt
enable bit, TXIE (PIE1<4>). TXIF is set regardless of
the state of enable bit, TXIE; it cannot be cleared in
software. It will reset only when new data is loaded into
the TXREG register.
While flag bit, TXIF, indicates the status of the TXREG
register, another bit, TRMT (TXSTA<1>), shows the
status of the TSR register. TRMT is a read-only bit which
is set when the TSR is empty. No interrupt logic is tied to
this bit so the user has to poll this bit in order to determine
if the TSR register is empty. The TSR is not
mapped in data memory so it is not available to the user.
To set up a Synchronous Master Transmission:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRG16
bit, as required, to achieve the desired baud rate.
2. Enable the synchronous master serial port by
setting bits, SYNC, SPEN and CSRC.
3. If interrupts are desired, set enable bit, TXIE.
4. If 9-bit transmission is desired, set bit, TX9.
5. Enable the transmission by setting bit, TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit, TX9D.
7. Start transmission by loading data to the TXREG
register.
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
FIGURE 18-11: SYNCHRONOUS TRANSMISSION
bit 0 bit 1 bit 7
Word 1
Q1 Q2 Q3Q4 Q1 Q2 Q3 Q4 Q1Q2 Q3 Q4 Q1Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3Q4 Q1Q2 Q3Q4 Q1 Q2Q3Q4 Q1 Q2Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
bit 2 bit 0 bit 1 bit 7 RC7/RX/DT
RC6/TX/CK pin
Write to
TXREG Reg
TXIF bit
(Interrupt Flag)
TXEN bit ‘1’ ‘1’
Word 2
TRMT bit
Write Word 1 Write Word 2
Note: Sync Master mode, SPBRG = 0, continuous transmission of two 8-bit words.
RC6/TX/CK pin
(TXCKP = 0)
(TXCKP = 1)PIC18F2420/2520/4420/4520
DS39631E-page 218 © 2008 Microchip Technology Inc.
FIGURE 18-12: SYNCHRONOUS TRANSMISSION (THROUGH TXEN)
TABLE 18-7: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER TRANSMISSION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
TXREG EUSART Transmit Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used for synchronous master transmission.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.
RC7/RX/DT pin
RC6/TX/CK pin
Write to
TXREG reg
TXIF bit
TRMT bit
bit 0 bit 1 bit 2 bit 6 bit 7
TXEN bit© 2008 Microchip Technology Inc. DS39631E-page 219
PIC18F2420/2520/4420/4520
18.3.2 EUSART SYNCHRONOUS
MASTER RECEPTION
Once Synchronous mode is selected, reception is
enabled by setting either the Single Receive Enable bit,
SREN (RCSTA<5>), or the Continuous Receive
Enable bit, CREN (RCSTA<4>). Data is sampled on the
RX pin on the falling edge of the clock.
If enable bit, SREN, is set, only a single word is
received. If enable bit, CREN, is set, the reception is
continuous until CREN is cleared. If both bits are set,
then CREN takes precedence.
To set up a Synchronous Master Reception:
1. Initialize the SPBRGH:SPBRG registers for the
appropriate baud rate. Set or clear the BRG16
bit, as required, to achieve the desired baud rate.
2. Enable the synchronous master serial port by
setting bits, SYNC, SPEN and CSRC.
3. Ensure bits, CREN and SREN, are clear.
4. If interrupts are desired, set enable bit, RCIE.
5. If 9-bit reception is desired, set bit, RX9.
6. If a single reception is required, set bit, SREN.
For continuous reception, set bit, CREN.
7. Interrupt flag bit, RCIF, will be set when reception
is complete and an interrupt will be generated if
the enable bit, RCIE, was set.
8. Read the RCSTA register to get the 9th 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
bit, CREN.
11. If using interrupts, ensure that the GIE and PEIE bits
in the INTCON register (INTCON<7:6>) are set.
FIGURE 18-13: SYNCHRONOUS RECEPTION (MASTER MODE, SREN)
TABLE 18-8: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER RECEPTION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
RCREG EUSART Receive Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used for synchronous master reception.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.
CREN bit
RC7/RX/DT
RC6/TX/CK pin
Write to
bit SREN
SREN bit
RCIF bit
(Interrupt)
Read
RXREG
Q2 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
‘0’
bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7
‘0’
Q1 Q2 Q3 Q4
Note: Timing diagram demonstrates Sync Master mode with bit, SREN = 1, and bit, BRGH = 0.
RC6/TX/CK pin
pin
(TXCKP = 0)
(TXCKP = 1)PIC18F2420/2520/4420/4520
DS39631E-page 220 © 2008 Microchip Technology Inc.
18.4 EUSART Synchronous
Slave Mode
Synchronous Slave mode is entered by clearing bit,
CSRC (TXSTA<7>). This mode differs from the
Synchronous Master mode in that the shift clock is supplied
externally at the CK pin (instead of being supplied
internally in Master mode). This allows the device to
transfer or receive data while in any low-power mode.
18.4.1 EUSART SYNCHRONOUS
SLAVE TRANSMISSION
The operation of the Synchronous Master and Slave
modes is 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 the TXREG
register.
c) Flag bit, TXIF, will not be set.
d) When the first word has been shifted out of TSR,
the TXREG register will transfer the second
word to the TSR and flag bit, TXIF, will now be
set.
e) If enable bit, TXIE, is set, the interrupt will wake
the chip from Sleep. If the global interrupt is
enabled, the program will branch to the interrupt
vector.
To set up a Synchronous Slave Transmission:
1. Enable the synchronous slave serial port by
setting bits, SYNC and SPEN, and clearing bit,
CSRC.
2. Clear bits, CREN and SREN.
3. If interrupts are desired, set enable bit, TXIE.
4. If 9-bit transmission is desired, set bit, TX9.
5. Enable the transmission by setting enable bit,
TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit, TX9D.
7. Start transmission by loading data to the TXREG
register.
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 18-9: REGISTERS ASSOCIATED WITH SYNCHRONOUS SLAVE TRANSMISSION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
TXREG EUSART Transmit Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used for synchronous slave transmission.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.© 2008 Microchip Technology Inc. DS39631E-page 221
PIC18F2420/2520/4420/4520
18.4.2 EUSART SYNCHRONOUS SLAVE
RECEPTION
The operation of the Synchronous Master and Slave
modes is identical, except in the case of Sleep, or any
Idle mode and bit, SREN, which is a “don’t care” in
Slave mode.
If receive is enabled by setting the CREN bit prior to
entering Sleep or any Idle mode, then a word may be
received while in this low-power mode. Once the word
is received, the RSR register will transfer the data to the
RCREG register; if the RCIE enable bit is set, the interrupt
generated will wake the chip from the low-power
mode. If the global interrupt is enabled, the program will
branch to the interrupt vector.
To set up a Synchronous Slave Reception:
1. Enable the synchronous master serial port by
setting bits, SYNC and SPEN, and clearing bit,
CSRC.
2. If interrupts are desired, set enable bit, RCIE.
3. If 9-bit reception is desired, set bit, RX9.
4. To enable reception, set enable bit, CREN.
5. Flag bit, RCIF, will be set when reception is
complete. An interrupt will be generated if
enable bit, RCIE, was set.
6. Read the RCSTA register to get the 9th 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
bit, CREN.
9. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 18-10: REGISTERS ASSOCIATED WITH SYNCHRONOUS SLAVE RECEPTION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 51
RCREG EUSART Receive Register 51
TXSTA CSRC TX9 TXEN SYNC SENDB BRGH TRMT TX9D 51
BAUDCON ABDOVF RCIDL RXDTP TXCKP BRG16 — WUE ABDEN 51
SPBRGH EUSART Baud Rate Generator Register High Byte 51
SPBRG EUSART Baud Rate Generator Register Low Byte 51
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used for synchronous slave reception.
Note 1: Reserved in 28-pin devices; always maintain these bits clear.PIC18F2420/2520/4420/4520
DS39631E-page 222 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 223
PIC18F2420/2520/4420/4520
19.0 10-BIT ANALOG-TO-DIGITAL
CONVERTER (A/D) MODULE
The Analog-to-Digital (A/D) Converter module has
10 inputs for the 28-pin devices and 13 for the 40/44-pin
devices. This module allows conversion of an analog
input signal to a corresponding 10-bit digital number.
The module has five registers:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
• A/D Control Register 0 (ADCON0)
• A/D Control Register 1 (ADCON1)
• A/D Control Register 2 (ADCON2)
The ADCON0 register, shown in Register 19-1,
controls the operation of the A/D module. The
ADCON1 register, shown in Register 19-2, configures
the functions of the port pins. The ADCON2 register,
shown in Register 19-3, configures the A/D clock
source, programmed acquisition time and justification.
REGISTER 19-1: ADCON0: A/D CONTROL REGISTER 0
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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-6 Unimplemented: Read as ‘0’
bit 5-2 CHS<3:0>: Analog Channel Select bits
0000 = Channel 0 (AN0)
0001 = Channel 1 (AN1)
0010 = Channel 2 (AN2)
0011 = Channel 3 (AN3)
0100 = Channel 4 (AN4)
0101 = Channel 5 (AN5)(1,2)
0110 = Channel 6 (AN6)(1,2)
0111 = Channel 7 (AN7)(1,2)
1000 = Channel 8 (AN8)
1001 = Channel 9 (AN9)
1010 = Channel 10 (AN10)
1011 = Channel 11 (AN11)
1100 = Channel 12 (AN12)
1101 = Unimplemented)(2)
1110 = Unimplemented)(2)
1111 = Unimplemented)(2)
bit 1 GO/DONE: A/D Conversion Status bit
When ADON = 1:
1 = A/D conversion in progress
0 = A/D Idle
bit 0 ADON: A/D On bit
1 = A/D Converter module is enabled
0 = A/D Converter module is disabled
Note 1: These channels are not implemented on 28-pin devices.
2: Performing a conversion on unimplemented channels will return a floating input measurement.PIC18F2420/2520/4420/4520
DS39631E-page 224 © 2008 Microchip Technology Inc.
REGISTER 19-2: ADCON1: A/D CONTROL REGISTER 1
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-q(1) R/W-q(1) R/W-q(1)
— — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-6 Unimplemented: Read as ‘0’
bit 5 VCFG1: Voltage Reference Configuration bit (VREF- source)
1 = VREF- (AN2)
0 = VSS
bit 4 VCFG0: Voltage Reference Configuration bit (VREF+ source)
1 = VREF+ (AN3)
0 = VDD
bit 3-0 PCFG<3:0>: A/D Port Configuration Control bits:
Note 1: The POR value of the PCFG bits depends on the value of the PBADEN Configuration bit. When
PBADEN = 1, PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.
2: AN5 through AN7 are available only on 40/44-pin devices.
A = Analog input D = Digital I/O
PCFG3:
PCFG0
AN12
AN11
AN10
AN9
AN8
AN7(2)
AN6(2)
AN5(2)
AN4
AN3
AN2
AN1
AN0
0000(1) A A A A A A A A A AAAA
0001 A A A A A A A A A AAAA
0010 A A A A A A A A A AAAA
0011 D A A A A A A A A AAAA
0100 D D A A A A A A A AAAA
0101 D D D A A A A A A AAAA
0110 D D D D A A A A A AAAA
0111(1) D D D D D A A A A AAAA
1000 D D D D D D A A A AAAA
1001 D D D D D D D A A AAAA
1010 D D D D D D D D A AAAA
1011 D D D D D D D D D AAAA
1100 D D D D D D D D D DAAA
1101 D D D D D D D D D DDAA
1110 D D D D D D D D D DDDA
1111 D D D D D D D D D DDDD© 2008 Microchip Technology Inc. DS39631E-page 225
PIC18F2420/2520/4420/4520
REGISTER 19-3: ADCON2: A/D CONTROL REGISTER 2
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 ADFM: A/D Result Format Select bit
1 = Right justified
0 = Left justified
bit 6 Unimplemented: Read as ‘0’
bit 5-3 ACQT<2:0>: A/D Acquisition Time Select bits
111 = 20 TAD
110 = 16 TAD
101 = 12 TAD
100 = 8 TAD
011 = 6 TAD
010 = 4 TAD
001 = 2 TAD
000 = 0 TAD(1)
bit 2-0 ADCS<2:0>: A/D Conversion Clock Select bits
111 = FRC (clock derived from A/D RC oscillator)(1)
110 = FOSC/64
101 = FOSC/16
100 = FOSC/4
011 = FRC (clock derived from A/D RC oscillator)(1)
010 = FOSC/32
001 = FOSC/8
000 = FOSC/2
Note 1: If the A/D FRC clock source is selected, a delay of one TCY (instruction cycle) is added before the A/D
clock starts. This allows the SLEEP instruction to be executed before starting a conversion.PIC18F2420/2520/4420/4520
DS39631E-page 226 © 2008 Microchip Technology Inc.
The analog reference voltage is software selectable to
either the device’s positive and negative supply voltage
(VDD and VSS), or the voltage level on the RA3/AN3/
VREF+ and RA2/AN2/VREF-/CVREF pins.
The A/D Converter has a unique feature of being able
to operate while the device is in Sleep mode. To operate
in Sleep, the A/D conversion clock must be derived
from the A/D’s internal RC oscillator.
The output of the sample and hold is the input into the
converter, which generates the result via successive
approximation.
A device Reset forces all registers to their Reset state.
This forces the A/D module to be turned off and any
conversion in progress is aborted.
Each port pin associated with the A/D Converter can be
configured as an analog input, or as a digital I/O. The
ADRESH and ADRESL registers contain the result of the
A/D conversion. When the A/D conversion is complete,
the result is loaded into the ADRESH:ADRESL register
pair, the GO/DONE bit (ADCON0 register) is cleared and
the A/D Interrupt Flag bit, ADIF, is set. The block diagram
of the A/D module is shown in Figure 19-1.
FIGURE 19-1: A/D BLOCK DIAGRAM
(Input Voltage)
VAIN
VREF+ Reference
Voltage
VDD(2)
VCFG<1:0>
CHS<3:0>
AN7(1)
AN6(1)
AN5(1)
AN4
AN3
AN2
AN1
AN0
0111
0110
0101
0100
0011
0010
0001
0000
10-Bit
A/D
VREFVSS(2)
Converter
AN12
AN11
AN10
AN9
AN8
1100
1011
1010
1001
1000
Note 1: Channels, AN5 through AN7, are not available on 28-pin devices.
2: I/O pins have diode protection to VDD and VSS.
0X
1X
X1
X0© 2008 Microchip Technology Inc. DS39631E-page 227
PIC18F2420/2520/4420/4520
The value in the ADRESH:ADRESL registers is not
modified for a Power-on Reset. The ADRESH:ADRESL
registers will contain unknown data after a Power-on
Reset.
After the A/D module has been configured as desired,
the selected channel must be acquired before the
conversion is started. The analog input channels must
have their corresponding TRIS bits selected as an
input. To determine acquisition time, see Section 19.1
“A/D Acquisition Requirements”. After this acquisition
time has elapsed, the A/D conversion can be
started. An acquisition time can be programmed to
occur between setting the GO/DONE bit and the actual
start of the conversion.
The following steps should be followed to perform 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 acquisition time (ADCON2)
• Select A/D conversion clock (ADCON2)
• Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired):
• Clear ADIF bit
• Set ADIE bit
• Set GIE bit
3. Wait the required acquisition time (if required).
4. Start conversion:
• Set GO/DONE bit (ADCON0 register)
5. Wait for A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared
OR
• Waiting for the A/D interrupt
6. Read A/D Result registers (ADRESH:ADRESL);
clear bit, ADIF, if required.
7. For next conversion, go to step 1 or step 2, as
required. The A/D conversion time per bit is
defined as TAD. A minimum wait of 2 TAD is
required before the next acquisition starts.
FIGURE 19-2: A/D TRANSFER FUNCTION
FIGURE 19-3: ANALOG INPUT MODEL
Digital Code Output
3FEh
003h
002h
001h
000h
0.5 LSB
1 LSB
1.5 LSB
2 LSB
2.5 LSB
1022 LSB
1022.5 LSB
3 LSB
Analog Input Voltage
3FFh
1023 LSB
1023.5 LSB
VAIN CPIN
Rs ANx
5 pF
VT = 0.6V
VT = 0.6V ILEAKAGE
RIC ≤ 1k
Sampling
Switch
SS RSS
CHOLD = 25 pF
VSS
VDD
±100 nA
Legend: CPIN
VT
ILEAKAGE
RIC
SS
CHOLD
= Input Capacitance
= Threshold Voltage
= Leakage Current at the pin due to
= Interconnect Resistance
= Sampling Switch
= Sample/Hold Capacitance (from DAC)
various junctions
RSS = Sampling Switch Resistance
VDD
6V
Sampling Switch
5V
4V
3V
2V
1 23 4
(kΩ)PIC18F2420/2520/4420/4520
DS39631E-page 228 © 2008 Microchip Technology Inc.
19.1 A/D Acquisition Requirements
For the A/D Converter to meet its specified accuracy,
the charge holding capacitor (CHOLD) must be allowed
to fully charge to the input channel voltage level. The
analog input model is shown in Figure 19-3. The
source impedance (RS) and the internal sampling
switch (RSS) impedance directly affect the time
required to charge the capacitor CHOLD. The sampling
switch (RSS) impedance varies over the device voltage
(VDD). 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Ω. After the analog input channel is
selected (changed), the channel must be sampled for
at least the minimum acquisition time before starting a
conversion.
To calculate the minimum acquisition time,
Equation 19-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.
Example 19-3 shows the calculation of the minimum
required acquisition time TACQ. This calculation is
based on the following application system
assumptions:
CHOLD = 25 pF
Rs = 2.5 kΩ
Conversion Error ≤ 1/2 LSb
VDD = 5V → Rss = 2 kΩ
Temperature = 85°C (system max.)
EQUATION 19-1: ACQUISITION TIME
EQUATION 19-2: A/D MINIMUM CHARGING TIME
EQUATION 19-3: CALCULATING THE MINIMUM REQUIRED ACQUISITION TIME
Note: When the conversion is started, the
holding capacitor is disconnected from the
input pin.
TACQ = Amplifier Settling Time + Holding Capacitor Charging Time + Temperature Coefficient
= TAMP + TC + TCOFF
VHOLD = (VREF – (VREF/2048)) • (1 – e(-TC/CHOLD(RIC + RSS + RS)))
or
TC = -(CHOLD)(RIC + RSS + RS) ln(1/2048)
TACQ =TAMP + TC + TCOFF
TAMP = 0.2 μs
TCOFF = (Temp – 25°C)(0.02 μs/°C)
(85°C – 25°C)(0.02 μs/°C)
1.2 μs
Temperature coefficient is only required for temperatures > 25°C. Below 25°C, TCOFF = 0 μs.
TC = -(CHOLD)(RIC + RSS + RS) ln(1/2047) μs
-(25 pF) (1 kΩ + 2 kΩ + 2.5 kΩ) ln(0.0004883) μs
1.05 μs
TACQ = 0.2 μs + 1 μs + 1.2 μs
2.4 μs© 2008 Microchip Technology Inc. DS39631E-page 229
PIC18F2420/2520/4420/4520
19.2 Selecting and Configuring
Acquisition Time
The ADCON2 register allows the user to select an
acquisition time that occurs each time the GO/DONE
bit is set. It also gives users the option to use an
automatically determined acquisition time.
Acquisition time may be set with the ACQT<2:0> bits
(ADCON2<5:3>), which provides a range of 2 to
20 TAD. When the GO/DONE bit is set, the A/D module
continues to sample the input for the selected acquisition
time, then automatically begins a conversion.
Since the acquisition time is programmed, there may
be no need to wait for an acquisition time between
selecting a channel and setting the GO/DONE bit.
Manual acquisition is selected when
ACQT<2:0> = 000. When the GO/DONE bit is set,
sampling is stopped and a conversion begins. The user
is responsible for ensuring the required acquisition time
has passed between selecting the desired input
channel and setting the GO/DONE bit. This option is
also the default Reset state of the ACQT<2:0> bits and
is compatible with devices that do not offer
programmable acquisition times.
In either case, when the conversion is completed, the
GO/DONE bit is cleared, the ADIF flag is set and the
A/D begins sampling the currently selected channel
again. If an acquisition time is programmed, there is
nothing to indicate if the acquisition time has ended or
if the conversion has begun.
19.3 Selecting the A/D Conversion
Clock
The A/D conversion time per bit is defined as TAD. The
A/D conversion requires 11 TAD per 10-bit conversion.
The source of the A/D conversion clock is software
selectable. There are seven possible options for TAD:
• 2 TOSC
• 4 TOSC
• 8 TOSC
• 16 TOSC
• 32 TOSC
• 64 TOSC
• Internal RC Oscillator
For correct A/D conversions, the A/D conversion clock
(TAD) must be as short as possible, but greater than the
minimum TAD (see parameter 130 for more
information).
Table 19-1 shows the resultant TAD times derived from
the device operating frequencies and the A/D clock
source selected.
TABLE 19-1: TAD vs. DEVICE OPERATING FREQUENCIES
AD Clock Source (TAD) Maximum Device Frequency
Operation ADCS<2:0> PIC18F2X20/4X20 PIC18LF2X2X/4X20(4)
2 TOSC 000 2.86 MHz 1.43 kHz
4 TOSC 100 5.71 MHz 2.86 MHz
8 TOSC 001 11.43 MHz 5.72 MHz
16 TOSC 101 22.86 MHz 11.43 MHz
32 TOSC 010 40.0 MHz 22.86 MHz
64 TOSC 110 40.0 MHz 22.86 MHz
RC(3) x11 1.00 MHz(1) 1.00 MHz(2)
Note 1: The RC source has a typical TAD time of 1.2 μs.
2: The RC source has a typical TAD time of 2.5 μs.
3: 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.
4: Low-power (PIC18LFXXXX) devices only.PIC18F2420/2520/4420/4520
DS39631E-page 230 © 2008 Microchip Technology Inc.
19.4 Operation in Power-Managed
Modes
The selection of the automatic acquisition time and A/D
conversion clock is determined in part by the clock
source and frequency while in a power-managed mode.
If the A/D is expected to operate while the device is in
a power-managed mode, the ACQT<2:0> and
ADCS<2:0> bits in ADCON2 should be updated in
accordance with the clock source to be used in that
mode. After entering the mode, an A/D acquisition or
conversion may be started. Once started, the device
should continue to be clocked by the same clock
source until the conversion has been completed.
If desired, the device may be placed into the
corresponding Idle mode during the conversion. If the
device clock frequency is less than 1 MHz, the A/D RC
clock source should be selected.
Operation in Sleep mode requires the A/D FRC clock to
be selected. If the ACQT<2:0> bits are set to ‘000’ and
a conversion is started, the conversion will be delayed
one instruction cycle to allow execution of the SLEEP
instruction and entry to Sleep mode. The IDLEN bit
(OSCCON<7>) must have already been cleared prior
to starting the conversion.
19.5 Configuring Analog Port Pins
The ADCON1, TRISA, TRISB and TRISE registers all
configure the A/D port pins. The port pins needed 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.
The A/D operation is independent of the state of the
CHS<3:0> bits and the TRIS bits.
Note 1: When reading the PORT register, all pins
configured as analog input channels will
read as cleared (a low level). Pins configured
as digital inputs will convert as
analog inputs. Analog levels on a digitally
configured input will be accurately
converted.
2: Analog levels on any pin defined as a digital
input may cause the digital input buffer
to consume current out of the device’s
specification limits.
3: The PBADEN bit, in Configuration
Register 3H, configures PORTB pins to
reset as analog or digital pins by controlling
how the PCFG bits in ADCON1 are
reset.© 2008 Microchip Technology Inc. DS39631E-page 231
PIC18F2420/2520/4420/4520
19.6 A/D Conversions
Figure 19-4 shows the operation of the A/D Converter
after the GO/DONE bit has been set and the
ACQT<2:0> bits are cleared. A conversion is started
after the following instruction to allow entry into Sleep
mode before the conversion begins.
Figure 19-5 shows the operation of the A/D Converter
after the GO/DONE bit has been set and the
ACQT<2:0> bits are set to ‘010’, and selecting a 4 TAD
acquisition time before the conversion starts.
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. This means 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 completed or aborted, a
2 TAD wait is required before the next acquisition can
be started. After this wait, acquisition on the selected
channel is automatically started.
19.7 Discharge
The discharge phase is used to initialize the value of
the capacitor array. The array is discharged before
every sample. This feature helps to optimize the unitygain
amplifier, as the circuit always needs to charge the
capacitor array, rather than charge/discharge based on
previous measure values.
FIGURE 19-4: A/D CONVERSION TAD CYCLES (ACQT<2:0> = 000, TACQ = 0)
FIGURE 19-5: A/D CONVERSION TAD CYCLES (ACQT<2:0> = 010, TACQ = 4 TAD)
Note: The GO/DONE bit should NOT be set in
the same instruction that turns on the A/D.
TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD11
Set GO/DONE bit
Holding capacitor is disconnected from analog input (typically 100 ns)
TCY - TAD TAD9 TAD10
ADRESH:ADRESL are loaded, GO/DONE bit is cleared,
ADIF bit is set, holding capacitor is connected to analog input.
Conversion starts
b9 b8 b7 b6 b5 b4 b3 b2 b1 b0
On the following cycle:
TAD1
Discharge
1 2 3 4 5 6 7 8 11
Set GO/DONE bit
(Holding capacitor is disconnected)
9 10
Conversion starts
1 2 3 4
(Holding capacitor continues
acquiring input)
TACQT Cycles TAD Cycles
Automatic
Acquisition
Time
b9 b8 b7 b6 b5 b4 b3 b2 b1 b0
ADRESH:ADRESL are loaded, GO/DONE bit is cleared,
ADIF bit is set, holding capacitor is connected to analog input.
On the following cycle:
TAD1
Discharge PIC18F2420/2520/4420/4520
DS39631E-page 232 © 2008 Microchip Technology Inc.
19.8 Use of the CCP2 Trigger
An A/D conversion can be started by the Special Event
Trigger of the CCP2 module. This requires that the
CCP2M<3:0> bits (CCP2CON<3:0>) be programmed
as ‘1011’ and that the A/D module is enabled (ADON
bit is set). When the trigger occurs, the GO/DONE bit
will be set, starting the A/D acquisition and conversion,
and the Timer1 (or Timer3) counter will be reset to zero.
Timer1 (or Timer3) is reset to automatically repeat the
A/D acquisition period with minimal software overhead
(moving ADRESH:ADRESL to the desired location).
The appropriate analog input channel must be selected
and the minimum acquisition period is either timed by
the user, or an appropriate TACQ time is selected before
the Special Event Trigger sets the GO/DONE bit (starts
a conversion).
If the A/D module is not enabled (ADON is cleared), the
Special Event Trigger will be ignored by the A/D
module, but will still reset the Timer1 (or Timer3)
counter.
TABLE 19-2: REGISTERS ASSOCIATED WITH A/D OPERATION
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR1 PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 52
PIE1 PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 52
IPR1 PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
ADRESH A/D Result Register High Byte 51
ADRESL A/D Result Register Low Byte 51
ADCON0 — — CHS3 CHS2 CHS1 CHS0 GO/DONE ADON 51
ADCON1 — — VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0 51
ADCON2 ADFM — ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 51
PORTA RA7(2) RA6(2) RA5 RA4 RA3 RA2 RA1 RA0 52
TRISA TRISA7(2) TRISA6(2) PORTA Data Direction Register 52
PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 52
TRISB PORTB Data Direction Register 52
LATB PORTB Data Latch Register (Read and Write to Data Latch) 52
PORTE(4) — — — — RE3(3) RE2 RE1 RE0 52
TRISE(4) IBF OBF IBOV PSPMODE — TRISE2 TRISE1 TRISE0 52
LATE(4) — — — — — PORTE Data Latch Register 52
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used for A/D conversion.
Note 1: These bits are unimplemented on 28-pin devices; always maintain these bits clear.
2: PORTA<7:6> and their direction bits are individually configured as port pins based on various primary
oscillator modes. When disabled, these bits read as ‘0’.
3: RE3 port bit is available only as an input pin when the MCLRE Configuration bit is ‘0’.
4: These registers are not implemented on 28-pin devices.© 2008 Microchip Technology Inc. DS39631E-page 233
PIC18F2420/2520/4420/4520
20.0 COMPARATOR MODULE
The analog comparator module contains two
comparators that can be configured in a variety of
ways. The inputs can be selected from the analog
inputs multiplexed with pins, RA0 through RA5, as well
as the on-chip voltage reference (see Section 21.0
“Comparator Voltage Reference Module”). The digital
outputs (normal or inverted) are available at the pin
level and can also be read through the control register.
The CMCON register (Register 20-1) selects the
comparator input and output configuration. Block
diagrams of the various comparator configurations are
shown in Figure 20-1.
REGISTER 20-1: CMCON: COMPARATOR CONTROL REGISTER
R-0 R-0 R/W-0 R/W-0 R/W-0 R/W-1 R/W-1 R/W-1
C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 C2OUT: Comparator 2 Output bit
When C2INV = 0:
1 = C2 VIN+ > C2 VIN-
0 = C2 VIN+ < C2 VINWhen
C2INV = 1:
1 = C2 VIN+ < C2 VIN-
0 = C2 VIN+ > C2 VINbit
6 C1OUT: Comparator 1 Output bit
When C1INV = 0:
1 = C1 VIN+ > C1 VIN-
0 = C1 VIN+ < C1 VINWhen
C1INV = 1:
1 = C1 VIN+ < C1 VIN-
0 = C1 VIN+ > C1 VINbit
5 C2INV: Comparator 2 Output Inversion bit
1 = C2 output inverted
0 = C2 output not inverted
bit 4 C1INV: Comparator 1 Output Inversion bit
1 = C1 output inverted
0 = C1 output not inverted
bit 3 CIS: Comparator Input Switch bit
When CM<2:0> = 110:
1 = C1 VIN- connects to RA3/AN3/VREF+
C2 VIN- connects to RA2/AN2/VREF-/CVREF
0 = C1 VIN- connects to RA0/AN0
C2 VIN- connects to RA1/AN1
bit 2-0 CM<2:0>: Comparator Mode bits
Figure 20-1 shows the Comparator modes and the CM<2:0> bit settings.PIC18F2420/2520/4420/4520
DS39631E-page 234 © 2008 Microchip Technology Inc.
20.1 Comparator Configuration
There are eight modes of operation for the comparators,
shown in Figure 20-1. Bits CM<2:0> of the
CMCON register are used to select these modes. The
TRISA register controls the data direction of the comparator
pins for each mode. If the Comparator mode is
changed, the comparator output level may not be valid
for the specified mode change delay shown in
Section 26.0 “Electrical Characteristics”.
FIGURE 20-1: COMPARATOR I/O OPERATING MODES
Note: Comparator interrupts should be disabled
during a Comparator mode change;
otherwise, a false interrupt may occur.
C1
RA0/AN0 VINVIN+
RA3/AN3/ Off (Read as ‘0’)
Comparators Reset
A
A
CM<2:0> = 000
C2
RA1/AN1 VINVIN+
RA2/AN2/ Off (Read as ‘0’)
A
A
C1
VINVIN+
C1OUT
Two Independent Comparators
A
A
CM<2:0> = 010
C2
VINVIN+
C2OUT
A
A
C1
VINVIN+
C1OUT
Two Common Reference Comparators
A
A
CM<2:0> = 100
C2
VINVIN+
C2OUT
A
D
C2
VINVIN+
Off (Read as ‘0’)
One Independent Comparator with Output
D
D
CM<2:0> = 001
C1
VINVIN+
C1OUT
A
A
C1
VINVIN+
Off (Read as ‘0’)
Comparators Off (POR Default Value)
D
D
CM<2:0> = 111
C2
VINVIN+
Off (Read as ‘0’)
D
D
C1
VINVIN+
C1OUT
Four Inputs Multiplexed to Two Comparators
A
A
CM<2:0> = 110
C2
VINVIN+
C2OUT
A
A
From VREF Module
CIS = 0
CIS = 1
CIS = 0
CIS = 1
C1
VINVIN+
C1OUT
Two Common Reference Comparators with Outputs
A
A
CM<2:0> = 101
C2
VINVIN+
C2OUT
A
D
A = Analog Input, port reads zeros always D = Digital Input CIS (CMCON<3>) is the Comparator Input Switch
CVREF
C1
VINVIN+
C1OUT
Two Independent Comparators with Outputs
A
A
CM<2:0> = 011
C2
VINVIN+
C2OUT
A
A
RA5/AN4/SS/HLVDIN/C2OUT*
RA4/T0CKI/C1OUT*
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
RA1/AN1
RA2/AN2/
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
RA1/AN1
RA2/AN2/
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
RA1/AN1
RA2/AN2/
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
RA1/AN1
RA2/AN2/
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
RA1/AN1
RA2/AN2/
VREF+
VREF-/CVREF
RA0/AN0
RA3/AN3/
VREF+
RA1/AN1
RA2/AN2/
VREF-/CVREF
RA4/T0CKI/C1OUT*
RA5/AN4/SS/HLVDIN/C2OUT*
RA0/AN0
RA3/AN3/
VREF+
RA1/AN1
RA2/AN2/
VREF-/CVREF
RA4/T0CKI/C1OUT*
* Setting the TRISA<5:4> bits will disable the comparator outputs by configuring the pins as inputs.© 2008 Microchip Technology Inc. DS39631E-page 235
PIC18F2420/2520/4420/4520
20.2 Comparator Operation
A single comparator is shown in Figure 20-2, along with
the relationship between the analog input levels and
the digital output. When the analog input at VIN+ is less
than the analog input VIN-, the output of the comparator
is a digital low level. When the analog input at VIN+ is
greater than the analog input VIN-, the output of the
comparator is a digital high level. The shaded areas of
the output of the comparator in Figure 20-2 represent
the uncertainty, due to input offsets and response time.
20.3 Comparator Reference
Depending on the comparator operating mode, either
an external or internal voltage reference may be used.
The analog signal present at VIN- is compared to the
signal at VIN+ and the digital output of the comparator
is adjusted accordingly (Figure 20-2).
FIGURE 20-2: SINGLE COMPARATOR
20.3.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. However, threshold detector applications may
require the same reference. The reference signal must
be between VSS and VDD and can be applied to either
pin of the comparator(s).
20.3.2 INTERNAL REFERENCE SIGNAL
The comparator module also allows the selection of an
internally generated voltage reference from the
comparator voltage reference module. This module is
described in more detail in Section 21.0 “Comparator
Voltage Reference Module”.
The internal reference is only available in the mode
where four inputs are multiplexed to two comparators
(CM<2:0> = 110). In this mode, the internal voltage
reference is applied to the VIN+ pin of both
comparators.
20.4 Comparator Response Time
Response time is the minimum time, after selecting a
new reference voltage or input source, before the
comparator output has a valid level. If the internal reference
is changed, the maximum delay of the internal
voltage reference must be considered when using the
comparator outputs. Otherwise, the maximum delay of
the comparators should be used (see Section 26.0
“Electrical Characteristics”).
20.5 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 RA4 and RA5
I/O pins. When enabled, multiplexers in the output path
of the RA4 and RA5 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 20-3 shows the comparator output block
diagram.
The TRISA bits will still function as an output enable/
disable for the RA4 and RA5 pins while in this mode.
The polarity of the comparator outputs can be changed
using the C2INV and C1INV bits (CMCON<4:5>).
–
VIN+ +
VINOutput
Output
VINVIN+
Note 1: When reading the PORT register, all pins
configured as analog inputs will read as
‘0’. Pins configured as digital inputs will
convert an analog input according to the
Schmitt Trigger input specification.
2: Analog levels on any pin defined as a
digital input may cause the input buffer to
consume more current than is specified.PIC18F2420/2520/4420/4520
DS39631E-page 236 © 2008 Microchip Technology Inc.
FIGURE 20-3: COMPARATOR OUTPUT BLOCK DIAGRAM
20.6 Comparator Interrupts
The comparator interrupt flag is set whenever there is
a change in the output value of either comparator.
Software will need to maintain information about the
status of the output bits, as read from CMCON<7:6>, to
determine the actual change that occurred. The CMIF
bit (PIR2<6>) is the Comparator Interrupt Flag. The
CMIF bit must be reset by clearing it. Since it is also
possible to write a ‘1’ to this register, a simulated
interrupt may be initiated.
Both the CMIE bit (PIE2<6>) and the PEIE bit
(INTCON<6>) must be set to enable the interrupt. In
addition, the GIE bit (INTCON<7>) must also be set. If
any of these bits are clear, the interrupt is not enabled,
though the CMIF bit will still be set if an interrupt
condition occurs.
The user, in the Interrupt Service Routine, can clear the
interrupt in the following manner:
a) Any read or write of CMCON will end the
mismatch condition.
b) Clear flag bit, CMIF.
A mismatch condition will continue to set flag bit, CMIF.
Reading CMCON will end the mismatch condition and
allow flag bit, CMIF, to be cleared.
20.7 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.
Each operational comparator will consume additional
current, as shown in the comparator specifications. To
minimize power consumption while in Sleep mode, turn
off the comparators (CM<2:0> = 111) before entering
Sleep. If the device wakes up from Sleep, the contents
of the CMCON register are not affected.
20.8 Effects of a Reset
A device Reset forces the CMCON register to its Reset
state, causing the comparator modules to be turned off
(CM<2:0> = 111). However, the input pins (RA0
through RA3) are configured as analog inputs by
default on device Reset. The I/O configuration for these
pins is determined by the setting of the PCFG<3:0> bits
(ADCON1<3:0>). Therefore, device current is
minimized when analog inputs are present at Reset
time.
D Q
EN
To RA4 or
RA5 pin
Bus
Data
Set
MULTIPLEX
CMIF
bit
- +
Port pins
Read CMCON
Reset
From
Other
Comparator
CxINV
D Q
EN CL
Note: If a change in the CMCON register
(C1OUT or C2OUT) should occur when a
read operation is being executed (start of
the Q2 cycle), then the CMIF (PIR2<6>)
interrupt flag may not get set.© 2008 Microchip Technology Inc. DS39631E-page 237
PIC18F2420/2520/4420/4520
20.9 Analog Input Connection
Considerations
A simplified circuit for an analog input is shown in
Figure 20-4. Since the analog pins are connected to a
digital output, they have reverse biased diodes to VDD
and VSS. The analog input, therefore, must be between
VSS 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 condition may
occur. A maximum source impedance of 10 kΩ is
recommended for the analog sources. Any external
component connected to an analog input pin, such as
a capacitor or a Zener diode, should have very little
leakage current.
FIGURE 20-4: COMPARATOR ANALOG INPUT MODEL
TABLE 20-1: REGISTERS ASSOCIATED WITH COMPARATOR MODULE
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
CMCON C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0 51
CVRCON CVREN CVROE CVRR CVRSS CVR3 CVR2 CVR1 CVR0 51
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 52
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OSCFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
PORTA RA7(1) RA6(1) RA5 RA4 RA3 RA2 RA1 RA0 52
LATA LATA7(1) LATA6(1) PORTA Data Latch Register (Read and Write to Data Latch) 52
TRISA TRISA7(1) TRISA6(1) PORTA Data Direction Register 52
Legend: — = unimplemented, read as ‘0’. Shaded cells are unused by the comparator module.
Note 1: PORTA<7:6> and their direction and latch bits are individually configured as port pins based on various
primary oscillator modes. When disabled, these bits are read as ‘0’.
VA
RS < 10k
AIN
CPIN
5 pF
VDD
VT = 0.6V
VT = 0.6V
RIC
ILEAKAGE
±100 nA
VSS
Legend: CPIN = Input Capacitance
VT = Threshold Voltage
ILEAKAGE = Leakage Current at the pin due to various junctions
RIC = Interconnect Resistance
RS = Source Impedance
VA = Analog Voltage
Comparator
InputPIC18F2420/2520/4420/4520
DS39631E-page 238 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 239
PIC18F2420/2520/4420/4520
21.0 COMPARATOR VOLTAGE
REFERENCE MODULE
The comparator voltage reference is a 16-tap resistor
ladder network that provides a selectable reference
voltage. Although its primary purpose is to provide a
reference for the analog comparators, it may also be
used independently of them.
A block diagram of the module is shown in Figure 21-1.
The resistor ladder is segmented to provide two ranges
of CVREF values and has a power-down function to
conserve power when the reference is not being used.
The module’s supply reference can be provided from
either device VDD/VSS or an external voltage reference.
21.1 Configuring the Comparator
Voltage Reference
The voltage reference module is controlled through the
CVRCON register (Register 21-1). The comparator
voltage reference provides two ranges of output voltage,
each with 16 distinct levels. The range to be used
is selected by the CVRR bit (CVRCON<5>). The
primary difference between the ranges is the size of the
steps selected by the CVREF Selection bits
(CVR<3:0>), with one range offering finer resolution.
The equations used to calculate the output of the
comparator voltage reference are as follows:
If CVRR = 1:
CVREF = ((CVR<3:0>)/24) x CVRSRC
If CVRR = 0:
CVREF = (CVRSRC x 1/4) + (((CVR<3:0>)/32) x
CVRSRC)
The comparator reference supply voltage can come
from either VDD and VSS, or the external VREF+ and
VREF- that are multiplexed with RA2 and RA3. The
voltage source is selected by the CVRSS bit
(CVRCON<4>).
The settling time of the comparator voltage reference
must be considered when changing the CVREF output
(see Table 26-3 in Section 26.0 “Electrical
Characteristics”).
REGISTER 21-1: CVRCON: COMPARATOR VOLTAGE REFERENCE 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
CVREN CVROE(1) CVRR CVRSS CVR3 CVR2 CVR1 CVR0
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 CVREN: Comparator Voltage Reference Enable bit
1 = CVREF circuit powered on
0 = CVREF circuit powered down
bit 6 CVROE: Comparator VREF Output Enable bit(1)
1 = CVREF voltage level is also output on the RA2/AN2/VREF-/CVREF pin
0 = CVREF voltage is disconnected from the RA2/AN2/VREF-/CVREF pin
bit 5 CVRR: Comparator VREF Range Selection bit
1 = 0 to 0.667 CVRSRC, with CVRSRC/24 step size (low range)
0 = 0.25 CVRSRC to 0.75 CVRSRC, with CVRSRC/32 step size (high range)
bit 4 CVRSS: Comparator VREF Source Selection bit
1 = Comparator reference source, CVRSRC = (VREF+) – (VREF-)
0 = Comparator reference source, CVRSRC = VDD – VSS
bit 3-0 CVR3:CVR0: Comparator VREF Value Selection bits (0 ≤ (CVR<3:0>) ≤ 15)
When CVRR = 1:
CVREF = ((CVR<3:0>)/24) • (CVRSRC)
When CVRR = 0:
CVREF = (CVRSRC/4) + ((CVR<3:0>)/32) • (CVRSRC)
Note 1: CVROE overrides the TRISA<2> bit setting.PIC18F2420/2520/4420/4520
DS39631E-page 240 © 2008 Microchip Technology Inc.
FIGURE 21-1: COMPARATOR VOLTAGE REFERENCE BLOCK DIAGRAM
21.2 Voltage Reference Accuracy/Error
The full range of voltage reference cannot be realized
due to the construction of the module. The transistors
on the top and bottom of the resistor ladder network
(Figure 21-1) keep CVREF from approaching the reference
source rails. The voltage reference is derived
from the reference source; therefore, the CVREF output
changes with fluctuations in that source. The tested
absolute accuracy of the voltage reference can be
found in Section 26.0 “Electrical Characteristics”.
21.3 Operation During Sleep
When the device wakes up from Sleep through an
interrupt or a Watchdog Timer time-out, the contents of
the CVRCON register are not affected. To minimize
current consumption in Sleep mode, the voltage
reference should be disabled.
21.4 Effects of a Reset
A device Reset disables the voltage reference by
clearing bit, CVREN (CVRCON<7>). This Reset also
disconnects the reference from the RA2 pin by clearing
bit, CVROE (CVRCON<6>) and selects the high-voltage
range by clearing bit, CVRR (CVRCON<5>). The CVR
value select bits are also cleared.
21.5 Connection Considerations
The voltage reference module operates independently
of the comparator module. The output of the reference
generator may be connected to the RA2 pin if the
CVROE bit is set. Enabling the voltage reference output
onto RA2 when it is configured as a digital input will
increase current consumption. Connecting RA2 as a
digital output with CVRSS enabled will also increase
current consumption.
The RA2 pin can be used as a simple D/A output with
limited drive capability. Due to the limited current drive
capability, a buffer must be used on the voltage
reference output for external connections to VREF.
Figure 21-2 shows an example buffering technique. 16-to-1 MUX
CVR<3:0>
8R
R CVREN
CVRSS = 0
VDD
VREF+ CVRSS = 1
8R
CVRSS = 0
VREF- CVRSS = 1
R
R
R
R
R
R
16 Steps
CVRR
CVREF© 2008 Microchip Technology Inc. DS39631E-page 241
PIC18F2420/2520/4420/4520
FIGURE 21-2: COMPARATOR VOLTAGE REFERENCE OUTPUT BUFFER EXAMPLE
TABLE 21-1: REGISTERS ASSOCIATED WITH COMPARATOR VOLTAGE REFERENCE
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
CVRCON CVREN CVROE CVRR CVRSS CVR3 CVR2 CVR1 CVR0 51
CMCON C2OUT C1OUT C2INV C1INV CIS CM2 CM1 CM0 51
TRISA TRISA7(1) TRISA6(1) PORTA Data Direction Register 52
Legend: Shaded cells are not used with the comparator voltage reference.
Note 1: PORTA pins are enabled based on oscillator configuration.
CVREF Output +
–
CVREF
Module
Voltage
Reference
Output
Impedance
R(1)
RA2
Note 1: R is dependent upon the comparator voltage reference configuration bits, CVRCON<3:0> and CVRCON<5>.
PIC18FXXXXPIC18F2420/2520/4420/4520
DS39631E-page 242 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. Advance Information DS39631E-page 243
PIC18F2420/2520/4420/4520
22.0 HIGH/LOW-VOLTAGE
DETECT (HLVD)
PIC18F2420/2520/4420/4520 devices have a
High/Low-Voltage Detect module (HLVD). This is a programmable
circuit that allows the user to specify both a
device voltage trip point and the direction of change from
that point. If the device experiences an excursion past
the trip point in that direction, 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 the interrupt.
The High/Low-Voltage Detect Control register
(Register 22-1) completely controls the operation of the
HLVD module. This allows the circuitry to be “turned
off” by the user under software control, which
minimizes the current consumption for the device.
The block diagram for the HLVD module is shown in
Figure 22-1.
REGISTER 22-1: HLVDCON: HIGH/LOW-VOLTAGE DETECT CONTROL REGISTER
R/W-0 U-0 R-0 R/W-0 R/W-0 R/W-1 R/W-0 R/W-1
VDIRMAG — IRVST HLVDEN HLVDL3(1) HLVDL2(1) HLVDL1(1) HLVDL0(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7 VDIRMAG: Voltage Direction Magnitude Select bit
1 = Event occurs when voltage equals or exceeds trip point (HLVDL<3:0>)
0 = Event occurs when voltage equals or falls below trip point (HLVDL<3:0>)
bit 6 Unimplemented: Read as ‘0’
bit 5 IRVST: Internal Reference Voltage Stable Flag bit
1 = Indicates that the voltage detect logic will generate the interrupt flag at the specified voltage range
0 = Indicates that the voltage detect logic will not generate the interrupt flag at the specified voltage
range and the HLVD interrupt should not be enabled
bit 4 HLVDEN: High/Low-Voltage Detect Power Enable bit
1 = HLVD enabled
0 = HLVD disabled
bit 3-0 HLVDL<3:0>: Voltage Detection Limit bits(1)
1111 = External analog input is used (input comes from the HLVDIN pin)
1110 = Maximum setting
.
.
.
0000 = Minimum setting
Note 1: See Table 26-4 for specifications.PIC18F2420/2520/4420/4520
DS39631E-page 244 Advance Information © 2008 Microchip Technology Inc.
The module is enabled by setting the HLVDEN bit.
Each time that the HLVD module is enabled, the circuitry
requires some time to stabilize. The IRVST bit is
a read-only bit and is used to indicate when the circuit
is stable. The module can only generate an interrupt
after the circuit is stable and IRVST is set.
The VDIRMAG bit determines the overall operation of
the module. When VDIRMAG is cleared, the module
monitors for drops in VDD below a predetermined set
point. When the bit is set, the module monitors for rises
in VDD above the set point.
22.1 Operation
When the HLVD module is enabled, a comparator uses
an internally generated reference voltage as the set
point. The set point is compared with the trip point,
where each node in the resistor divider represents a
trip point voltage. The “trip point” voltage is the voltage
level at which the device detects a high or low-voltage
event, depending on the configuration of the module.
When the supply voltage is equal to the trip point, the
voltage tapped off of the resistor array is equal to the
internal reference voltage generated by the voltage
reference module. The comparator then generates an
interrupt signal by setting the HLVDIF bit.
The trip point voltage is software programmable to any one
of 16 values. The trip point is selected by programming the
HLVDL<3:0> bits (HLVDCON<3:0>).
The HLVD module has an additional feature that allows
the user to supply the trip voltage to the module from an
external source. This mode is enabled when bits,
HLVDL<3:0>, are set to ‘1111’. In this state, the
comparator input is multiplexed from the external input
pin, HLVDIN. This gives users flexibility because it
allows them to configure the High/Low-Voltage Detect
interrupt to occur at any voltage in the valid operating
range.
FIGURE 22-1: HLVD MODULE BLOCK DIAGRAM (WITH EXTERNAL INPUT)
Set
VDD
16-to-1 MUX
HLVDEN
HLVDCON
HLVDIN
HLVDL<3:0>
Register
HLVDIN
VDD
Externally Generated
Trip Point
HLVDIF
HLVDEN
BOREN
Internal Voltage
Reference
VDIRMAG© 2008 Microchip Technology Inc. Advance Information DS39631E-page 245
PIC18F2420/2520/4420/4520
22.2 HLVD Setup
The following steps are needed to set up the HLVD
module:
1. Write the value to the HLVDL<3:0> bits that
selects the desired HLVD trip point.
2. Set the VDIRMAG bit to detect high voltage
(VDIRMAG = 1) or low voltage (VDIRMAG = 0).
3. Enable the HLVD module by setting the
HLVDEN bit.
4. Clear the HLVD interrupt flag (PIR2<2>), which
may have been set from a previous interrupt.
5. Enable the HLVD interrupt, if interrupts are
desired, by setting the HLVDIE and GIE bits
(PIE2<2> and INTCON<7>). An interrupt will not
be generated until the IRVST bit is set.
22.3 Current Consumption
When the module is enabled, the HLVD comparator
and voltage divider are enabled and will consume static
current. The total current consumption, when enabled,
is specified in electrical specification parameter D022B.
Depending on the application, the HLVD module does
not need to be operating constantly. To decrease the
current requirements, the HLVD circuitry may only
need to be enabled for short periods where the voltage
is checked. After doing the check, the HLVD module
may be disabled.
22.4 HLVD Start-up Time
The internal reference voltage of the HLVD module,
specified in electrical specification parameter D420,
may be used by other internal circuitry, such as the
programmable Brown-out Reset. If the HLVD or other
circuits using the voltage reference are disabled to
lower the device’s current consumption, the reference
voltage circuit will require time to become stable before
a low or high-voltage condition can be reliably
detected. This start-up time, TIRVST, is an interval that
is independent of device clock speed. It is specified in
electrical specification parameter 36.
The HLVD interrupt flag is not enabled until TIRVST has
expired and a stable reference voltage is reached. For
this reason, brief excursions beyond the set point may
not be detected during this interval (refer to Figure 22-2
or Figure 22-3).
FIGURE 22-2: LOW-VOLTAGE DETECT OPERATION (VDIRMAG = 0)
VLVD
VDD
HLVDIF
VLVD
VDD
Enable HLVD
TIRVST
HLVDIF may not be set
Enable HLVD
HLVDIF
HLVDIF Cleared in Software
HLVDIF Cleared in Software
HLVDIF cleared in software,
CASE 1:
CASE 2:
HLVDIF remains set since HLVD condition still exists
TIRVST
Internal Reference is Stable
Internal Reference is Stable
IRVST
IRVSTPIC18F2420/2520/4420/4520
DS39631E-page 246 Advance Information © 2008 Microchip Technology Inc.
FIGURE 22-3: HIGH-VOLTAGE DETECT OPERATION (VDIRMAG = 1)
22.5 Applications
In many applications, the ability to detect a drop below,
or rise above, a particular threshold is desirable. For
example, the HLVD module could be periodically
enabled to detect Universal Serial Bus (USB) attach or
detach. This assumes the device is powered by a lower
voltage source than the USB when detached. An attach
would indicate a high-voltage detect from, for example,
3.3V to 5V (the voltage on USB) and vice versa for a
detach. This feature could save a design a few extra
components and an attach signal (input pin).
For general battery applications, Figure 22-4 shows a
possible voltage curve. Over time, the device voltage
decreases. When the device voltage reaches voltage,
VA, the HLVD logic generates an interrupt at time, TA.
The interrupt could cause the execution of an ISR,
which would allow the application to perform “housekeeping
tasks” and perform a controlled shutdown
before the device voltage exits the valid operating
range at TB. The HLVD, thus, would give the application
a time window, represented by the difference
between TA and TB, to safely exit.
FIGURE 22-4: TYPICAL LOW-VOLTAGE
DETECT APPLICATION
VLVD
VDD
HLVDIF
VLVD
VDD
Enable HLVD
TIRVST
HLVDIF may not be set
Enable HLVD
HLVDIF
HLVDIF Cleared in Software
HLVDIF Cleared in Software
HLVDIF cleared in software,
CASE 1:
CASE 2:
HLVDIF remains set since HLVD condition still exists
TIRVST
IRVST
Internal Reference is Stable
Internal Reference is Stable
IRVST
Time
Voltage
VA
VB
TA TB
VA = HLVD trip point
VB = Minimum valid device
operating voltage
Legend:© 2008 Microchip Technology Inc. Advance Information DS39631E-page 247
PIC18F2420/2520/4420/4520
22.6 Operation During Sleep
When enabled, the HLVD circuitry continues to operate
during Sleep. If the device voltage crosses the trip
point, the HLVDIF 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.
22.7 Effects of a Reset
A device Reset forces all registers to their Reset state.
This forces the HLVD module to be turned off.
TABLE 22-1: REGISTERS ASSOCIATED WITH HIGH/LOW-VOLTAGE DETECT MODULE
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on Page
HLVDCON VDIRMAG — IRVST HLVDEN HLVDL3 HLVDL2 HLVDL1 HLVDL0 50
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 49
PIR2 OSCFIF CMIF — EEIF BCLIF HLVDIF TMR3IF CCP2IF 52
PIE2 OCSFIE CMIE — EEIE BCLIE HLVDIE TMR3IE CCP2IE 52
IPR2 OSCFIP CMIP — EEIP BCLIP HLVDIP TMR3IP CCP2IP 52
Legend: — = unimplemented, read as ‘0’. Shaded cells are unused by the HLVD module.PIC18F2420/2520/4420/4520
DS39631E-page 248 Advance Information © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 249
PIC18F2420/2520/4420/4520
23.0 SPECIAL FEATURES OF
THE CPU
PIC18F2420/2520/4420/4520 devices include several
features intended to maximize reliability and minimize
cost through elimination of external components. These
are:
• Oscillator Selection
• Resets:
- Power-on Reset (POR)
- Power-up Timer (PWRT)
- Oscillator Start-up Timer (OST)
- Brown-out Reset (BOR)
• Interrupts
• Watchdog Timer (WDT)
• Fail-Safe Clock Monitor
• Two-Speed Start-up
• Code Protection
• ID Locations
• In-Circuit Serial Programming
The oscillator can be configured for the application
depending on frequency, power, accuracy and cost. All
of the options are discussed in detail in Section 2.0
“Oscillator Configurations”.
A complete discussion of device Resets and interrupts
is available in previous sections of this data sheet.
In addition to their Power-up and Oscillator Start-up
Timers provided for Resets, PIC18F2420/2520/4420/
4520 devices have a Watchdog Timer, which is either
permanently enabled via the Configuration bits or
software controlled (if configured as disabled).
The inclusion of an internal RC oscillator also provides
the additional benefits of a Fail-Safe Clock Monitor
(FSCM) and Two-Speed Start-up. FSCM provides for
background monitoring of the peripheral clock and
automatic switchover in the event of its failure. TwoSpeed
Start-up enables code to be executed almost
immediately on start-up, while the primary clock source
completes its start-up delays.
All of these features are enabled and configured by
setting the appropriate Configuration register bits.
23.1 Configuration Bits
The Configuration bits can be programmed (read as
‘0’) or left unprogrammed (read as ‘1’) to select various
device configurations. These bits are mapped starting
at program memory location, 300000h.
The user will note that address 300000h is beyond the
user program memory space. In fact, it belongs to the
configuration memory space (300000h-3FFFFFh), which
can only be accessed using table reads and table writes.
Programming the Configuration registers is done in a
manner similar to programming the Flash memory. The
WR bit in the EECON1 register starts a self-timed write
to the Configuration register. In normal operation mode,
a TBLWT instruction with the TBLPTR pointing to the
Configuration register sets up the address and the data
for the Configuration register write. Setting the WR bit
starts a long write to the Configuration register. The
Configuration registers are written a byte at a time. To
write or erase a configuration cell, a TBLWT instruction
can write a ‘1’ or a ‘0’ into the cell. For additional details
on Flash programming, refer to Section 6.5 “Writing
to Flash Program Memory”.
TABLE 23-1: CONFIGURATION BITS AND DEVICE IDs
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Default/
Unprogrammed
Value
300001h CONFIG1H IESO FCMEN — — FOSC3 FOSC2 FOSC1 FOSC0 00-- 0111
300002h CONFIG2L — — — BORV1 BORV0 BOREN1 BOREN0 PWRTEN ---1 1111
300003h CONFIG2H — — — WDTPS3 WDTPS2 WDTPS1 WDTPS0 WDTEN ---1 1111
300005h CONFIG3H MCLRE — — — — LPT1OSC PBADEN CCP2MX 1--- -011
300006h CONFIG4L DEBUG XINST — — — LVP — STVREN 10-- -1-1
300008h CONFIG5L — — — — CP3(1) CP2(1) CP1 CP0 ---- 1111
300009h CONFIG5H CPD CPB — — — — — — 11-- ----
30000Ah CONFIG6L — — — — WRT3(1) WRT2(1) WRT1 WRT0 ---- 1111
30000Bh CONFIG6H WRTD WRTB WRTC — — — — — 111- ----
30000Ch CONFIG7L — — — — EBTR3(1) EBTR2(1) EBTR1 EBTR0 ---- 1111
30000Dh CONFIG7H — EBTRB — — — — — — -1-- ----
3FFFFEh DEVID1 DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0 xxxx xxxx(2)
3FFFFFh DEVID2 DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3 xxxx xxxx(2)
Legend: x = unknown, u = unchanged, — = unimplemented, q = value depends on condition.
Shaded cells are unimplemented, read as ‘0’.
Note 1: Unimplemented in PIC18F2420/4420 devices; maintain this bit set.
2: See Register 23-12 for DEVID1 values. DEVID registers are read-only and cannot be programmed by the user.PIC18F2420/2520/4420/4520
DS39631E-page 250 © 2008 Microchip Technology Inc.
REGISTER 23-1: CONFIG1H: CONFIGURATION REGISTER 1 HIGH (BYTE ADDRESS 300001h)
R/P-0 R/P-0 U-0 U-0 R/P-0 R/P-1 R/P-1 R/P-1
IESO FCMEN — — FOSC3 FOSC2 FOSC1 FOSC0
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 IESO: Internal/External Oscillator Switchover bit
1 = Oscillator Switchover mode enabled
0 = Oscillator Switchover mode disabled
bit 6 FCMEN: Fail-Safe Clock Monitor Enable bit
1 = Fail-Safe Clock Monitor enabled
0 = Fail-Safe Clock Monitor disabled
bit 5-4 Unimplemented: Read as ‘0’
bit 3-0 FOSC<3:0>: Oscillator Selection bits
11xx = External RC oscillator, CLKO function on RA6
101x = External RC oscillator, CLKO function on RA6
1001 = Internal oscillator block, CLKO function on RA6; port function on RA7
1000 = Internal oscillator block, port function on RA6 and RA7
0111 = External RC oscillator, port function on RA6
0110 = HS oscillator, PLL enabled (Clock Frequency = 4 x FOSC1)
0101 = EC oscillator, port function on RA6
0100 = EC oscillator, CLKO function on RA6
0011 = External RC oscillator, CLKO function on RA6
0010 = HS oscillator
0001 = XT oscillator
0000 = LP oscillator© 2008 Microchip Technology Inc. DS39631E-page 251
PIC18F2420/2520/4420/4520
REGISTER 23-2: CONFIG2L: CONFIGURATION REGISTER 2 LOW (BYTE ADDRESS 300002h)
U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1 R/P-1
— — — BORV1(1) BORV0(1) BOREN1(2) BOREN0(2) PWRTEN(2)
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-5 Unimplemented: Read as ‘0’
bit 4-3 BORV<1:0>: Brown-out Reset Voltage bits(1)
11 = Minimum setting
.
.
.
00 = Maximum setting
bit 2-1 BOREN<1:0>: Brown-out Reset Enable bits(2)
11 = Brown-out Reset enabled in hardware only (SBOREN is disabled)
10 = Brown-out Reset enabled in hardware only and disabled in Sleep mode (SBOREN is disabled)
01 = Brown-out Reset enabled and controlled by software (SBOREN is enabled)
00 = Brown-out Reset disabled in hardware and software
bit 0 PWRTEN: Power-up Timer Enable bit(2)
1 = PWRT disabled
0 = PWRT enabled
Note 1: See Section 26.1 “DC Characteristics: Supply Voltage” for specifications.
2: The Power-up Timer is decoupled from Brown-out Reset, allowing these features to be independently
controlled.PIC18F2420/2520/4420/4520
DS39631E-page 252 © 2008 Microchip Technology Inc.
REGISTER 23-3: CONFIG2H: CONFIGURATION REGISTER 2 HIGH (BYTE ADDRESS 300003h)
U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1 R/P-1
— — — WDTPS3 WDTPS2 WDTPS1 WDTPS0 WDTEN
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-5 Unimplemented: Read as ‘0’
bit 4-1 WDTPS<3:0>: Watchdog Timer Postscale Select bits
1111 = 1:32,768
1110 = 1:16,384
1101 = 1:8,192
1100 = 1:4,096
1011 = 1:2,048
1010 = 1:1,024
1001 = 1:512
1000 = 1:256
0111 = 1:128
0110 = 1:64
0101 = 1:32
0100 = 1:16
0011 = 1:8
0010 = 1:4
0001 = 1:2
0000 = 1:1
bit 0 WDTEN: Watchdog Timer Enable bit
1 = WDT enabled
0 = WDT disabled (control is placed on the SWDTEN bit)© 2008 Microchip Technology Inc. DS39631E-page 253
PIC18F2420/2520/4420/4520
REGISTER 23-4: CONFIG3H: CONFIGURATION REGISTER 3 HIGH (BYTE ADDRESS 300005h)
R/P-1 U-0 U-0 U-0 U-0 R/P-0 R/P-1 R/P-1
MCLRE — — — — LPT1OSC PBADEN CCP2MX
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 MCLRE: MCLR Pin Enable bit
1 = MCLR pin enabled; RE3 input pin disabled
0 = RE3 input pin enabled; MCLR disabled
bit 6-3 Unimplemented: Read as ‘0’
bit 2 LPT1OSC: Low-Power Timer1 Oscillator Enable bit
1 = Timer1 configured for low-power operation
0 = Timer1 configured for higher power operation
bit 1 PBADEN: PORTB A/D Enable bit
(Affects ADCON1 Reset state. ADCON1 controls PORTB<4:0> pin configuration.)
1 = PORTB<4:0> pins are configured as analog input channels on Reset
0 = PORTB<4:0> pins are configured as digital I/O on Reset
bit 0 CCP2MX: CCP2 MUX bit
1 = CCP2 input/output is multiplexed with RC1
0 = CCP2 input/output is multiplexed with RB3
REGISTER 23-5: CONFIG4L: CONFIGURATION REGISTER 4 LOW (BYTE ADDRESS 300006h)
R/P-1 R/P-0 U-0 U-0 U-0 R/P-1 U-0 R/P-1
DEBUG XINST — — — LVP — STVREN
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 DEBUG: Background Debugger Enable bit
1 = Background debugger disabled, RB6 and RB7 configured as general purpose I/O pins
0 = Background debugger enabled, RB6 and RB7 are dedicated to In-Circuit Debug
bit 6 XINST: Extended Instruction Set Enable bit
1 = Instruction set extension and Indexed Addressing mode enabled
0 = Instruction set extension and Indexed Addressing mode disabled (Legacy mode)
bit 5-3 Unimplemented: Read as ‘0’
bit 2 LVP: Single-Supply ICSP™ Enable bit
1 = Single-Supply ICSP enabled
0 = Single-Supply ICSP disabled
bit 1 Unimplemented: Read as ‘0’
bit 0 STVREN: Stack Full/Underflow Reset Enable bit
1 = Stack full/underflow will cause Reset
0 = Stack full/underflow will not cause ResetPIC18F2420/2520/4420/4520
DS39631E-page 254 © 2008 Microchip Technology Inc.
REGISTER 23-6: CONFIG5L: CONFIGURATION REGISTER 5 LOW (BYTE ADDRESS 300008h)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — CP3(1) CP2(1) CP1 CP0
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-4 Unimplemented: Read as ‘0’
bit 3 CP3: Code Protection bit(1)
1 = Block 3 (006000-007FFFh) not code-protected
0 = Block 3 (006000-007FFFh) code-protected
bit 2 CP2: Code Protection bit(1)
1 = Block 2 (004000-005FFFh) not code-protected
0 = Block 2 (004000-005FFFh) code-protected
bit 1 CP1: Code Protection bit
1 = Block 1 (002000-003FFFh) not code-protected
0 = Block 1 (002000-003FFFh) code-protected
bit 0 CP0: Code Protection bit
1 = Block 0 (000800-001FFFh) not code-protected
0 = Block 0 (000800-001FFFh) code-protected
Note 1: Unimplemented in PIC18F2420/4420 devices; maintain this bit set.
REGISTER 23-7: CONFIG5H: CONFIGURATION REGISTER 5 HIGH (BYTE ADDRESS 300009h)
R/C-1 R/C-1 U-0 U-0 U-0 U-0 U-0 U-0
CPD CPB — — — — — —
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 CPD: Data EEPROM Code Protection bit
1 = Data EEPROM not code-protected
0 = Data EEPROM code-protected
bit 6 CPB: Boot Block Code Protection bit
1 = Boot block (000000-0007FFh) not code-protected
0 = Boot block (000000-0007FFh) code-protected
bit 5-0 Unimplemented: Read as ‘0’© 2008 Microchip Technology Inc. DS39631E-page 255
PIC18F2420/2520/4420/4520
REGISTER 23-8: CONFIG6L: CONFIGURATION REGISTER 6 LOW (BYTE ADDRESS 30000Ah)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — WRT3(1) WRT2(1) WRT1 WRT0
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-4 Unimplemented: Read as ‘0’
bit 3 WRT3: Write Protection bit(1)
1 = Block 3 (006000-007FFFh) not write-protected
0 = Block 3 (006000-007FFFh) write-protected
bit 2 WRT2: Write Protection bit(1)
1 = Block 2 (004000-005FFFh) not write-protected
0 = Block 2 (004000-005FFFh) write-protected
bit 1 WRT1: Write Protection bit
1 = Block 1 (002000-003FFFh) not write-protected
0 = Block 1 (002000-003FFFh) write-protected
bit 0 WRT0: Write Protection bit
1 = Block 0 (000800-001FFFh) not write-protected
0 = Block 0 (000800-001FFFh) write-protected
Note 1: Unimplemented in PIC18F2420/4420 devices; maintain this bit set.
REGISTER 23-9: CONFIG6H: CONFIGURATION REGISTER 6 HIGH (BYTE ADDRESS 30000Bh)
R/C-1 R/C-1 R/C-1 U-0 U-0 U-0 U-0 U-0
WRTD WRTB WRTC(1) — — — — —
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 WRTD: Data EEPROM Write Protection bit
1 = Data EEPROM not write-protected
0 = Data EEPROM write-protected
bit 6 WRTB: Boot Block Write Protection bit
1 = Boot block (000000-0007FFh) not write-protected
0 = Boot block (000000-0007FFh) write-protected
bit 5 WRTC: Configuration Register Write Protection bit(1)
1 = Configuration registers (300000-3000FFh) not write-protected
0 = Configuration registers (300000-3000FFh) write-protected
bit 4-0 Unimplemented: Read as ‘0’
Note 1: This bit is read-only in normal execution mode; it can be written only in Program mode.PIC18F2420/2520/4420/4520
DS39631E-page 256 © 2008 Microchip Technology Inc.
REGISTER 23-10: CONFIG7L: CONFIGURATION REGISTER 7 LOW (BYTE ADDRESS 30000Ch)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — EBTR3(1) EBTR2(1) EBTR1 EBTR0
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-4 Unimplemented: Read as ‘0’
bit 3 EBTR3: Table Read Protection bit(1)
1 = Block 3 (006000-007FFFh) not protected from table reads executed in other blocks
0 = Block 3 (006000-007FFFh) protected from table reads executed in other blocks
bit 2 EBTR2: Table Read Protection bit(1)
1 = Block 2 (004000-005FFFh) not protected from table reads executed in other blocks
0 = Block 2 (004000-005FFFh) protected from table reads executed in other blocks
bit 1 EBTR1: Table Read Protection bit
1 = Block 1 (002000-003FFFh) not protected from table reads executed in other blocks
0 = Block 1 (002000-003FFFh) protected from table reads executed in other blocks
bit 0 EBTR0: Table Read Protection bit
1 = Block 0 (000800-001FFFh) not protected from table reads executed in other blocks
0 = Block 0 (000800-001FFFh) protected from table reads executed in other blocks
Note 1: Unimplemented in PIC18F2420/4420 devices; maintain this bit set.
REGISTER 23-11: CONFIG7H: CONFIGURATION REGISTER 7 HIGH (BYTE ADDRESS 30000Dh)
U-0 R/C-1 U-0 U-0 U-0 U-0 U-0 U-0
— EBTRB — — — — — —
bit 7 bit 0
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7 Unimplemented: Read as ‘0’
bit 6 EBTRB: Boot Block Table Read Protection bit
1 = Boot block (000000-0007FFh) not protected from table reads executed in other blocks
0 = Boot block (000000-0007FFh) protected from table reads executed in other blocks
bit 5-0 Unimplemented: Read as ‘0’© 2008 Microchip Technology Inc. DS39631E-page 257
PIC18F2420/2520/4420/4520
REGISTER 23-12: DEVID1: DEVICE ID REGISTER 1 FOR PIC18F2420/2520/4420/4520
R R R RR R R R
DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0
bit 7 bit 0
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-5 DEV<2:0>: Device ID bits
110 = PIC18F4420
100 = PIC18F4520
010 = PIC18F2420
000 = PIC18F2520
bit 4-0 REV<4:0>: Revision ID bits
These bits are used to indicate the device revision.
REGISTER 23-13: DEVID2: DEVICE ID REGISTER 2 FOR PIC18F2420/2520/4420/4520
R R R RR R R R
DEV10(1) DEV9(1) DEV8(1) DEV7(1) DEV6(1) DEV5(1) DEV4(1) DEV3(1)
bit 7 bit 0
Legend:
R = Read-only bit P = Programmable bit U = Unimplemented bit, read as ‘0’
-n = Value when device is unprogrammed u = Unchanged from programmed state
bit 7-0 DEV<10:3>: Device ID bits(1)
These bits are used with the DEV<2:0> bits in Device ID Register 1 to identify the part number.
0001 0001 = PIC18F2420/2520 devices
0001 0000 = PIC18F4420/4520 devices
Note 1: These values for DEV<10:3> may be shared with other devices. The specific device is always identified by
using the entire DEV<10:0> bit sequence.PIC18F2420/2520/4420/4520
DS39631E-page 258 © 2008 Microchip Technology Inc.
23.2 Watchdog Timer (WDT)
For PIC18F2420/2520/4420/4520 devices, the WDT is
driven by the INTRC source. When the WDT is
enabled, the clock source is also enabled. The nominal
WDT period is 4 ms and has the same stability as the
INTRC oscillator.
The 4 ms period of the WDT is multiplied by a 16-bit
postscaler. Any output of the WDT postscaler is
selected by a multiplexer, controlled by bits in Configuration
Register 2H. Available periods range from 4 ms
to 131.072 seconds (2.18 minutes). The WDT and
postscaler are cleared when any of the following events
occur: a SLEEP or CLRWDT instruction is executed, the
IRCF bits (OSCCON<6:4>) are changed or a clock
failure has occurred.
23.2.1 CONTROL REGISTER
Register 23-14 shows the WDTCON register. This is a
readable and writable register which contains a control
bit that allows software to override the WDT enable
Configuration bit, but only if the Configuration bit has
disabled the WDT.
FIGURE 23-1: WDT BLOCK DIAGRAM
Note 1: The CLRWDT and SLEEP instructions
clear the WDT and postscaler counts
when executed.
2: Changing the setting of the IRCF bits
(OSCCON<6:4>) clears the WDT and
postscaler counts.
3: When a CLRWDT instruction is executed,
the postscaler count will be cleared.
INTRC Source
WDT
Wake-up from
Reset
WDT Counter
Programmable Postscaler
1:1 to 1:32,768
Enable WDT
WDTPS<3:0>
SWDTEN
WDTEN
CLRWDT
4
Power-Managed
Reset
All Device Resets
Sleep
÷128
Change on IRCF bits
Modes© 2008 Microchip Technology Inc. DS39631E-page 259
PIC18F2420/2520/4420/4520
TABLE 23-2: SUMMARY OF WATCHDOG TIMER REGISTERS
REGISTER 23-14: WDTCON: WATCHDOG TIMER CONTROL REGISTER
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-0
— — — — — — — SWDTEN(1)
bit 7 bit 0
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 7-1 Unimplemented: Read as ‘0’
bit 0 SWDTEN: Software Controlled Watchdog Timer Enable bit(1)
1 = Watchdog Timer is on
0 = Watchdog Timer is off
Note 1: This bit has no effect if the Configuration bit, WDTEN, is enabled.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Reset
Values
on page
RCON IPEN SBOREN(1) — RI TO PD POR BOR 48
WDTCON — — — — — — — SWDTEN(2) 50
Legend: — = unimplemented, read as ‘0’. Shaded cells are not used by the Watchdog Timer.
Note 1: The SBOREN bit is only available when the BOREN<1:0> Configuration bits = 01; otherwise, it is
disabled and reads as ‘0’. See Section 4.4 “Brown-out Reset (BOR)”.
2: This bit has no effect if the Configuration bit, WDTEN, is enabled.PIC18F2420/2520/4420/4520
DS39631E-page 260 © 2008 Microchip Technology Inc.
23.3 Two-Speed Start-up
The Two-Speed Start-up feature helps to minimize the
latency period from oscillator start-up to code execution
by allowing the microcontroller to use the INTOSC
oscillator as a clock source until the primary clock
source is available. It is enabled by setting the IESO
Configuration bit.
Two-Speed Start-up should be enabled only if the
primary oscillator mode is LP, XT, HS or HSPLL
(Crystal-Based modes). Other sources do not require
an OST start-up delay; for these, Two-Speed Start-up
should be disabled.
When enabled, Resets and wake-ups from Sleep mode
cause the device to configure itself to run from the
internal oscillator block as the clock source, following
the time-out of the Power-up Timer after a Power-on
Reset is enabled. This allows almost immediate code
execution while the primary oscillator starts and the
OST is running. Once the OST times out, the device
automatically switches to PRI_RUN mode.
To use a higher clock speed on wake-up, the INTOSC
or postscaler clock sources can be selected to provide
a higher clock speed by setting bits, IRCF<2:0>,
immediately after Reset. For wake-ups from Sleep, the
INTOSC or postscaler clock sources can be selected
by setting the IRCF<2:0> bits prior to entering Sleep
mode.
In all other power-managed modes, Two-Speed Startup
is not used. The device will be clocked by the
currently selected clock source until the primary clock
source becomes available. The setting of the IESO bit
is ignored.
23.3.1 SPECIAL CONSIDERATIONS FOR
USING TWO-SPEED START-UP
While using the INTOSC oscillator in Two-Speed Startup,
the device still obeys the normal command
sequences for entering power-managed modes,
including multiple SLEEP instructions (refer to
Section 3.1.4 “Multiple Sleep Commands”). In
practice, this means that user code can change the
SCS<1:0> bit settings or issue SLEEP instructions
before the OST times out. This would allow an
application to briefly wake-up, perform routine
“housekeeping” tasks and return to Sleep before the
device starts to operate from the primary oscillator.
User code can also check if the primary clock source is
currently providing the device clocking by checking the
status of the OSTS bit (OSCCON<3>). If the bit is set,
the primary oscillator is providing the clock. Otherwise,
the internal oscillator block is providing the clock during
wake-up from Reset or Sleep mode.
FIGURE 23-2: TIMING TRANSITION FOR TWO-SPEED START-UP (INTOSC TO HSPLL)
Q1 Q3 Q4
OSC1
Peripheral
Program PC PC + 2
INTOSC
PLL Clock
Q1
PC + 6
Q2
Output
Q3 Q4 Q1
CPU Clock
PC + 4
Clock
Counter
Q2 Q2 Q3
Note 1: TOST = 1024 TOSC; TPLL = 2 ms (approx). These intervals are not shown to scale.
2: Clock transition typically occurs within 2-4 TOSC.
Wake from Interrupt Event
TPLL(1)
1 2 n-1 n
Clock
OSTS bit Set
Transition(2)
Multiplexer
TOST(1)© 2008 Microchip Technology Inc. DS39631E-page 261
PIC18F2420/2520/4420/4520
23.4 Fail-Safe Clock Monitor
The Fail-Safe Clock Monitor (FSCM) allows the microcontroller
to continue operation in the event of an external
oscillator failure by automatically switching the device
clock to the internal oscillator block. The FSCM function
is enabled by setting the FCMEN Configuration bit.
When FSCM is enabled, the INTRC oscillator runs at
all times to monitor clocks to peripherals and provide a
backup clock in the event of a clock failure. Clock
monitoring (shown in Figure 23-3) is accomplished by
creating a sample clock signal, which is the INTRC output
divided by 64. This allows ample time between
FSCM sample clocks for a peripheral clock edge to
occur. The peripheral device clock and the sample
clock are presented as inputs to the Clock Monitor latch
(CM). The CM is set on the falling edge of the device
clock source, but cleared on the rising edge of the
sample clock.
FIGURE 23-3: FSCM BLOCK DIAGRAM
Clock failure is tested for on the falling edge of the
sample clock. If a sample clock falling edge occurs
while CM is still set, a clock failure has been detected
(Figure 23-4). This causes the following:
• the FSCM generates an oscillator fail interrupt by
setting bit, OSCFIF (PIR2<7>);
• the device clock source is switched to the internal
oscillator block (OSCCON is not updated to show
the current clock source – this is the fail-safe
condition) and
• the WDT is reset.
During switchover, the postscaler frequency from the
internal oscillator block may not be sufficiently stable for
timing sensitive applications. In these cases, it may be
desirable to select another clock configuration and enter
an alternate power-managed mode. This can be done to
attempt a partial recovery or execute a controlled shutdown.
See Section 3.1.4 “Multiple Sleep Commands”
and Section 23.3.1 “Special Considerations for
Using Two-Speed Start-up” for more details.
To use a higher clock speed on wake-up, the INTOSC or
postscaler clock sources can be selected to provide a
higher clock speed by setting bits, IRCF<2:0>, immediately
after Reset. For wake-ups from Sleep, the INTOSC
or postscaler clock sources can be selected by setting the
IRCF<2:0> bits prior to entering Sleep mode.
The FSCM will detect failures of the primary or secondary
clock sources only. If the internal oscillator block
fails, no failure would be detected, nor would any action
be possible.
23.4.1 FSCM AND THE WATCHDOG TIMER
Both the FSCM and the WDT are clocked by the
INTRC oscillator. Since the WDT operates with a
separate divider and counter, disabling the WDT has
no effect on the operation of the INTRC oscillator when
the FSCM is enabled.
As already noted, the clock source is switched to the
INTOSC clock when a clock failure is detected.
Depending on the frequency selected by the
IRCF<2:0> bits, this may mean a substantial change in
the speed of code execution. If the WDT is enabled
with a small prescale value, a decrease in clock speed
allows a WDT time-out to occur and a subsequent
device Reset. For this reason, fail-safe clock events
also reset the WDT and postscaler, allowing it to start
timing from when execution speed was changed and
decreasing the likelihood of an erroneous time-out.
23.4.2 EXITING FAIL-SAFE OPERATION
The fail-safe condition is terminated by either a device
Reset or by entering a power-managed mode. On
Reset, the controller starts the primary clock source
specified in Configuration Register 1H (with any
required start-up delays that are required for the oscillator
mode, such as the OST or PLL timer). The
INTOSC multiplexer provides the device clock until the
primary clock source becomes ready (similar to a TwoSpeed
Start-up). The clock source is then switched to
the primary clock (indicated by the OSTS bit in the
OSCCON register becoming set). The Fail-Safe Clock
Monitor then resumes monitoring the peripheral clock.
The primary clock source may never become ready during
start-up. In this case, operation is clocked by the
INTOSC multiplexer. The OSCCON register will remain
in its Reset state until a power-managed mode is
entered.
Peripheral
INTRC ÷ 64
S
C
Q
(32 μs) 488 Hz
(2.048 ms)
Clock Monitor
Latch (CM)
(edge-triggered)
Clock
Failure
Detected
Source
Clock
QPIC18F2420/2520/4420/4520
DS39631E-page 262 © 2008 Microchip Technology Inc.
FIGURE 23-4: FSCM TIMING DIAGRAM
23.4.3 FSCM INTERRUPTS IN
POWER-MANAGED MODES
By entering a power-managed mode, the clock multiplexer
selects the clock source selected by the OSCCON
register. Fail-Safe Clock Monitoring of the powermanaged
clock source resumes in the power-managed
mode.
If an oscillator failure occurs during power-managed
operation, the subsequent events depend on whether
or not the oscillator failure interrupt is enabled. If
enabled (OSCFIF = 1), code execution will be clocked
by the INTOSC multiplexer. An automatic transition
back to the failed clock source will not occur.
If the interrupt is disabled, subsequent interrupts while
in Idle mode will cause the CPU to begin executing
instructions while being clocked by the INTOSC
source.
23.4.4 POR OR WAKE FROM SLEEP
The FSCM is designed to detect oscillator failure at any
point after the device has exited Power-on Reset
(POR) or low-power Sleep mode. When the primary
device clock is EC, RC or INTRC modes, monitoring
can begin immediately following these events.
For oscillator modes involving a crystal or resonator
(HS, HSPLL, LP or XT), the situation is somewhat
different. Since the oscillator may require a start-up
time considerably longer than the FCSM sample clock
time, a false clock failure may be detected. To prevent
this, the internal oscillator block is automatically configured
as the device clock and functions until the primary
clock is stable (the OST and PLL timers have timed
out). This is identical to Two-Speed Start-up mode.
Once the primary clock is stable, the INTRC returns to
its role as the FSCM source.
As noted in Section 23.3.1 “Special Considerations
for Using Two-Speed Start-up”, it is also possible to
select another clock configuration and enter an
alternate power-managed mode while waiting for the
primary clock to become stable. When the new powermanaged
mode is selected, the primary clock is
disabled.
OSCFIF
CM Output
Device
Clock
Output
Sample Clock
Failure
Detected
Oscillator
Failure
Note: The device clock is normally at a much higher frequency than the sample clock. The relative frequencies in this
example have been chosen for clarity.
(Q)
CM Test CM Test CM Test
Note: The same logic that prevents false oscillator
failure interrupts on POR, or wake from
Sleep, will also prevent the detection of
the oscillator’s failure to start at all following
these events. This can be avoided by
monitoring the OSTS bit and using a
timing routine to determine if the oscillator
is taking too long to start. Even so, no
oscillator failure interrupt will be flagged. © 2008 Microchip Technology Inc. DS39631E-page 263
PIC18F2420/2520/4420/4520
23.5 Program Verification and
Code Protection
The overall structure of the code protection on the
PIC18 Flash devices differs significantly from other
PIC® devices.
The user program memory is divided into five blocks.
One of these is a boot block of 2 Kbytes. The remainder
of the memory is divided into four blocks on binary
boundaries.
Each of the five blocks has three code protection bits
associated with them. They are:
• Code-Protect bit (CPn)
• Write-Protect bit (WRTn)
• External Block Table Read bit (EBTRn)
Figure 23-5 shows the program memory organization
for 16 and 32-Kbyte devices and the specific code protection
bit associated with each block. The actual
locations of the bits are summarized in Table 23-3.
FIGURE 23-5: CODE-PROTECTED PROGRAM MEMORY FOR
PIC18F2420/2520/4420/4520
TABLE 23-3: SUMMARY OF CODE PROTECTION REGISTERS
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
300008h CONFIG5L — — — — CP3(1) CP2(1) CP1 CP0
300009h CONFIG5H CPD CPB — — — — — —
30000Ah CONFIG6L — — — — WRT3(1) WRT2(1) WRT1 WRT0
30000Bh CONFIG6H WRTD WRTB WRTC — — — — —
30000Ch CONFIG7L — — — — EBTR3(1) EBTR2(1) EBTR1 EBTR0
30000Dh CONFIG7H — EBTRB — — — — — —
Legend: Shaded cells are unimplemented.
Note 1: Unimplemented in PIC18F2420/4420 devices; maintain this bit set.
MEMORY SIZE/DEVICE
Block Code Protection
16 Kbytes Controlled By:
(PIC18F2420/4420)
32 Kbytes
(PIC18F2520/4520)
Address
Range
Boot Block Boot Block 000000h
0007FFh CPB, WRTB, EBTRB
Block 0 Block 0
000800h
001FFFh
CP0, WRT0, EBTR0
Block 1 Block 1
002000h
003FFFh
CP1, WRT1, EBTR1
Unimplemented
Read ‘0’s
Block 2
004000h
005FFFh
CP2, WRT2, EBTR2
Block 3
006000h
007FFFh
CP3, WRT3, EBTR3
Unimplemented
Read ‘0’s
1FFFFFh
(Unimplemented Memory Space)PIC18F2420/2520/4420/4520
DS39631E-page 264 © 2008 Microchip Technology Inc.
23.5.1 PROGRAM MEMORY
CODE PROTECTION
The program memory may be read to, or written from,
any location using the table read and table write
instructions. The Device ID may be read with table
reads. The Configuration registers may be read and
written with the table read and table write instructions.
In normal execution mode, the CPn bits have no direct
effect. CPn bits inhibit external reads and writes. A block
of user memory may be protected from table writes if the
WRTn Configuration bit is ‘0’. The EBTRn bits control
table reads. For a block of user memory with the EBTRn
bit set to ‘0’, a table read instruction that executes from
within that block is allowed to read. A table read
instruction that executes from a location outside of that
block is not allowed to read and will result in reading ‘0’s.
Figures 23-6 through 23-8 illustrate table write and table
read protection.
FIGURE 23-6: TABLE WRITE (WRTn) DISALLOWED
Note: Code protection bits may only be written to
a ‘0’ from a ‘1’ state. It is not possible to
write a ‘1’ to a bit in the ‘0’ state. Code protection
bits are only set to ‘1’ by a full chip
erase or block erase function. The full chip
erase and block erase functions can only
be initiated via ICSP or an external
programmer.
000000h
0007FFh
000800h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFh
WRTB, EBTRB = 11
WRT0, EBTR0 = 01
WRT1, EBTR1 = 11
WRT2, EBTR2 = 11
WRT3, EBTR3 = 11
TBLWT*
TBLPTR = 0008FFh
PC = 001FFEh
PC = 005FFEh TBLWT*
Register Values Program Memory Configuration Bit Settings
Results: All table writes disabled to Blockn whenever WRTn = 0.© 2008 Microchip Technology Inc. DS39631E-page 265
PIC18F2420/2520/4420/4520
FIGURE 23-7: EXTERNAL BLOCK TABLE READ (EBTRn) DISALLOWED
FIGURE 23-8: EXTERNAL BLOCK TABLE READ (EBTRn) ALLOWED
WRTB, EBTRB = 11
WRT0, EBTR0 = 10
WRT1, EBTR1 = 11
WRT2, EBTR2 = 11
WRT3, EBTR3 = 11
TBLRD*
TBLPTR = 0008FFh
PC = 003FFEh
Results: All table reads from external blocks to Blockn are disabled whenever EBTRn = 0.
TABLAT register returns a value of ‘0’.
Register Values Program Memory Configuration Bit Settings
000000h
0007FFh
000800h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFh
WRTB, EBTRB = 11
WRT0, EBTR0 = 10
WRT1, EBTR1 = 11
WRT2, EBTR2 = 11
WRT3, EBTR3 = 11
TBLRD*
TBLPTR = 0008FFh
PC = 001FFEh
Register Values Program Memory Configuration Bit Settings
Results: Table reads permitted within Blockn, even when EBTRBn = 0.
TABLAT register returns the value of the data at the location TBLPTR.
000000h
0007FFh
000800h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFhPIC18F2420/2520/4420/4520
DS39631E-page 266 © 2008 Microchip Technology Inc.
23.5.2 DATA EEPROM
CODE PROTECTION
The entire data EEPROM is protected from external
reads and writes by two bits: CPD and WRTD. CPD
inhibits external reads and writes of data EEPROM.
WRTD inhibits internal and external writes to data
EEPROM. The CPU can always read data EEPROM
under normal operation, regardless of the protection bit
settings.
23.5.3 CONFIGURATION REGISTER
PROTECTION
The Configuration registers can be write-protected.
The WRTC bit controls protection of the Configuration
registers. In normal execution mode, the WRTC bit is
read-only. WRTC can only be written via ICSP or an
external programmer.
23.6 ID Locations
Eight memory locations (200000h-200007h) are
designated as ID locations, where the user can store
checksum or other code identification numbers. These
locations are both readable and writable during normal
execution through the TBLRD and TBLWT instructions,
or during program/verify. The ID locations can be read
when the device is code-protected.
23.7 In-Circuit Serial Programming
PIC18F2420/2520/4420/4520 devices can be serially
programmed while in the end application circuit. This is
simply done with two lines for clock and data and three
other lines for power, ground and the programming
voltage. This allows customers to manufacture boards
with unprogrammed devices and then program the
microcontroller just before shipping the product. This
also allows the most recent firmware or a custom
firmware to be programmed.
23.8 In-Circuit Debugger
When the DEBUG Configuration bit is programmed to
a ‘0’, the In-Circuit Debugger functionality is enabled.
This function allows simple debugging functions when
used with MPLAB® IDE. When the microcontroller has
this feature enabled, some resources are not available
for general use. Table 23-4 shows which resources are
required by the background debugger.
TABLE 23-4: DEBUGGER RESOURCES
To use the In-Circuit Debugger function of the microcontroller,
the design must implement In-Circuit Serial
Programming connections to MCLR/VPP/RE3, VDD,
VSS, RB7 and RB6. This will interface to the In-Circuit
Debugger module available from Microchip or one of
the third party development tool companies.
23.9 Single-Supply ICSP Programming
The LVP Configuration bit enables Single-Supply ICSP
Programming (formerly known as Low-Voltage ICSP
Programming or LVP). When Single-Supply Programming
is enabled, the microcontroller can be programmed
without requiring high voltage being applied to the
MCLR/VPP/RE3 pin, but the RB5/KBI1/PGM pin is then
dedicated to controlling Program mode entry and is not
available as a general purpose I/O pin.
While programming, using Single-Supply Programming
mode, VDD is applied to the MCLR/VPP/RE3 pin as in
normal execution mode. To enter Programming mode,
VDD is applied to the PGM pin.
If Single-Supply ICSP Programming mode will not be
used, the LVP bit can be cleared. RB5/KBI1/PGM then
becomes available as the digital I/O pin, RB5. The LVP
bit may be set or cleared only when using standard
high-voltage programming (VIHH applied to the MCLR/
VPP/RE3 pin). Once LVP has been disabled, only the
standard high-voltage programming is available and
must be used to program the device.
Memory that is not code-protected can be erased using
either a block erase, or erased row by row, then written
at any specified VDD. If code-protected memory is to be
erased, a block erase is required. If a block erase is to
be performed when using Low-Voltage Programming,
the device must be supplied with VDD of 4.5V to 5.5V.
I/O pins: RB6, RB7
Stack: 2 levels
Program Memory: 512 bytes
Data Memory: 10 bytes
Note 1: High-voltage programming is always
available, regardless of the state of the
LVP bit or the PGM pin, by applying VIHH
to the MCLR pin.
2: By default, Single-Supply ICSP is
enabled in unprogrammed devices (as
supplied from Microchip) and erased
devices.
3: When Single-Supply Programming is
enabled, the RB5 pin can no longer be
used as a general purpose I/O pin.
4: When LVP is enabled, externally pull the
PGM pin to VSS to allow normal program
execution.© 2008 Microchip Technology Inc. DS39631E-page 267
PIC18F2420/2520/4420/4520
24.0 INSTRUCTION SET SUMMARY
PIC18F2420/2520/4420/4520 devices incorporate the
standard set of 75 PIC18 core instructions, as well as an
extended set of 8 new instructions, for the optimization
of code that is recursive or that utilizes a software stack.
The extended set is discussed later in this section.
24.1 Standard Instruction Set
The standard PIC18 instruction set adds many
enhancements to the previous PIC® MCU instruction
sets, while maintaining an easy migration from these
PIC MCU instruction sets. Most instructions are a
single program memory word (16 bits), but there are
four instructions that require two program memory
locations.
Each single-word instruction is a 16-bit word divided
into an opcode, which specifies the instruction type and
one or more operands, which further specify the
operation of the instruction.
The instruction set is highly orthogonal and is grouped
into four basic categories:
• Byte-oriented operations
• Bit-oriented operations
• Literal operations
• Control operations
The PIC18 instruction set summary in Table 24-2 lists
byte-oriented, bit-oriented, literal and control
operations. Table 24-1 shows the opcode field
descriptions.
Most byte-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The destination of the result (specified by ‘d’)
3. The accessed memory (specified by ‘a’)
The file register designator ‘f’ specifies which file
register is to be used by the instruction. The destination
designator ‘d’ specifies where the result of the operation
is to be placed. If ‘d’ is zero, the result is placed in
the WREG register. If ‘d’ is one, the result is placed in
the file register specified in the instruction.
All bit-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The bit in the file register (specified by ‘b’)
3. The accessed memory (specified by ‘a’)
The bit field designator ‘b’ selects the number of the bit
affected by the operation, while the file register
designator ‘f’ represents the number of the file in which
the bit is located.
The literal instructions may use some of the following
operands:
• A literal value to be loaded into a file register
(specified by ‘k’)
• The desired FSR register to load the literal value
into (specified by ‘f’)
• No operand required
(specified by ‘—’)
The control instructions may use some of the following
operands:
• A program memory address (specified by ‘n’)
• The mode of the CALL or RETURN instructions
(specified by ‘s’)
• The mode of the table read and table write
instructions (specified by ‘m’)
• No operand required
(specified by ‘—’)
All instructions are a single word, except for four
double-word instructions. These instructions were
made double-word to contain the required information
in 32 bits. In the second word, the 4 MSbs are ‘1’s. If
this second word is executed as an instruction (by
itself), it will execute as a NOP.
All single-word instructions are executed in a single
instruction cycle, unless a conditional test is true or the
program counter is changed as a result of the instruction.
In these cases, the execution takes two instruction
cycles, with the additional instruction cycle(s) executed
as a NOP.
The double-word instructions execute in two instruction
cycles.
One instruction cycle consists of four oscillator periods.
Thus, for an oscillator frequency of 4 MHz, the normal
instruction execution time is 1 μs. If a conditional test is
true, or the program counter is changed as a result of
an instruction, the instruction execution time is 2 μs.
Two-word branch instructions (if true) would take 3 μs.
Figure 24-1 shows the general formats that the instructions
can have. All examples use the convention ‘nnh’
to represent a hexadecimal number.
The Instruction Set Summary, shown in Table 24-2,
lists the standard instructions recognized by the
Microchip Assembler (MPASMTM).
Section 24.1.1 “Standard Instruction Set” provides
a description of each instruction.PIC18F2420/2520/4420/4520
DS39631E-page 268 © 2008 Microchip Technology Inc.
TABLE 24-1: OPCODE FIELD DESCRIPTIONS
Field Description
a RAM access bit
a = 0: RAM location in Access RAM (BSR register is ignored)
a = 1: RAM bank is specified by BSR register
bbb Bit address within an 8-bit file register (0 to 7).
BSR Bank Select Register. Used to select the current RAM bank.
C, DC, Z, OV, N ALU Status bits: Carry, Digit Carry, Zero, Overflow, Negative.
d Destination select bit
d = 0: store result in WREG
d = 1: store result in file register f
dest Destination: either the WREG register or the specified register file location.
f 8-bit Register file address (00h to FFh) or 2-bit FSR designator (0h to 3h).
fs 12-bit Register file address (000h to FFFh). This is the source address.
fd 12-bit Register file address (000h to FFFh). This is the destination address.
GIE Global Interrupt Enable bit.
k Literal field, constant data or label (may be either an 8-bit, 12-bit or a 20-bit value).
label Label name.
mm The mode of the TBLPTR register for the table read and table write instructions.
Only used with table read and table write instructions:
* No change to register (such as TBLPTR with table reads and writes)
*+ Post-Increment register (such as TBLPTR with table reads and writes)
*- Post-Decrement register (such as TBLPTR with table reads and writes)
+* Pre-Increment register (such as TBLPTR with table reads and writes)
n The relative address (2’s complement number) for relative branch instructions or the direct address for
Call/Branch and Return instructions.
PC Program Counter.
PCL Program Counter Low Byte.
PCH Program Counter High Byte.
PCLATH Program Counter High Byte Latch.
PCLATU Program Counter Upper Byte Latch.
PD Power-down bit.
PRODH Product of Multiply High Byte.
PRODL Product of Multiply Low Byte.
s Fast Call/Return mode select bit
s = 0: do not update into/from shadow registers
s = 1: certain registers loaded into/from shadow registers (Fast mode)
TBLPTR 21-bit Table Pointer (points to a Program Memory location).
TABLAT 8-bit Table Latch.
TO Time-out bit.
TOS Top-of-Stack.
u Unused or unchanged.
WDT Watchdog Timer.
WREG Working register (accumulator).
x Don’t care (‘0’ or ‘1’). The assembler will generate code with x = 0. It is the recommended form of use for
compatibility with all Microchip software tools.
zs 7-bit offset value for indirect addressing of register files (source).
zd 7-bit offset value for indirect addressing of register files (destination).
{ } Optional argument.
[text] Indicates an indexed address.
(text) The contents of text.
[expr] Specifies bit n of the register indicated by the pointer expr.
→ Assigned to.
< > Register bit field.
∈ In the set of.
italics User-defined term (font is Courier New).© 2008 Microchip Technology Inc. DS39631E-page 269
PIC18F2420/2520/4420/4520
FIGURE 24-1: GENERAL FORMAT FOR INSTRUCTIONS
Byte-oriented file register operations
15 10 9 8 7 0
d = 0 for result destination to be WREG register
OPCODE d a f (FILE #)
d = 1 for result destination to be file register (f)
a = 0 to force Access Bank
Bit-oriented file register operations
15 12 11 9 8 7 0
OPCODE b (BIT #) a f (FILE #)
b = 3-bit position of bit in file register (f)
Literal operations
15 8 7 0
OPCODE k (literal)
k = 8-bit immediate value
Byte to Byte move operations (2-word)
15 12 11 0
OPCODE f (Source FILE #)
CALL, GOTO and Branch operations
15 8 7 0
OPCODE n<7:0> (literal)
n = 20-bit immediate value
a = 1 for BSR to select bank
f = 8-bit file register address
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
15 12 11 0
1111 n<19:8> (literal)
15 12 11 0
1111 f (Destination FILE #)
f = 12-bit file register address
Control operations
Example Instruction
ADDWF MYREG, W, B
MOVFF MYREG1, MYREG2
BSF MYREG, bit, B
MOVLW 7Fh
GOTO Label
15 8 7 0
OPCODE n<7:0> (literal)
15 12 11 0
1111 n<19:8> (literal)
CALL MYFUNC
15 11 10 0
OPCODE n<10:0> (literal)
S = Fast bit
BRA MYFUNC
15 8 7 0
OPCODE n<7:0> (literal) BC MYFUNC
SPIC18F2420/2520/4420/4520
DS39631E-page 270 © 2008 Microchip Technology Inc.
TABLE 24-2: PIC18FXXXX INSTRUCTION SET
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
BYTE-ORIENTED OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
SUBWF
SUBWFB
SWAPF
TSTFSZ
XORWF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, Skip =
Compare f with WREG, Skip >
Compare f with WREG, Skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to 1st word
fd (destination) 2nd word
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
Borrow
Subtract WREG from f
Subtract WREG from f with
Borrow
Swap Nibbles in f
Test f, Skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1 (2 or 3)
1
0010
0010
0001
0110
0001
0110
0110
0110
0000
0010
0100
0010
0011
0100
0001
0101
1100
1111
0110
0000
0110
0011
0100
0011
0100
0110
0101
0101
0101
0011
0110
0001
01da
00da
01da
101a
11da
001a
010a
000a
01da
11da
11da
10da
11da
10da
00da
00da
ffff
ffff
111a
001a
110a
01da
01da
00da
00da
100a
01da
11da
10da
10da
011a
10da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z, N
Z, N
None
None
None
C, DC, Z, OV, N
C, Z, N
Z, N
C, Z, N
Z, N
None
C, DC, Z, OV, N
C, DC, Z, OV, N
C, DC, Z, OV, N
None
None
Z, N
1, 2
1, 2
1,2
2
1, 2
4
4
1, 2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
4
1, 2
1, 2
1
1, 2
1, 2
1, 2
1, 2
4
1, 2
Note 1: When a PORT 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.
3: If the 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 two-word instructions. The second word of these instructions will be executed as a NOP unless the
first word of the instruction retrieves the information embedded in these 16 bits. This ensures that all program memory
locations have a valid instruction.© 2008 Microchip Technology Inc. DS39631E-page 271
PIC18F2420/2520/4420/4520
BIT-ORIENTED OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
CLRWDT
DAW
GOTO
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
RETLW
RETURN
SLEEP
n
n
n
n
n
n
n
n
n
n, s
—
—
n
—
—
—
—
n
s
k
s
—
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call Subroutine 1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to Address 1st word
2nd word
No Operation
No Operation
Pop Top of Return Stack (TOS)
Push Top of Return Stack (TOS)
Relative Call
Software Device Reset
Return from Interrupt Enable
Return with Literal in WREG
Return from Subroutine
Go into Standby mode
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
2
1
1
2
1
1
1
1
2
1
2
2
2
1
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0000
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
1100
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
kkkk
0001
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
kkkk
001s
0011
None
None
None
None
None
None
None
None
None
None
TO, PD
C
None
None
None
None
None
None
All
GIE/GIEH,
PEIE/GIEL
None
None
TO, PD
4
TABLE 24-2: PIC18FXXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT 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.
3: If the 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 two-word instructions. The second word of these instructions will be executed as a NOP unless the
first word of the instruction retrieves the information embedded in these 16 bits. This ensures that all program memory
locations have a valid instruction.PIC18F2420/2520/4420/4520
DS39631E-page 272 © 2008 Microchip Technology Inc.
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
LFSR
MOVLB
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
f, k
k
k
k
k
k
k
Add Literal and WREG
AND Literal with WREG
Inclusive OR Literal with WREG
Move Literal (12-bit)2nd word
to FSR(f) 1st word
Move Literal to BSR<3:0>
Move Literal to WREG
Multiply Literal with WREG
Return with Literal in WREG
Subtract WREG from Literal
Exclusive OR Literal with WREG
1
1
1
2
1
1
1
2
1
1
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
0000
1111
1011
1001
1110
0000
0001
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
00ff
kkkk
0000
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
None
None
None
None
C, DC, Z, OV, N
Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD*
TBLRD*+
TBLRD*-
TBLRD+*
TBLWT*
TBLWT*+
TBLWT*-
TBLWT+*
Table Read
Table Read with Post-Increment
Table Read with Post-Decrement
Table Read with Pre-Increment
Table Write
Table Write with Post-Increment
Table Write with Post-Decrement
Table Write with Pre-Increment
2
2
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
1000
1001
1010
1011
1100
1101
1110
1111
None
None
None
None
None
None
None
None
TABLE 24-2: PIC18FXXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT 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.
3: If the 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 two-word instructions. The second word of these instructions will be executed as a NOP unless the
first word of the instruction retrieves the information embedded in these 16 bits. This ensures that all program memory
locations have a valid instruction.© 2008 Microchip Technology Inc. DS39631E-page 273
PIC18F2420/2520/4420/4520
24.1.1 STANDARD INSTRUCTION SET
ADDLW ADD Literal to W
Syntax: ADDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) + k → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1111 kkkk kkkk
Description: The contents of W are added to the
8-bit literal ‘k’ and the result is placed in
W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: ADDLW 15h
Before Instruction
W = 10h
After Instruction
W = 25h
ADDWF ADD W to f
Syntax: ADDWF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0010 01da ffff ffff
Description: Add W to register ‘f’. If ‘d’ is ‘0’, the
result is stored in W. If ‘d’ is ‘1’, the
result is stored back in register ‘f’
(default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ADDWF REG, 0, 0
Before Instruction
W = 17h
REG = 0C2h
After Instruction
W = 0D9h
REG = 0C2h
Note: All PIC18 instructions may take an optional label argument preceding the instruction mnemonic for use in
symbolic addressing. If a label is used, the instruction format then becomes: {label} instruction argument(s).PIC18F2420/2520/4420/4520
DS39631E-page 274 © 2008 Microchip Technology Inc.
ADDWFC ADD W and Carry bit to f
Syntax: ADDWFC f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) + (C) → dest
Status Affected: N,OV, C, DC, Z
Encoding: 0010 00da ffff ffff
Description: Add W, the Carry flag and data memory
location ‘f’. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed in data memory location ‘f’.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ADDWFC REG, 0, 1
Before Instruction
Carry bit = 1
REG = 02h
W = 4Dh
After Instruction
Carry bit = 0
REG = 02h
W = 50h
ANDLW AND Literal with W
Syntax: ANDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .AND. k → W
Status Affected: N, Z
Encoding: 0000 1011 kkkk kkkk
Description: The contents of W are ANDed with the
8-bit literal ‘k’. The result is placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’
Process
Data
Write to W
Example: ANDLW 05Fh
Before Instruction
W = A3h
After Instruction
W = 03h© 2008 Microchip Technology Inc. DS39631E-page 275
PIC18F2420/2520/4420/4520
ANDWF AND W with f
Syntax: ANDWF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .AND. (f) → dest
Status Affected: N, Z
Encoding: 0001 01da ffff ffff
Description: The contents of W are ANDed with
register ‘f’. If ‘d’ is ‘0’, the result is stored
in W. If ‘d’ is ‘1’, the result is stored back
in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: ANDWF REG, 0, 0
Before Instruction
W = 17h
REG = C2h
After Instruction
W = 02h
REG = C2h
BC Branch if Carry
Syntax: BC n
Operands: -128 ≤ n ≤ 127
Operation: if Carry bit is ‘1’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0010 nnnn nnnn
Description: If the Carry bit is ‘1’, then the program
will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BC 5
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 1;
PC = address (HERE + 12)
If Carry = 0;
PC = address (HERE + 2)PIC18F2420/2520/4420/4520
DS39631E-page 276 © 2008 Microchip Technology Inc.
BCF Bit Clear f
Syntax: BCF f, b {,a}
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 0 → f
Status Affected: None
Encoding: 1001 bbba ffff ffff
Description: Bit ‘b’ in register ‘f’ is cleared.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BCF FLAG_REG, 7, 0
Before Instruction
FLAG_REG = C7h
After Instruction
FLAG_REG = 47h
BN Branch if Negative
Syntax: BN n
Operands: -128 ≤ n ≤ 127
Operation: if Negative bit is ‘1’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0110 nnnn nnnn
Description: If the Negative bit is ‘1’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 1;
PC = address (Jump)
If Negative = 0;
PC = address (HERE + 2)© 2008 Microchip Technology Inc. DS39631E-page 277
PIC18F2420/2520/4420/4520
BNC Branch if Not Carry
Syntax: BNC n
Operands: -128 ≤ n ≤ 127
Operation: if Carry bit is ‘0’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0011 nnnn nnnn
Description: If the Carry bit is ‘0’, then the program
will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNC Jump
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 0;
PC = address (Jump)
If Carry = 1;
PC = address (HERE + 2)
BNN Branch if Not Negative
Syntax: BNN n
Operands: -128 ≤ n ≤ 127
Operation: if Negative bit is ‘0’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0111 nnnn nnnn
Description: If the Negative bit is ‘0’, then the
program will branch.
The 2’s complement number ‘2n’ is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 0;
PC = address (Jump)
If Negative = 1;
PC = address (HERE + 2)PIC18F2420/2520/4420/4520
DS39631E-page 278 © 2008 Microchip Technology Inc.
BNOV Branch if Not Overflow
Syntax: BNOV n
Operands: -128 ≤ n ≤ 127
Operation: if Overflow bit is ‘0’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0101 nnnn nnnn
Description: If the Overflow bit is ‘0’, then the
program will branch.
The 2’s complement number, ‘2n’, is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNOV Jump
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 0;
PC = address (Jump)
If Overflow = 1;
PC = address (HERE + 2)
BNZ Branch if Not Zero
Syntax: BNZ n
Operands: -128 ≤ n ≤ 127
Operation: if Zero bit is ‘0’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0001 nnnn nnnn
Description: If the Zero bit is ‘0’, then the program
will branch.
The 2’s complement number, ‘2n’, is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BNZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 0;
PC = address (Jump)
If Zero = 1;
PC = address (HERE + 2)© 2008 Microchip Technology Inc. DS39631E-page 279
PIC18F2420/2520/4420/4520
BRA Unconditional Branch
Syntax: BRA n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 0nnn nnnn nnnn
Description: Add the 2’s complement number, ‘2n’, to
the PC. Since the PC will have incremented
to fetch the next instruction, the
new address will be PC + 2 + 2n. This
instruction is a two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE BRA Jump
Before Instruction
PC = address (HERE)
After Instruction
PC = address (Jump)
BSF Bit Set f
Syntax: BSF f, b {,a}
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 1 → f
Status Affected: None
Encoding: 1000 bbba ffff ffff
Description: Bit ‘b’ in register ‘f’ is set.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BSF FLAG_REG, 7, 1
Before Instruction
FLAG_REG = 0Ah
After Instruction
FLAG_REG = 8AhPIC18F2420/2520/4420/4520
DS39631E-page 280 © 2008 Microchip Technology Inc.
BTFSC Bit Test File, Skip if Clear
Syntax: BTFSC f, b {,a}
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: skip if (f) = 0
Status Affected: None
Encoding: 1011 bbba ffff ffff
Description: If bit ‘b’ in register ‘f’ is ‘0’, then the next
instruction is skipped. If bit ‘b’ is ‘0’, then
the next instruction fetched during the
current instruction execution is discarded
and a NOP is executed instead, making
this a two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected. If
‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates in
Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh).
See Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSC
:
:
FLAG, 1, 0
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (TRUE)
If FLAG<1> = 1;
PC = address (FALSE)
BTFSS Bit Test File, Skip if Set
Syntax: BTFSS f, b {,a}
Operands: 0 ≤ f ≤ 255
0 ≤ b < 7
a ∈ [0,1]
Operation: skip if (f) = 1
Status Affected: None
Encoding: 1010 bbba ffff ffff
Description: If bit ‘b’ in register ‘f’ is ‘1’, then the next
instruction is skipped. If bit ‘b’ is ‘1’, then
the next instruction fetched during the
current instruction execution is discarded
and a NOP is executed instead, making
this a two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected. If
‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh).
See Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSS
:
:
FLAG, 1, 0
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (FALSE)
If FLAG<1> = 1;
PC = address (TRUE)© 2008 Microchip Technology Inc. DS39631E-page 281
PIC18F2420/2520/4420/4520
BTG Bit Toggle f
Syntax: BTG f, b {,a}
Operands: 0 ≤ f ≤ 255
0 ≤ b < 7
a ∈ [0,1]
Operation: (f) → f
Status Affected: None
Encoding: 0111 bbba ffff ffff
Description: Bit ‘b’ in data memory location ‘f’ is
inverted.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: BTG PORTC, 4, 0
Before Instruction:
PORTC = 0111 0101 [75h]
After Instruction:
PORTC = 0110 0101 [65h]
BOV Branch if Overflow
Syntax: BOV n
Operands: -128 ≤ n ≤ 127
Operation: if Overflow bit is ‘1’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0100 nnnn nnnn
Description: If the Overflow bit is ‘1’, then the
program will branch.
The 2’s complement number, ‘2n’, is
added to the PC. Since the PC will have
incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BOV Jump
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 1;
PC = address (Jump)
If Overflow = 0;
PC = address (HERE + 2)PIC18F2420/2520/4420/4520
DS39631E-page 282 © 2008 Microchip Technology Inc.
BZ Branch if Zero
Syntax: BZ n
Operands: -128 ≤ n ≤ 127
Operation: if Zero bit is ‘1’,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0000 nnnn nnnn
Description: If the Zero bit is ‘1’, then the program
will branch.
The 2’s complement number, ‘2n’, is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is then a
two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
Process
Data
No
operation
Example: HERE BZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 1;
PC = address (Jump)
If Zero = 0;
PC = address (HERE + 2)
CALL Subroutine Call
Syntax: CALL k {,s}
Operands: 0 ≤ k ≤ 1048575
s ∈ [0,1]
Operation: (PC) + 4 → TOS,
k → PC<20:1>;
if s = 1,
(W) → WS,
(STATUS) → STATUSS,
(BSR) → BSRS
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
110s
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: Subroutine call of entire 2-Mbyte
memory range. First, return address
(PC + 4) is pushed onto the return
stack. If ‘s’ = 1, the W, STATUS and
BSR registers are also pushed into their
respective shadow registers, WS,
STATUSS and BSRS. If ‘s’ = 0, no
update occurs (default). Then, the
20-bit value ‘k’ is loaded into PC<20:1>.
CALL is a two-cycle instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’<7:0>,
PUSH PC to
stack
Read literal
‘k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE CALL THERE, 1
Before Instruction
PC = address (HERE)
After Instruction
PC = address (THERE)
TOS = address (HERE + 4)
WS = W
BSRS = BSR
STATUSS = STATUS© 2008 Microchip Technology Inc. DS39631E-page 283
PIC18F2420/2520/4420/4520
CLRF Clear f
Syntax: CLRF f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: 000h → f,
1 → Z
Status Affected: Z
Encoding: 0110 101a ffff ffff
Description: Clears the contents of the specified
register.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: CLRF FLAG_REG, 1
Before Instruction
FLAG_REG = 5Ah
After Instruction
FLAG_REG = 00h
CLRWDT Clear Watchdog Timer
Syntax: CLRWDT
Operands: None
Operation: 000h → WDT,
000h → WDT postscaler,
1 → TO,
1 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0100
Description: CLRWDT instruction resets the
Watchdog Timer. It also resets the postscaler
of the WDT. Status bits, TO and
PD, are set.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
No
operation
Example: CLRWDT
Before Instruction
WDT Counter = ?
After Instruction
WDT Counter = 00h
WDT Postscaler = 0
TO = 1
PD = 1PIC18F2420/2520/4420/4520
DS39631E-page 284 © 2008 Microchip Technology Inc.
COMF Complement f
Syntax: COMF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest
Status Affected: N, Z
Encoding: 0001 11da ffff ffff
Description: The contents of register ‘f’ are
complemented. If ‘d’ is ‘0’, the result is
stored in W. If ‘d’ is ‘1’, the result is
stored back in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: COMF REG, 0, 0
Before Instruction
REG = 13h
After Instruction
REG = 13h
W = ECh
CPFSEQ Compare f with W, Skip if f = W
Syntax: CPFSEQ f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) = (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 001a ffff ffff
Description: Compares the contents of data memory
location ‘f’ to the contents of W by
performing an unsigned subtraction.
If ‘f’ = W, then the fetched instruction is
discarded and a NOP is executed
instead, making this a two-cycle
instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSEQ REG, 0
NEQUAL :
EQUAL :
Before Instruction
PC Address = HERE
W =?
REG = ?
After Instruction
If REG = W;
PC = Address (EQUAL)
If REG ≠ W;
PC = Address (NEQUAL)© 2008 Microchip Technology Inc. DS39631E-page 285
PIC18F2420/2520/4420/4520
CPFSGT Compare f with W, Skip if f > W
Syntax: CPFSGT f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) > (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 010a ffff ffff
Description: Compares the contents of data memory
location ‘f’ to the contents of the W by
performing an unsigned subtraction.
If the contents of ‘f’ are greater than the
contents of WREG, then the fetched
instruction is discarded and a NOP is
executed instead, making this a
two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSGT REG, 0
NGREATER :
GREATER :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG > W;
PC = Address (GREATER)
If REG ≤ W;
PC = Address (NGREATER)
CPFSLT Compare f with W, Skip if f < W
Syntax: CPFSLT f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) < (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 000a ffff ffff
Description: Compares the contents of data memory
location ‘f’ to the contents of W by
performing an unsigned subtraction.
If the contents of ‘f’ are less than the
contents of W, then the fetched
instruction is discarded and a NOP is
executed instead, making this a
two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSLT REG, 1
NLESS :
LESS :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG < W;
PC = Address (LESS)
If REG ≥ W;
PC = Address (NLESS)PIC18F2420/2520/4420/4520
DS39631E-page 286 © 2008 Microchip Technology Inc.
DAW Decimal Adjust W Register
Syntax: DAW
Operands: None
Operation: If [W<3:0> > 9] or [DC = 1] then,
(W<3:0>) + 6 → W<3:0>;
else,
(W<3:0>) → W<3:0>;
If [W<7:4> + DC > 9] or [C = 1] then,
(W<7:4>) + 6 + DC → W<7:4>;
else,
(W<7:4>) + DC → W<7:4>
Status Affected: C
Encoding: 0000 0000 0000 0111
Description: DAW adjusts the 8-bit value in W,
resulting from the earlier addition of two
variables (each in packed BCD format)
and produces a correct packed BCD
result.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register W
Process
Data
Write
W
Example 1:
DAW
Before Instruction
W = A5h
C =0
DC = 0
After Instruction
W = 05h
C =1
DC = 0
Example 2:
Before Instruction
W = CEh
C =0
DC = 0
After Instruction
W = 34h
C =1
DC = 0
DECF Decrement f
Syntax: DECF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0000 01da ffff ffff
Description: Decrement register ‘f’. If ‘d’ is ‘0’, the
result is stored in W. If ‘d’ is ‘1’, the
result is stored back in register ‘f’
(default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: DECF CNT, 1, 0
Before Instruction
CNT = 01h
Z =0
After Instruction
CNT = 00h
Z =1© 2008 Microchip Technology Inc. DS39631E-page 287
PIC18F2420/2520/4420/4520
DECFSZ Decrement f, Skip if 0
Syntax: DECFSZ f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0010 11da ffff ffff
Description: The contents of register ‘f’ are
decremented. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If the result is ‘0’, the next instruction,
which is already fetched, is discarded
and a NOP is executed instead, making
it a two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DECFSZ CNT, 1, 1
GOTO LOOP
CONTINUE
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT – 1
If CNT = 0;
PC = Address (CONTINUE)
If CNT ≠ 0;
PC = Address (HERE + 2)
DCFSNZ Decrement f, Skip if Not 0
Syntax: DCFSNZ f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 11da ffff ffff
Description: The contents of register ‘f’ are
decremented. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If the result is not ‘0’, the next
instruction, which is already fetched, is
discarded and a NOP is executed
instead, making it a two-cycle
instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DCFSNZ TEMP, 1, 0
ZERO :
NZERO :
Before Instruction
TEMP = ?
After Instruction
TEMP = TEMP – 1,
If TEMP = 0;
PC = Address (ZERO)
If TEMP ≠ 0;
PC = Address (NZERO)PIC18F2420/2520/4420/4520
DS39631E-page 288 © 2008 Microchip Technology Inc.
GOTO Unconditional Branch
Syntax: GOTO k
Operands: 0 ≤ k ≤ 1048575
Operation: k → PC<20:1>
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
1111
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: GOTO allows an unconditional branch
anywhere within entire
2-Mbyte memory range. The 20-bit
value ‘k’ is loaded into PC<20:1>.
GOTO is always a two-cycle
instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’<7:0>,
No
operation
Read literal
‘k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: GOTO THERE
After Instruction
PC = Address (THERE)
INCF Increment f
Syntax: INCF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0010 10da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: INCF CNT, 1, 0
Before Instruction
CNT = FFh
Z =0
C =?
DC = ?
After Instruction
CNT = 00h
Z =1
C =1
DC = 1© 2008 Microchip Technology Inc. DS39631E-page 289
PIC18F2420/2520/4420/4520
INCFSZ Increment f, Skip if 0
Syntax: INCFSZ f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0011 11da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If the result is ‘0’, the next instruction,
which is already fetched, is discarded
and a NOP is executed instead, making
it a two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INCFSZ CNT, 1, 0
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT + 1
If CNT = 0;
PC = Address (ZERO)
If CNT ≠ 0;
PC = Address (NZERO)
INFSNZ Increment f, Skip if Not 0
Syntax: INFSNZ f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 10da ffff ffff
Description: The contents of register ‘f’ are
incremented. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If the result is not ‘0’, the next
instruction, which is already fetched, is
discarded and a NOP is executed
instead, making it a two-cycle
instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INFSNZ REG, 1, 0
ZERO
NZERO
Before Instruction
PC = Address (HERE)
After Instruction
REG = REG + 1
If REG ≠ 0;
PC = Address (NZERO)
If REG = 0;
PC = Address (ZERO)PIC18F2420/2520/4420/4520
DS39631E-page 290 © 2008 Microchip Technology Inc.
IORLW Inclusive OR Literal with W
Syntax: IORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .OR. k → W
Status Affected: N, Z
Encoding: 0000 1001 kkkk kkkk
Description: The contents of W are ORed with the
8-bit literal ‘k’. The result is placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: IORLW 35h
Before Instruction
W = 9Ah
After Instruction
W = BFh
IORWF Inclusive OR W with f
Syntax: IORWF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .OR. (f) → dest
Status Affected: N, Z
Encoding: 0001 00da ffff ffff
Description: Inclusive OR W with register ‘f’. If ‘d’ is
‘0’, the result is placed in W. If ‘d’ is ‘1’,
the result is placed back in register ‘f’
(default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: IORWF RESULT, 0, 1
Before Instruction
RESULT = 13h
W = 91h
After Instruction
RESULT = 13h
W = 93h© 2008 Microchip Technology Inc. DS39631E-page 291
PIC18F2420/2520/4420/4520
LFSR Load FSR
Syntax: LFSR f, k
Operands: 0 ≤ f ≤ 2
0 ≤ k ≤ 4095
Operation: k → FSRf
Status Affected: None
Encoding: 1110
1111
1110
0000
00ff
k7kkk
k11kkk
kkkk
Description: The 12-bit literal ‘k’ is loaded into the
File Select Register pointed to by ‘f’.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘k’ MSB
Process
Data
Write
literal ‘k’
MSB to
FSRfH
Decode Read literal
‘k’ LSB
Process
Data
Write literal
‘k’ to FSRfL
Example: LFSR 2, 3ABh
After Instruction
FSR2H = 03h
FSR2L = ABh
MOVF Move f
Syntax: MOVF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: f → dest
Status Affected: N, Z
Encoding: 0101 00da ffff ffff
Description: The contents of register ‘f’ are moved to
a destination dependent upon the
status of ‘d’. If ‘d’ is ‘0’, the result is
placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
Location ‘f’ can be anywhere in the
256-byte bank.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write W
Example: MOVF REG, 0, 0
Before Instruction
REG = 22h
W = FFh
After Instruction
REG = 22h
W = 22hPIC18F2420/2520/4420/4520
DS39631E-page 292 © 2008 Microchip Technology Inc.
MOVFF Move f to f
Syntax: MOVFF fs,fd
Operands: 0 ≤ fs ≤ 4095
0 ≤ fd ≤ 4095
Operation: (fs) → fd
Status Affected: None
Encoding:
1st word (source)
2nd word (destin.)
1100
1111
ffff
ffff
ffff
ffff
ffffs
ffffd
Description: The contents of source register ‘fs’ are
moved to destination register ‘fd’.
Location of source ‘fs’ can be anywhere
in the 4096-byte data space (000h to
FFFh) and location of destination ‘fd’
can also be anywhere from 000h to
FFFh.
Either source or destination can be W
(a useful special situation).
MOVFF is particularly useful for
transferring a data memory location to a
peripheral register (such as the transmit
buffer or an I/O port).
The MOVFF instruction cannot use the
PCL, TOSU, TOSH or TOSL as the
destination register.
Words: 2
Cycles: 2 (3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
(src)
Process
Data
No
operation
Decode No
operation
No dummy
read
No
operation
Write
register ‘f’
(dest)
Example: MOVFF REG1, REG2
Before Instruction
REG1 = 33h
REG2 = 11h
After Instruction
REG1 = 33h
REG2 = 33h
MOVLB Move Literal to Low Nibble in BSR
Syntax: MOVLW k
Operands: 0 ≤ k ≤ 255
Operation: k → BSR
Status Affected: None
Encoding: 0000 0001 kkkk kkkk
Description: The 8-bit literal ‘k’ is loaded into the
Bank Select Register (BSR). The value
of BSR<7:4> always remains ‘0’,
regardless of the value of k7:k4.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write literal
‘k’ to BSR
Example: MOVLB 5
Before Instruction
BSR Register = 02h
After Instruction
BSR Register = 05h© 2008 Microchip Technology Inc. DS39631E-page 293
PIC18F2420/2520/4420/4520
MOVLW Move Literal to W
Syntax: MOVLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W
Status Affected: None
Encoding: 0000 1110 kkkk kkkk
Description: The 8-bit literal ‘k’ is loaded into W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: MOVLW 5Ah
After Instruction
W = 5Ah
MOVWF Move W to f
Syntax: MOVWF f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) → f
Status Affected: None
Encoding: 0110 111a ffff ffff
Description: Move data from W to register ‘f’.
Location ‘f’ can be anywhere in the
256-byte bank.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: MOVWF REG, 0
Before Instruction
W = 4Fh
REG = FFh
After Instruction
W = 4Fh
REG = 4FhPIC18F2420/2520/4420/4520
DS39631E-page 294 © 2008 Microchip Technology Inc.
MULLW Multiply Literal with W
Syntax: MULLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) x k → PRODH:PRODL
Status Affected: None
Encoding: 0000 1101 kkkk kkkk
Description: An unsigned multiplication is carried
out between the contents of W and the
8-bit literal ‘k’. The 16-bit result is
placed in the PRODH:PRODL register
pair. PRODH contains the high byte.
W is unchanged.
None of the Status flags are affected.
Note that neither Overflow nor Carry is
possible in this operation. A zero result
is possible but not detected.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write
registers
PRODH:
PRODL
Example: MULLW 0C4h
Before Instruction
W = E2h
PRODH = ?
PRODL = ?
After Instruction
W = E2h
PRODH = ADh
PRODL = 08h
MULWF Multiply W with f
Syntax: MULWF f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) x (f) → PRODH:PRODL
Status Affected: None
Encoding: 0000 001a ffff ffff
Description: An unsigned multiplication is carried
out between the contents of W and the
register file location ‘f’. The 16-bit
result is stored in the PRODH:PRODL
register pair. PRODH contains the
high byte. Both W and ‘f’ are
unchanged.
None of the Status flags are affected.
Note that neither Overflow nor Carry is
possible in this operation. A zero
result is possible but not detected.
If ‘a’ is ‘0’, the Access Bank is
selected. If ‘a’ is ‘1’, the BSR is used
to select the GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction
operates in Indexed Literal Offset
Addressing mode whenever
f ≤ 95 (5Fh). See Section 24.2.3
“Byte-Oriented and Bit-Oriented
Instructions in Indexed Literal Offset
Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
registers
PRODH:
PRODL
Example: MULWF REG, 1
Before Instruction
W = C4h
REG = B5h
PRODH = ?
PRODL = ?
After Instruction
W = C4h
REG = B5h
PRODH = 8Ah
PRODL = 94h© 2008 Microchip Technology Inc. DS39631E-page 295
PIC18F2420/2520/4420/4520
NEGF Negate f
Syntax: NEGF f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: ( f ) + 1 → f
Status Affected: N, OV, C, DC, Z
Encoding: 0110 110a ffff ffff
Description: Location ‘f’ is negated using two’s
complement. The result is placed in the
data memory location ‘f’.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: NEGF REG, 1
Before Instruction
REG = 0011 1010 [3Ah]
After Instruction
REG = 1100 0110 [C6h]
NOP No Operation
Syntax: NOP
Operands: None
Operation: No operation
Status Affected: None
Encoding: 0000
1111
0000
xxxx
0000
xxxx
0000
xxxx
Description: No operation.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
Example:
None.PIC18F2420/2520/4420/4520
DS39631E-page 296 © 2008 Microchip Technology Inc.
POP Pop Top of Return Stack
Syntax: POP
Operands: None
Operation: (TOS) → bit bucket
Status Affected: None
Encoding: 0000 0000 0000 0110
Description: The TOS value is pulled off the return
stack and is discarded. The TOS value
then becomes the previous value that
was pushed onto the return stack.
This instruction is provided to enable
the user to properly manage the return
stack to incorporate a software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
POP TOS
value
No
operation
Example: POP
GOTO NEW
Before Instruction
TOS = 0031A2h
Stack (1 level down) = 014332h
After Instruction
TOS = 014332h
PC = NEW
PUSH Push Top of Return Stack
Syntax: PUSH
Operands: None
Operation: (PC + 2) → TOS
Status Affected: None
Encoding: 0000 0000 0000 0101
Description: The PC + 2 is pushed onto the top of
the return stack. The previous TOS
value is pushed down on the stack.
This instruction allows implementing a
software stack by modifying TOS and
then pushing it onto the return stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode PUSH
PC + 2 onto
return stack
No
operation
No
operation
Example: PUSH
Before Instruction
TOS = 345Ah
PC = 0124h
After Instruction
PC = 0126h
TOS = 0126h
Stack (1 level down) = 345Ah© 2008 Microchip Technology Inc. DS39631E-page 297
PIC18F2420/2520/4420/4520
RCALL Relative Call
Syntax: RCALL n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 → TOS,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 1nnn nnnn nnnn
Description: Subroutine call with a jump up to 1K
from the current location. First, return
address (PC + 2) is pushed onto the
stack. Then, add the 2’s complement
number ‘2n’ to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC + 2 + 2n. This instruction is a
two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
‘n’
PUSH PC to
stack
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE RCALL Jump
Before Instruction
PC = Address (HERE)
After Instruction
PC = Address (Jump)
TOS = Address (HERE + 2)
RESET Reset
Syntax: RESET
Operands: None
Operation: Reset all registers and flags that are
affected by a MCLR Reset.
Status Affected: All
Encoding: 0000 0000 1111 1111
Description: This instruction provides a way to
execute a MCLR Reset in software.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Start
Reset
No
operation
No
operation
Example: RESET
After Instruction
Registers = Reset Value
Flags* = Reset ValuePIC18F2420/2520/4420/4520
DS39631E-page 298 © 2008 Microchip Technology Inc.
RETFIE Return from Interrupt
Syntax: RETFIE {s}
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
1 → GIE/GIEH or PEIE/GIEL;
if s = 1,
(WS) → W,
(STATUSS) → STATUS,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged
Status Affected: GIE/GIEH, PEIE/GIEL.
Encoding: 0000 0000 0001 000s
Description: Return from interrupt. Stack is popped
and Top-of-Stack (TOS) is loaded into
the PC. Interrupts are enabled by
setting either the high or low-priority
global interrupt enable bit. If ‘s’ = 1, the
contents of the shadow registers, WS,
STATUSS and BSRS, are loaded into
their corresponding registers, W,
STATUS and BSR. If ‘s’ = 0, no update
of these registers occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
POP PC
from stack
Set GIEH or
GIEL
No
operation
No
operation
No
operation
No
operation
Example: RETFIE 1
After Interrupt
PC = TOS
W = WS
BSR = BSRS
STATUS = STATUSS
GIE/GIEH, PEIE/GIEL = 1
RETLW Return Literal to W
Syntax: RETLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W,
(TOS) → PC,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 1100 kkkk kkkk
Description: W is loaded with the 8-bit literal ‘k’. The
program counter is loaded from the top
of the stack (the return address). The
high address latch (PCLATH) remains
unchanged.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
POP PC
from stack,
Write to W
No
operation
No
operation
No
operation
No
operation
Example:
CALL TABLE ; W contains table
; offset value
; W now has
; table value
:
TABLE
ADDWF PCL ; W = offset
RETLW k0 ; Begin table
RETLW k1 ;
:
:
RETLW kn ; End of table
Before Instruction
W = 07h
After Instruction
W = value of kn© 2008 Microchip Technology Inc. DS39631E-page 299
PIC18F2420/2520/4420/4520
RETURN Return from Subroutine
Syntax: RETURN {s}
Operands: s ∈ [0,1]
Operation: (TOS) → PC;
if s = 1,
(WS) → W,
(STATUSS) → STATUS,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 0000 0001 001s
Description: Return from subroutine. The stack is
popped and the top of the stack (TOS)
is loaded into the program counter. If
‘s’= 1, the contents of the shadow
registers, WS, STATUSS and BSRS,
are loaded into their corresponding
registers, W, STATUS and BSR. If
‘s’ = 0, no update of these registers
occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
POP PC
from stack
No
operation
No
operation
No
operation
No
operation
Example: RETURN
After Instruction:
PC = TOS
RLCF Rotate Left f through Carry
Syntax: RLCF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → C,
(C) → dest<0>
Status Affected: C, N, Z
Encoding: 0011 01da ffff ffff
Description: The contents of register ‘f’ are rotated
one bit to the left through the Carry
flag. If ‘d’ is ‘0’, the result is placed in
W. If ‘d’ is ‘1’, the result is stored back
in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is
selected. If ‘a’ is ‘1’, the BSR is used to
select the GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction
operates in Indexed Literal Offset
Addressing mode whenever
f ≤ 95 (5Fh). See Section 24.2.3
“Byte-Oriented and Bit-Oriented
Instructions in Indexed Literal Offset
Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RLCF REG, 0, 0
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 1100 1100
C =1
C register fPIC18F2420/2520/4420/4520
DS39631E-page 300 © 2008 Microchip Technology Inc.
RLNCF Rotate Left f (No Carry)
Syntax: RLNCF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → dest<0>
Status Affected: N, Z
Encoding: 0100 01da ffff ffff
Description: The contents of register ‘f’ are rotated
one bit to the left. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result is
stored back in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RLNCF REG, 1, 0
Before Instruction
REG = 1010 1011
After Instruction
REG = 0101 0111
register f
RRCF Rotate Right f through Carry
Syntax: RRCF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → C,
(C) → dest<7>
Status Affected: C, N, Z
Encoding: 0011 00da ffff ffff
Description: The contents of register ‘f’ are rotated
one bit to the right through the Carry
flag. If ‘d’ is ‘0’, the result is placed in W.
If ‘d’ is ‘1’, the result is placed back in
register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: RRCF REG, 0, 0
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 0111 0011
C =0
C register f© 2008 Microchip Technology Inc. DS39631E-page 301
PIC18F2420/2520/4420/4520
RRNCF Rotate Right f (No Carry)
Syntax: RRNCF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → dest<7>
Status Affected: N, Z
Encoding: 0100 00da ffff ffff
Description: The contents of register ‘f’ are rotated
one bit to the right. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result is
placed back in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank will be
selected, overriding the BSR value. If ‘a’
is ‘1’, then the bank will be selected as
per the BSR value (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: RRNCF REG, 1, 0
Before Instruction
REG = 1101 0111
After Instruction
REG = 1110 1011
Example 2: RRNCF REG, 0, 0
Before Instruction
W =?
REG = 1101 0111
After Instruction
W = 1110 1011
REG = 1101 0111
register f
SETF Set f
Syntax: SETF f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: FFh → f
Status Affected: None
Encoding: 0110 100a ffff ffff
Description: The contents of the specified register
are set to FFh.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write
register ‘f’
Example: SETF REG, 1
Before Instruction
REG = 5Ah
After Instruction
REG = FFhPIC18F2420/2520/4420/4520
DS39631E-page 302 © 2008 Microchip Technology Inc.
SLEEP Enter Sleep mode
Syntax: SLEEP
Operands: None
Operation: 00h → WDT,
0 → WDT postscaler,
1 → TO,
0 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0011
Description: The Power-Down status bit (PD) is
cleared. The Time-out status bit (TO)
is set. Watchdog Timer and its postscaler
are cleared.
The processor is put into Sleep mode
with the oscillator stopped.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
Go to
Sleep
Example: SLEEP
Before Instruction
TO = ?
PD = ?
After Instruction
TO = 1 †
PD = 0
† If WDT causes wake-up, this bit is cleared.
SUBFWB Subtract f from W with Borrow
Syntax: SUBFWB f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) – (f) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 01da ffff ffff
Description: Subtract register ‘f’ and Carry flag
(borrow) from W (2’s complement
method). If ‘d’ is ‘0’, the result is stored
in W. If ‘d’ is ‘1’, the result is stored in
register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is
selected. If ‘a’ is ‘1’, the BSR is used
to select the GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction
operates in Indexed Literal Offset
Addressing mode whenever
f ≤ 95 (5Fh). See Section 24.2.3
“Byte-Oriented and Bit-Oriented
Instructions in Indexed Literal Offset
Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBFWB REG, 1, 0
Before Instruction
REG = 3
W =2
C =1
After Instruction
REG = FF
W =2
C =0
Z =0
N = 1 ; result is negative
Example 2: SUBFWB REG, 0, 0
Before Instruction
REG = 2
W =5
C =1
After Instruction
REG = 2
W =3
C =1
Z =0
N = 0 ; result is positive
Example 3: SUBFWB REG, 1, 0
Before Instruction
REG = 1
W =2
C =0
After Instruction
REG = 0
W =2
C =1
Z = 1 ; result is zero
N =0© 2008 Microchip Technology Inc. DS39631E-page 303
PIC18F2420/2520/4420/4520
SUBLW Subtract W from Literal
Syntax: SUBLW k
Operands: 0 ≤ k ≤ 255
Operation: k – (W) → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1000 kkkk kkkk
Description W is subtracted from the 8-bit
literal ‘k’. The result is placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example 1: SUBLW 02h
Before Instruction
W = 01h
C =?
After Instruction
W = 01h
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBLW 02h
Before Instruction
W = 02h
C =?
After Instruction
W = 00h
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBLW 02h
Before Instruction
W = 03h
C =?
After Instruction
W = FFh ; (2’s complement)
C = 0 ; result is negative
Z =0
N =1
SUBWF Subtract W from f
Syntax: SUBWF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 11da ffff ffff
Description: Subtract W from register ‘f’ (2’s
complement method). If ‘d’ is ‘0’, the
result is stored in W. If ‘d’ is ‘1’, the
result is stored back in register ‘f’
(default).
If ‘a’ is ‘0’, the Access Bank is
selected. If ‘a’ is ‘1’, the BSR is used
to select the GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction
operates in Indexed Literal Offset
Addressing mode whenever
f ≤ 95 (5Fh). See Section 24.2.3
“Byte-Oriented and Bit-Oriented
Instructions in Indexed Literal Offset
Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBWF REG, 1, 0
Before Instruction
REG = 3
W =2
C =?
After Instruction
REG = 1
W =2
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBWF REG, 0, 0
Before Instruction
REG = 2
W =2
C =?
After Instruction
REG = 2
W =0
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBWF REG, 1, 0
Before Instruction
REG = 1
W =2
C =?
After Instruction
REG = FFh ;(2’s complement)
W =2
C = 0 ; result is negative
Z =0
N =1PIC18F2420/2520/4420/4520
DS39631E-page 304 © 2008 Microchip Technology Inc.
SUBWFB Subtract W from f with Borrow
Syntax: SUBWFB f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 10da ffff ffff
Description: Subtract W and the Carry flag (borrow)
from register ‘f’ (2’s complement
method). If ‘d’ is ‘0’, the result is stored
in W. If ‘d’ is ‘1’, the result is stored back
in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example 1: SUBWFB REG, 1, 0
Before Instruction
REG = 19h (0001 1001)
W = 0Dh (0000 1101)
C =1
After Instruction
REG = 0Ch (0000 1011)
W = 0Dh (0000 1101)
C =1
Z =0
N = 0 ; result is positive
Example 2: SUBWFB REG, 0, 0
Before Instruction
REG = 1Bh (0001 1011)
W = 1Ah (0001 1010)
C =0
After Instruction
REG = 1Bh (0001 1011)
W = 00h
C =1
Z = 1 ; result is zero
N =0
Example 3: SUBWFB REG, 1, 0
Before Instruction
REG = 03h (0000 0011)
W = 0Eh (0000 1101)
C =1
After Instruction
REG = F5h (1111 0100)
; [2’s comp]
W = 0Eh (0000 1101)
C =0
Z =0
N = 1 ; result is negative
SWAPF Swap f
Syntax: SWAPF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f<3:0>) → dest<7:4>,
(f<7:4>) → dest<3:0>
Status Affected: None
Encoding: 0011 10da ffff ffff
Description: The upper and lower nibbles of register
‘f’ are exchanged. If ‘d’ is ‘0’, the result
is placed in W. If ‘d’ is ‘1’, the result is
placed in register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: SWAPF REG, 1, 0
Before Instruction
REG = 53h
After Instruction
REG = 35h© 2008 Microchip Technology Inc. DS39631E-page 305
PIC18F2420/2520/4420/4520
TBLRD Table Read
Syntax: TBLRD ( *; *+; *-; +*)
Operands: None
Operation: if TBLRD *,
(Prog Mem (TBLPTR)) → TABLAT,
TBLPTR – No Change;
if TBLRD *+,
(Prog Mem (TBLPTR)) → TABLAT,
(TBLPTR) + 1 → TBLPTR;
if TBLRD *-,
(Prog Mem (TBLPTR)) → TABLAT,
(TBLPTR) – 1 → TBLPTR;
if TBLRD +*,
(TBLPTR) + 1 → TBLPTR,
(Prog Mem (TBLPTR)) → TABLAT
Status Affected: None
Encoding: 0000 0000 0000 10nn
nn=0 *
=1 *+
=2 *-
=3 +*
Description: This instruction is used to read the contents
of Program Memory (P.M.). To address the
program memory, a pointer called Table
Pointer (TBLPTR) is used.
The TBLPTR (a 21-bit pointer) points to
each byte in the program memory. TBLPTR
has a 2-Mbyte address range.
TBLPTR<0> = 0:Least Significant Byte
of Program Memory
Word
TBLPTR<0> = 1:Most Significant Byte of
Program Memory
Word
The TBLRD instruction can modify the value
of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No operation
(Read Program
Memory)
No
operation
No operation
(Write TABLAT)
TBLRD Table Read (Continued)
Example1: TBLRD *+ ;
Before Instruction
TABLAT = 55h
TBLPTR = 00A356h
MEMORY (00A356h) = 34h
After Instruction
TABLAT = 34h
TBLPTR = 00A357h
Example2: TBLRD +* ;
Before Instruction
TABLAT = AAh
TBLPTR = 01A357h
MEMORY (01A357h) = 12h
MEMORY (01A358h) = 34h
After Instruction
TABLAT = 34h
TBLPTR = 01A358hPIC18F2420/2520/4420/4520
DS39631E-page 306 © 2008 Microchip Technology Inc.
TBLWT Table Write
Syntax: TBLWT ( *; *+; *-; +*)
Operands: None
Operation: if TBLWT*,
(TABLAT) → Holding Register,
TBLPTR – No Change;
if TBLWT*+,
(TABLAT) → Holding Register,
(TBLPTR) + 1 → TBLPTR;
if TBLWT*-,
(TABLAT) → Holding Register,
(TBLPTR) – 1 → TBLPTR;
if TBLWT+*,
(TBLPTR) + 1 → TBLPTR,
(TABLAT) → Holding Register
Status Affected: None
Encoding: 0000 0000 0000 11nn
nn=0 *
=1 *+
=2 *-
=3 +*
Description: This instruction uses the 3 LSBs of
TBLPTR to determine which of the
8 holding registers the TABLAT is written
to. The holding registers are used to
program the contents of Program
Memory (P.M.). (Refer to Section 6.0
“Flash Program Memory” for additional
details on programming Flash memory.)
The TBLPTR (a 21-bit pointer) points to
each byte in the program memory.
TBLPTR has a 2-MByte address range.
The LSb of the TBLPTR selects which
byte of the program memory location to
access.
TBLPTR<0> = 0:Least Significant
Byte of Program
Memory Word
TBLPTR<0> = 1:Most Significant
Byte of Program
Memory Word
The TBLWT instruction can modify the
value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No
operation
(Read
TABLAT)
No
operation
No
operation
(Write to
Holding
Register )
TBLWT Table Write (Continued)
Example1: TBLWT *+;
Before Instruction
TABLAT = 55h
TBLPTR = 00A356h
HOLDING REGISTER
(00A356h) = FFh
After Instructions (table write completion)
TABLAT = 55h
TBLPTR = 00A357h
HOLDING REGISTER
(00A356h) = 55h
Example 2: TBLWT +*;
Before Instruction
TABLAT = 34h
TBLPTR = 01389Ah
HOLDING REGISTER
(01389Ah) = FFh
HOLDING REGISTER
(01389Bh) = FFh
After Instruction (table write completion)
TABLAT = 34h
TBLPTR = 01389Bh
HOLDING REGISTER
(01389Ah) = FFh
HOLDING REGISTER
(01389Bh) = 34h
© 2008 Microchip Technology Inc. DS39631E-page 307
PIC18F2420/2520/4420/4520
TSTFSZ Test f, Skip if 0
Syntax: TSTFSZ f {,a}
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: skip if f = 0
Status Affected: None
Encoding: 0110 011a ffff ffff
Description: If ‘f’ = 0, the next instruction fetched
during the current instruction execution
is discarded and a NOP is executed,
making this a two-cycle instruction.
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE TSTFSZ CNT, 1
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
If CNT = 00h,
PC = Address (ZERO)
If CNT ≠ 00h,
PC = Address (NZERO)
XORLW Exclusive OR Literal with W
Syntax: XORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .XOR. k → W
Status Affected: N, Z
Encoding: 0000 1010 kkkk kkkk
Description: The contents of W are XORed with
the 8-bit literal ‘k’. The result is placed
in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to W
Example: XORLW 0AFh
Before Instruction
W = B5h
After Instruction
W = 1AhPIC18F2420/2520/4420/4520
DS39631E-page 308 © 2008 Microchip Technology Inc.
XORWF Exclusive OR W with f
Syntax: XORWF f {,d {,a}}
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .XOR. (f) → dest
Status Affected: N, Z
Encoding: 0001 10da ffff ffff
Description: Exclusive OR the contents of W with
register ‘f’. If ‘d’ is ‘0’, the result is stored
in W. If ‘d’ is ‘1’, the result is stored back
in the register ‘f’ (default).
If ‘a’ is ‘0’, the Access Bank is selected.
If ‘a’ is ‘1’, the BSR is used to select the
GPR bank (default).
If ‘a’ is ‘0’ and the extended instruction
set is enabled, this instruction operates
in Indexed Literal Offset Addressing
mode whenever f ≤ 95 (5Fh). See
Section 24.2.3 “Byte-Oriented and
Bit-Oriented Instructions in Indexed
Literal Offset Mode” for details.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: XORWF REG, 1, 0
Before Instruction
REG = AFh
W = B5h
After Instruction
REG = 1Ah
W = B5h© 2008 Microchip Technology Inc. DS39631E-page 309
PIC18F2420/2520/4420/4520
24.2 Extended Instruction Set
In addition to the standard 75 instructions of the PIC18
instruction set, PIC18F2420/2520/4420/4520 devices
also provide an optional extension to the core CPU
functionality. The added features include eight additional
instructions that augment indirect and indexed
addressing operations and the implementation of
Indexed Literal Offset Addressing mode for many of the
standard PIC18 instructions.
The additional features of the extended instruction set
are disabled by default. To enable them, users must set
the XINST Configuration bit.
The instructions in the extended set can all be
classified as literal operations, which either manipulate
the File Select Registers, or use them for indexed
addressing. Two of the instructions, ADDFSR and
SUBFSR, each have an additional special instantiation
for using FSR2. These versions (ADDULNK and
SUBULNK) allow for automatic return after execution.
The extended instructions are specifically implemented
to optimize re-entrant program code (that is, code that
is recursive or that uses a software stack) written in
high-level languages, particularly C. Among other
things, they allow users working in high-level
languages to perform certain operations on data
structures more efficiently. These include:
• Dynamic allocation and deallocation of software
stack space when entering and leaving
subroutines
• Function Pointer invocation
• Software Stack Pointer manipulation
• Manipulation of variables located in a software
stack
A summary of the instructions in the extended instruction
set is provided in Table 24-3. Detailed descriptions
are provided in Section 24.2.2 “Extended Instruction
Set”. The opcode field descriptions in Table 24-1
(page 268) apply to both the standard and extended
PIC18 instruction sets.
24.2.1 EXTENDED INSTRUCTION SYNTAX
Most of the extended instructions use indexed arguments,
using one of the File Select Registers and some
offset to specify a source or destination register. When
an argument for an instruction serves as part of
indexed addressing, it is enclosed in square brackets
(“[ ]”). This is done to indicate that the argument is used
as an index or offset. MPASM™ Assembler will flag an
error if it determines that an index or offset value is not
bracketed.
When the extended instruction set is enabled, brackets
are also used to indicate index arguments in byteoriented
and bit-oriented instructions. This is in addition
to other changes in their syntax. For more details, see
Section 24.2.3.1 “Extended Instruction Syntax with
Standard PIC18 Commands”.
TABLE 24-3: EXTENSIONS TO THE PIC18 INSTRUCTION SET
Note: The instruction set extension and the
Indexed Literal Offset Addressing mode
were designed for optimizing applications
written in C; the user may likely never use
these instructions directly in assembler.
The syntax for these commands is provided
as a reference for users who may be
reviewing code that has been generated
by a compiler.
Note: In the past, square brackets have been
used to denote optional arguments in the
PIC18 and earlier instruction sets. In this
text and going forward, optional
arguments are denoted by braces (“{ }”).
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
MSb LSb Affected
ADDFSR
ADDULNK
CALLW
MOVSF
MOVSS
PUSHL
SUBFSR
SUBULNK
f, k
k
zs, fd
zs, zd
k
f, k
k
Add Literal to FSR
Add Literal to FSR2 and Return
Call Subroutine using WREG
Move zs (source) to 1st word
fd (destination) 2nd word
Move zs (source) to 1st word
zd (destination) 2nd word
Store Literal at FSR2,
Decrement FSR2
Subtract Literal from FSR
Subtract Literal from FSR2 and
Return
1
2
2
2
2
1
1
2
1110
1110
0000
1110
1111
1110
1111
1110
1110
1110
1000
1000
0000
1011
ffff
1011
xxxx
1010
1001
1001
ffkk
11kk
0001
0zzz
ffff
1zzz
xzzz
kkkk
ffkk
11kk
kkkk
kkkk
0100
zzzz
ffff
zzzz
zzzz
kkkk
kkkk
kkkk
None
None
None
None
None
None
None
NonePIC18F2420/2520/4420/4520
DS39631E-page 310 © 2008 Microchip Technology Inc.
24.2.2 EXTENDED INSTRUCTION SET
ADDFSR Add Literal to FSR
Syntax: ADDFSR f, k
Operands: 0 ≤ k ≤ 63
f ∈ [ 0, 1, 2 ]
Operation: FSR(f) + k → FSR(f)
Status Affected: None
Encoding: 1110 1000 ffkk kkkk
Description: The 6-bit literal ‘k’ is added to the
contents of the FSR specified by ‘f’.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to
FSR
Example: ADDFSR 2, 23h
Before Instruction
FSR2 = 03FFh
After Instruction
FSR2 = 0422h
ADDULNK Add Literal to FSR2 and Return
Syntax: ADDULNK k
Operands: 0 ≤ k ≤ 63
Operation: FSR2 + k → FSR2,
(TOS) → PC
Status Affected: None
Encoding: 1110 1000 11kk kkkk
Description: The 6-bit literal ‘k’ is added to the
contents of FSR2. A RETURN is then
executed by loading the PC with the
TOS.
The instruction takes two cycles to
execute; a NOP is performed during
the second cycle.
This may be thought of as a special
case of the ADDFSR instruction,
where f = 3 (binary ‘11’); it operates
only on FSR2.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal ‘k’
Process
Data
Write to
FSR
No
Operation
No
Operation
No
Operation
No
Operation
Example: ADDULNK 23h
Before Instruction
FSR2 = 03FFh
PC = 0100h
After Instruction
FSR2 = 0422h
PC = (TOS)
Note: All PIC18 instructions may take an optional label argument preceding the instruction mnemonic for use in
symbolic addressing. If a label is used, the instruction syntax then becomes: {label} instruction argument(s).© 2008 Microchip Technology Inc. DS39631E-page 311
PIC18F2420/2520/4420/4520
CALLW Subroutine Call Using WREG
Syntax: CALLW
Operands: None
Operation: (PC + 2) → TOS,
(W) → PCL,
(PCLATH) → PCH,
(PCLATU) → PCU
Status Affected: None
Encoding: 0000 0000 0001 0100
Description First, the return address (PC + 2) is
pushed onto the return stack. Next, the
contents of W are written to PCL; the
existing value is discarded. Then, the
contents of PCLATH and PCLATU are
latched into PCH and PCU,
respectively. The second cycle is
executed as a NOP instruction while the
new next instruction is fetched.
Unlike CALL, there is no option to
update W, STATUS or BSR.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
WREG
PUSH PC to
stack
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CALLW
Before Instruction
PC = address (HERE)
PCLATH = 10h
PCLATU = 00h
W = 06h
After Instruction
PC = 001006h
TOS = address (HERE + 2)
PCLATH = 10h
PCLATU = 00h
W = 06h
MOVSF Move Indexed to f
Syntax: MOVSF [zs], fd
Operands: 0 ≤ zs ≤ 127
0 ≤ fd ≤ 4095
Operation: ((FSR2) + zs) → fd
Status Affected: None
Encoding:
1st word (source)
2nd word (destin.)
1110
1111
1011
ffff
0zzz
ffff
zzzzs
ffffd
Description: The contents of the source register are
moved to destination register ‘fd’. The
actual address of the source register is
determined by adding the 7-bit literal
offset ‘zs’ in the first word to the value of
FSR2. The address of the destination
register is specified by the 12-bit literal
‘fd’ in the second word. Both addresses
can be anywhere in the 4096-byte data
space (000h to FFFh).
The MOVSF instruction cannot use the
PCL, TOSU, TOSH or TOSL as the
destination register.
If the resultant source address points to
an indirect addressing register, the
value returned will be 00h.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Determine
source addr
Determine
source addr
Read
source reg
Decode No
operation
No dummy
read
No
operation
Write
register ‘f’
(dest)
Example: MOVSF [05h], REG2
Before Instruction
FSR2 = 80h
Contents
of 85h = 33h
REG2 = 11h
After Instruction
FSR2 = 80h
Contents
of 85h = 33h
REG2 = 33hPIC18F2420/2520/4420/4520
DS39631E-page 312 © 2008 Microchip Technology Inc.
MOVSS Move Indexed to Indexed
Syntax: MOVSS [zs], [zd]
Operands: 0 ≤ zs ≤ 127
0 ≤ zd ≤ 127
Operation: ((FSR2) + zs) → ((FSR2) + zd)
Status Affected: None
Encoding:
1st word (source)
2nd word (dest.)
1110
1111
1011
xxxx
1zzz
xzzz
zzzzs
zzzzd
Description The contents of the source register are
moved to the destination register. The
addresses of the source and destination
registers are determined by adding the
7-bit literal offsets ‘zs’ or ‘zd’,
respectively, to the value of FSR2. Both
registers can be located anywhere in
the 4096-byte data memory space
(000h to FFFh).
The MOVSS instruction cannot use the
PCL, TOSU, TOSH or TOSL as the
destination register.
If the resultant source address points to
an indirect addressing register, the
value returned will be 00h. If the
resultant destination address points to
an indirect addressing register, the
instruction will execute as a NOP.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Determine
source addr
Determine
source addr
Read
source reg
Decode Determine
dest addr
Determine
dest addr
Write
to dest reg
Example: MOVSS [05h], [06h]
Before Instruction
FSR2 = 80h
Contents
of 85h = 33h
Contents
of 86h = 11h
After Instruction
FSR2 = 80h
Contents
of 85h = 33h
Contents
of 86h = 33h
PUSHL Store Literal at FSR2, Decrement FSR2
Syntax: PUSHL k
Operands: 0 ≤ k ≤ 255
Operation: k → (FSR2),
FSR2 – 1 → FSR2
Status Affected: None
Encoding: 1111 1010 kkkk kkkk
Description: The 8-bit literal ‘k’ is written to the data
memory address specified by FSR2. FSR2
is decremented by 1 after the operation.
This instruction allows users to push values
onto a software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read ‘k’ Process
data
Write to
destination
Example: PUSHL 08h
Before Instruction
FSR2H:FSR2L = 01ECh
Memory (01ECh) = 00h
After Instruction
FSR2H:FSR2L = 01EBh
Memory (01ECh) = 08h© 2008 Microchip Technology Inc. DS39631E-page 313
PIC18F2420/2520/4420/4520
SUBFSR Subtract Literal from FSR
Syntax: SUBFSR f, k
Operands: 0 ≤ k ≤ 63
f ∈ [ 0, 1, 2 ]
Operation: FSR(f) – k → FSRf
Status Affected: None
Encoding: 1110 1001 ffkk kkkk
Description: The 6-bit literal ‘k’ is subtracted from
the contents of the FSR specified by
‘f’.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: SUBFSR 2, 23h
Before Instruction
FSR2 = 03FFh
After Instruction
FSR2 = 03DCh
SUBULNK Subtract Literal from FSR2 and Return
Syntax: SUBULNK k
Operands: 0 ≤ k ≤ 63
Operation: FSR2 – k → FSR2,
(TOS) → PC
Status Affected: None
Encoding: 1110 1001 11kk kkkk
Description: The 6-bit literal ‘k’ is subtracted from the
contents of the FSR2. A RETURN is then
executed by loading the PC with the TOS.
The instruction takes two cycles to
execute; a NOP is performed during the
second cycle.
This may be thought of as a special case of
the SUBFSR instruction, where f = 3 (binary
‘11’); it operates only on FSR2.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
No
Operation
No
Operation
No
Operation
No
Operation
Example: SUBULNK 23h
Before Instruction
FSR2 = 03FFh
PC = 0100h
After Instruction
FSR2 = 03DCh
PC = (TOS)PIC18F2420/2520/4420/4520
DS39631E-page 314 © 2008 Microchip Technology Inc.
24.2.3 BYTE-ORIENTED AND
BIT-ORIENTED INSTRUCTIONS IN
INDEXED LITERAL OFFSET MODE
In addition to eight new commands in the extended set,
enabling the extended instruction set also enables
Indexed Literal Offset Addressing mode (Section 5.5.1
“Indexed Addressing with Literal Offset”). This has
a significant impact on the way that many commands of
the standard PIC18 instruction set are interpreted.
When the extended set is disabled, addresses embedded
in opcodes are treated as literal memory locations:
either as a location in the Access Bank (‘a’ = 0), or in a
GPR bank designated by the BSR (‘a’ = 1). When the
extended instruction set is enabled and ‘a’ = 0, however,
a file register argument of 5Fh or less is
interpreted as an offset from the pointer value in FSR2
and not as a literal address. For practical purposes, this
means that all instructions that use the Access RAM bit
as an argument – that is, all byte-oriented and bitoriented
instructions, or almost half of the core PIC18
instructions – may behave differently when the
extended instruction set is enabled.
When the content of FSR2 is 00h, the boundaries of the
Access RAM are essentially remapped to their original
values. This may be useful in creating backward
compatible code. If this technique is used, it may be
necessary to save the value of FSR2 and restore it
when moving back and forth between C and assembly
routines in order to preserve the Stack Pointer. Users
must also keep in mind the syntax requirements of the
extended instruction set (see Section 24.2.3.1
“Extended Instruction Syntax with Standard PIC18
Commands”).
Although the Indexed Literal Offset Addressing mode
can be very useful for dynamic stack and pointer
manipulation, it can also be very annoying if a simple
arithmetic operation is carried out on the wrong
register. Users who are accustomed to the PIC18 programming
must keep in mind that, when the extended
instruction set is enabled, register addresses of 5Fh or
less are used for Indexed Literal Offset Addressing.
Representative examples of typical byte-oriented and
bit-oriented instructions in the Indexed Literal Offset
Addressing mode are provided on the following page to
show how execution is affected. The operand conditions
shown in the examples are applicable to all
instructions of these types.
24.2.3.1 Extended Instruction Syntax with
Standard PIC18 Commands
When the extended instruction set is enabled, the file
register argument, ‘f’, in the standard byte-oriented and
bit-oriented commands is replaced with the literal offset
value, ‘k’. As already noted, this occurs only when ‘f’ is
less than or equal to 5Fh. When an offset value is used,
it must be indicated by square brackets (“[ ]”). As with
the extended instructions, the use of brackets indicates
to the compiler that the value is to be interpreted as an
index or an offset. Omitting the brackets, or using a
value greater than 5Fh within brackets, will generate an
error in the MPASM Assembler.
If the index argument is properly bracketed for Indexed
Literal Offset Addressing, the Access RAM argument is
never specified; it will automatically be assumed to be
‘0’. This is in contrast to standard operation (extended
instruction set disabled) when ‘a’ is set on the basis of
the target address. Declaring the Access RAM bit in
this mode will also generate an error in the MPASM
Assembler.
The destination argument, ‘d’, functions as before.
In the latest versions of the MPASM assembler,
language support for the extended instruction set must
be explicitly invoked. This is done with either the
command line option, /y, or the PE directive in the
source listing.
24.2.4 CONSIDERATIONS WHEN
ENABLING THE EXTENDED
INSTRUCTION SET
It is important to note that the extensions to the instruction
set may not be beneficial to all users. In particular,
users who are not writing code that uses a software
stack may not benefit from using the extensions to the
instruction set.
Additionally, the Indexed Literal Offset Addressing
mode may create issues with legacy applications
written to the PIC18 assembler. This is because
instructions in the legacy code may attempt to address
registers in the Access Bank below 5Fh. Since these
addresses are interpreted as literal offsets to FSR2
when the instruction set extension is enabled, the
application may read or write to the wrong data
addresses.
When porting an application to the PIC18F2420/2520/
4420/4520, it is very important to consider the type of
code. A large, re-entrant application that is written in ‘C’
and would benefit from efficient compilation will do well
when using the instruction set extensions. Legacy
applications that heavily use the Access Bank will most
likely not benefit from using the extended instruction
set.
Note: Enabling the PIC18 instruction set
extension may cause legacy applications
to behave erratically or fail entirely. © 2008 Microchip Technology Inc. DS39631E-page 315
PIC18F2420/2520/4420/4520
ADDWF ADD W to Indexed
(Indexed Literal Offset mode)
Syntax: ADDWF [k] {,d}
Operands: 0 ≤ k ≤ 95
d ∈ [0,1]
Operation: (W) + ((FSR2) + k) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0010 01d0 kkkk kkkk
Description: The contents of W are added to the
contents of the register indicated by
FSR2, offset by the value ‘k’.
If ‘d’ is ‘0’, the result is stored in W. If ‘d’
is ‘1’, the result is stored back in
register ‘f’ (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read ‘k’ Process
Data
Write to
destination
Example: ADDWF [OFST] , 0
Before Instruction
W = 17h
OFST = 2Ch
FSR2 = 0A00h
Contents
of 0A2Ch = 20h
After Instruction
W = 37h
Contents
of 0A2Ch = 20h
BSF Bit Set Indexed
(Indexed Literal Offset mode)
Syntax: BSF [k], b
Operands: 0 ≤ f ≤ 95
0 ≤ b ≤ 7
Operation: 1 → ((FSR2) + k)
Status Affected: None
Encoding: 1000 bbb0 kkkk kkkk
Description: Bit ‘b’ of the register indicated by FSR2,
offset by the value ‘k’, is set.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register ‘f’
Process
Data
Write to
destination
Example: BSF [FLAG_OFST], 7
Before Instruction
FLAG_OFST = 0Ah
FSR2 = 0A00h
Contents
of 0A0Ah = 55h
After Instruction
Contents
of 0A0Ah = D5h
SETF Set Indexed
(Indexed Literal Offset mode)
Syntax: SETF [k]
Operands: 0 ≤ k ≤ 95
Operation: FFh → ((FSR2) + k)
Status Affected: None
Encoding: 0110 1000 kkkk kkkk
Description: The contents of the register indicated by
FSR2, offset by ‘k’, are set to FFh.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read ‘k’ Process
Data
Write
register
Example: SETF [OFST]
Before Instruction
OFST = 2Ch
FSR2 = 0A00h
Contents
of 0A2Ch = 00h
After Instruction
Contents
of 0A2Ch = FFhPIC18F2420/2520/4420/4520
DS39631E-page 316 © 2008 Microchip Technology Inc.
24.2.5 SPECIAL CONSIDERATIONS WITH
MICROCHIP MPLAB® IDE TOOLS
The latest versions of Microchip’s software tools have
been designed to fully support the extended instruction
set of the PIC18F2420/2520/4420/4520 family of
devices. This includes the MPLAB C18 C compiler,
MPASM assembly language and MPLAB Integrated
Development Environment (IDE).
When selecting a target device for software
development, MPLAB IDE will automatically set default
Configuration bits for that device. The default setting for
the XINST Configuration bit is ‘0’, disabling the
extended instruction set and Indexed Literal Offset
Addressing mode. For proper execution of applications
developed to take advantage of the extended
instruction set, XINST must be set during
programming.
To develop software for the extended instruction set,
the user must enable support for the instructions and
the Indexed Addressing mode in their language tool(s).
Depending on the environment being used, this may be
done in several ways:
• A menu option, or dialog box within the
environment, that allows the user to configure the
language tool and its settings for the project
• A command line option
• A directive in the source code
These options vary between different compilers,
assemblers and development environments. Users are
encouraged to review the documentation accompanying
their development systems for the appropriate
information.© 2008 Microchip Technology Inc. DS39631E-page 317
PIC18F2420/2520/4420/4520
25.0 DEVELOPMENT SUPPORT
The PIC® microcontrollers are supported with a full
range of hardware and software development tools:
• Integrated Development Environment
- MPLAB® IDE Software
• Assemblers/Compilers/Linkers
- MPASMTM Assembler
- MPLAB C18 and MPLAB C30 C Compilers
- MPLINKTM Object Linker/
MPLIBTM Object Librarian
- MPLAB ASM30 Assembler/Linker/Library
• Simulators
- MPLAB SIM Software Simulator
• Emulators
- MPLAB ICE 2000 In-Circuit Emulator
- MPLAB REAL ICE™ In-Circuit Emulator
• In-Circuit Debugger
- MPLAB ICD 2
• Device Programmers
- PICSTART® Plus Development Programmer
- MPLAB PM3 Device Programmer
- PICkit™ 2 Development Programmer
• Low-Cost Demonstration and Development
Boards and Evaluation Kits
25.1 MPLAB Integrated Development
Environment Software
The MPLAB IDE software brings an ease of software
development previously unseen in the 8/16-bit microcontroller
market. The MPLAB IDE is a Windows®
operating system-based application that contains:
• A single graphical interface to all debugging tools
- Simulator
- Programmer (sold separately)
- Emulator (sold separately)
- In-Circuit Debugger (sold separately)
• A full-featured editor with color-coded context
• A multiple project manager
• Customizable data windows with direct edit of
contents
• High-level source code debugging
• Visual device initializer for easy register
initialization
• Mouse over variable inspection
• Drag and drop variables from source to watch
windows
• Extensive on-line help
• Integration of select third party tools, such as
HI-TECH Software C Compilers and IAR
C Compilers
The MPLAB IDE allows you to:
• Edit your source files (either assembly or C)
• One touch assemble (or compile) and download
to PIC MCU emulator and simulator tools
(automatically updates all project information)
• Debug using:
- Source files (assembly or C)
- Mixed assembly and C
- Machine code
MPLAB IDE supports multiple debugging tools in a
single development paradigm, from the cost-effective
simulators, through low-cost in-circuit debuggers, to
full-featured emulators. This eliminates the learning
curve when upgrading to tools with increased flexibility
and power.PIC18F2420/2520/4420/4520
DS39631E-page 318 © 2008 Microchip Technology Inc.
25.2 MPASM Assembler
The MPASM Assembler is a full-featured, universal
macro assembler for all PIC MCUs.
The MPASM Assembler generates relocatable object
files for the MPLINK Object Linker, Intel® standard HEX
files, MAP files to detail memory usage and symbol
reference, absolute LST files that contain source lines
and generated machine code and COFF files for
debugging.
The MPASM Assembler features include:
• Integration into MPLAB IDE projects
• User-defined macros to streamline
assembly code
• Conditional assembly for multi-purpose
source files
• Directives that allow complete control over the
assembly process
25.3 MPLAB C18 and MPLAB C30
C Compilers
The MPLAB C18 and MPLAB C30 Code Development
Systems are complete ANSI C compilers for
Microchip’s PIC18 and PIC24 families of microcontrollers
and the dsPIC30 and dsPIC33 family of digital
signal controllers. These compilers provide powerful
integration capabilities, superior code optimization and
ease of use not found with other compilers.
For easy source level debugging, the compilers provide
symbol information that is optimized to the MPLAB IDE
debugger.
25.4 MPLINK Object Linker/
MPLIB Object Librarian
The MPLINK Object Linker combines relocatable
objects created by the MPASM Assembler and the
MPLAB C18 C Compiler. It can link relocatable objects
from precompiled libraries, using directives from a
linker script.
The MPLIB Object Librarian manages the creation and
modification of library files of precompiled code. When
a routine from a library is called from a source file, only
the modules that contain that routine will be linked in
with the application. This allows large libraries to be
used efficiently in many different applications.
The object linker/library features include:
• Efficient linking of single libraries instead of many
smaller files
• Enhanced code maintainability by grouping
related modules together
• Flexible creation of libraries with easy module
listing, replacement, deletion and extraction
25.5 MPLAB ASM30 Assembler, Linker
and Librarian
MPLAB ASM30 Assembler produces relocatable
machine code from symbolic assembly language for
dsPIC30F devices. MPLAB C30 C Compiler uses the
assembler to produce its object file. The assembler
generates relocatable object files that can then be
archived or linked with other relocatable object files and
archives to create an executable file. Notable features
of the assembler include:
• Support for the entire dsPIC30F instruction set
• Support for fixed-point and floating-point data
• Command line interface
• Rich directive set
• Flexible macro language
• MPLAB IDE compatibility
25.6 MPLAB SIM Software Simulator
The MPLAB SIM Software Simulator allows code
development in a PC-hosted environment by simulating
the PIC MCUs and dsPIC® DSCs on an instruction
level. On any given instruction, the data areas can be
examined or modified and stimuli can be applied from
a comprehensive stimulus controller. Registers can be
logged to files for further run-time analysis. The trace
buffer and logic analyzer display extend the power of
the simulator to record and track program execution,
actions on I/O, most peripherals and internal registers.
The MPLAB SIM Software Simulator fully supports
symbolic debugging using the MPLAB C18 and
MPLAB C30 C Compilers, and the MPASM and
MPLAB ASM30 Assemblers. The software simulator
offers the flexibility to develop and debug code outside
of the hardware laboratory environment, making it an
excellent, economical software development tool. © 2008 Microchip Technology Inc. DS39631E-page 319
PIC18F2420/2520/4420/4520
25.7 MPLAB ICE 2000
High-Performance
In-Circuit Emulator
The MPLAB ICE 2000 In-Circuit Emulator is intended
to provide the product development engineer with a
complete microcontroller design tool set for PIC
microcontrollers. Software control of the MPLAB ICE
2000 In-Circuit Emulator is advanced by the MPLAB
Integrated Development Environment, which allows
editing, building, downloading and source debugging
from a single environment.
The MPLAB ICE 2000 is a full-featured emulator
system with enhanced trace, trigger and data monitoring
features. Interchangeable processor modules allow
the system to be easily reconfigured for emulation of
different processors. The architecture of the MPLAB
ICE 2000 In-Circuit Emulator allows expansion to
support new PIC microcontrollers.
The MPLAB ICE 2000 In-Circuit Emulator system has
been designed as a real-time emulation system with
advanced features that are typically found on more
expensive development tools. The PC platform and
Microsoft® Windows® 32-bit operating system were
chosen to best make these features available in a
simple, unified application.
25.8 MPLAB REAL ICE In-Circuit
Emulator System
MPLAB REAL ICE In-Circuit Emulator System is
Microchip’s next generation high-speed emulator for
Microchip Flash DSC and MCU devices. It debugs and
programs PIC® Flash MCUs and dsPIC® Flash DSCs
with the easy-to-use, powerful graphical user interface of
the MPLAB Integrated Development Environment (IDE),
included with each kit.
The MPLAB REAL ICE probe is connected to the design
engineer’s PC using a high-speed USB 2.0 interface and
is connected to the target with either a connector
compatible with the popular MPLAB ICD 2 system
(RJ11) or with the new high-speed, noise tolerant, LowVoltage
Differential Signal (LVDS) interconnection
(CAT5).
MPLAB REAL ICE is field upgradeable through future
firmware downloads in MPLAB IDE. In upcoming
releases of MPLAB IDE, new devices will be supported,
and new features will be added, such as software breakpoints
and assembly code trace. MPLAB REAL ICE
offers significant advantages over competitive emulators
including low-cost, full-speed emulation, real-time
variable watches, trace analysis, complex breakpoints, a
ruggedized probe interface and long (up to three meters)
interconnection cables.
25.9 MPLAB ICD 2 In-Circuit Debugger
Microchip’s In-Circuit Debugger, MPLAB ICD 2, is a
powerful, low-cost, run-time development tool,
connecting to the host PC via an RS-232 or high-speed
USB interface. This tool is based on the Flash PIC
MCUs and can be used to develop for these and other
PIC MCUs and dsPIC DSCs. The MPLAB ICD 2 utilizes
the in-circuit debugging capability built into the Flash
devices. This feature, along with Microchip’s In-Circuit
Serial ProgrammingTM (ICSPTM) protocol, offers costeffective,
in-circuit Flash debugging from the graphical
user interface of the MPLAB Integrated Development
Environment. This enables a designer to develop and
debug source code by setting breakpoints, single stepping
and watching variables, and CPU status and
peripheral registers. Running at full speed enables
testing hardware and applications in real time. MPLAB
ICD 2 also serves as a development programmer for
selected PIC devices.
25.10 MPLAB PM3 Device Programmer
The MPLAB PM3 Device Programmer is a universal,
CE compliant device programmer with programmable
voltage verification at VDDMIN and VDDMAX for
maximum reliability. It features a large LCD display
(128 x 64) for menus and error messages and a modular,
detachable socket assembly to support various
package types. The ICSP™ cable assembly is included
as a standard item. In Stand-Alone mode, the MPLAB
PM3 Device Programmer can read, verify and program
PIC devices without a PC connection. It can also set
code protection in this mode. The MPLAB PM3
connects to the host PC via an RS-232 or USB cable.
The MPLAB PM3 has high-speed communications and
optimized algorithms for quick programming of large
memory devices and incorporates an SD/MMC card for
file storage and secure data applications.PIC18F2420/2520/4420/4520
DS39631E-page 320 © 2008 Microchip Technology Inc.
25.11 PICSTART Plus Development
Programmer
The PICSTART Plus Development Programmer is an
easy-to-use, low-cost, prototype programmer. It
connects to the PC via a COM (RS-232) port. MPLAB
Integrated Development Environment software makes
using the programmer simple and efficient. The
PICSTART Plus Development Programmer supports
most PIC devices in DIP packages up to 40 pins.
Larger pin count devices, such as the PIC16C92X and
PIC17C76X, may be supported with an adapter socket.
The PICSTART Plus Development Programmer is CE
compliant.
25.12 PICkit 2 Development Programmer
The PICkit™ 2 Development Programmer is a low-cost
programmer and selected Flash device debugger with
an easy-to-use interface for programming many of
Microchip’s baseline, mid-range and PIC18F families of
Flash memory microcontrollers. The PICkit 2 Starter Kit
includes a prototyping development board, twelve
sequential lessons, software and HI-TECH’s PICC™
Lite C compiler, and is designed to help get up to speed
quickly using PIC® microcontrollers. The kit provides
everything needed to program, evaluate and develop
applications using Microchip’s powerful, mid-range
Flash memory family of microcontrollers.
25.13 Demonstration, Development and
Evaluation Boards
A wide variety of demonstration, development and
evaluation boards for various PIC MCUs and dsPIC
DSCs allows quick application development on fully functional
systems. Most boards include prototyping areas for
adding custom circuitry and provide application firmware
and source code for examination and modification.
The boards support a variety of features, including LEDs,
temperature sensors, switches, speakers, RS-232
interfaces, LCD displays, potentiometers and additional
EEPROM memory.
The demonstration and development boards can be
used in teaching environments, for prototyping custom
circuits and for learning about various microcontroller
applications.
In addition to the PICDEM™ and dsPICDEM™ demonstration/development
board series of circuits, Microchip
has a line of evaluation kits and demonstration software
for analog filter design, KEELOQ® security ICs, CAN,
IrDA®, PowerSmart battery management, SEEVAL®
evaluation system, Sigma-Delta ADC, flow rate
sensing, plus many more.
Check the Microchip web page (www.microchip.com)
for the complete list of demonstration, development
and evaluation kits.© 2008 Microchip Technology Inc. DS39631E-page 321
PIC18F2420/2520/4420/4520
26.0 ELECTRICAL CHARACTERISTICS
Absolute Maximum Ratings(†)
Ambient temperature under bias.............................................................................................................-40°C to +125°C
Storage temperature .............................................................................................................................. -65°C to +150°C
Voltage on any pin with respect to VSS (except VDD and MCLR) ................................................... -0.3V to (VDD + 0.3V)
Voltage on VDD with respect to VSS ......................................................................................................... -0.3V to +7.5V
Voltage on MCLR with respect to VSS (Note 2) ......................................................................................... 0V to +13.25V
Total power dissipation (Note 1) ...............................................................................................................................1.0W
Maximum current out of VSS pin ...........................................................................................................................300 mA
Maximum current into VDD pin ..............................................................................................................................250 mA
Input clamp current, IIK (VI < 0 or VI > VDD)...................................................................................................................... ±20 mA
Output clamp current, IOK (VO < 0 or VO > VDD) .............................................................................................................. ±20 mA
Maximum output current sunk by any I/O pin..........................................................................................................25 mA
Maximum output current sourced by any I/O pin ....................................................................................................25 mA
Maximum current sunk by all ports .......................................................................................................................200 mA
Maximum current sourced by all ports ..................................................................................................................200 mA
Note 1: Power dissipation is calculated as follows:
Pdis = VDD x {IDD – ∑ IOH} + ∑ {(VDD – VOH) x IOH} + ∑(VOL x IOL)
2: Voltage spikes below VSS at the MCLR/VPP/RE3 pin, inducing currents greater than 80 mA, may cause
latch-up. Thus, a series resistor of 50-100Ω should be used when applying a “low” level to the MCLR/VPP/
RE3 pin, rather than pulling this pin directly to VSS.
† NOTICE: Stresses above those listed under “Absolute Maximum Ratings” may cause permanent damage to the
device. This is a stress rating only and functional operation of the device at those or any other conditions above those
indicated in the operation listings of this specification is not implied. Exposure to maximum rating conditions for
extended periods may affect device reliability.PIC18F2420/2520/4420/4520
DS39631E-page 322 © 2008 Microchip Technology Inc.
FIGURE 26-1: PIC18F2420/2520/4420/4520 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
FIGURE 26-2: PIC18F2420/2520/4420/4520 VOLTAGE-FREQUENCY GRAPH (EXTENDED)
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
4.2V
PIC18F2420/2520/4420/4520
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
25 MHz
5.0V
3.5V
3.0V
2.5V
4.2V
PIC18F2420/2520/4420/4520© 2008 Microchip Technology Inc. DS39631E-page 323
PIC18F2420/2520/4420/4520
FIGURE 26-3: PIC18LF2420/2520/4420/4520 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
FMAX = (16.36 MHz/V) (VDDAPPMIN – 2.0V) + 4 MHz
Note: VDDAPPMIN is the minimum voltage of the PIC® device in the application.
4 MHz
4.2V
PIC18LF2420/2520/4420/4520PIC18F2420/2520/4420/4520
DS39631E-page 324 © 2008 Microchip Technology Inc.
26.1 DC Characteristics: Supply Voltage
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
D001 VDD Supply Voltage
PIC18LF2X2X/4X20 2.0 — 5.5 V HS, XT, RC and LP Oscillator mode
PIC18F2X20/4X20 4.2 — 5.5 V
D002 VDR RAM Data Retention
Voltage(1)
1.5 — — V
D003 VPOR VDD Start Voltage
to Ensure Internal
Power-on Reset Signal
— — 0.7 V See section on Power-on Reset for details
D004 SVDD VDD Rise Rate
to Ensure Internal
Power-on Reset Signal
0.05 — — V/ms See section on Power-on Reset for details
VBOR Brown-out Reset Voltage
D005 PIC18LF2X2X/4X20
BORV<1:0> = 11 2.00 2.11 2.22 V
BORV<1:0> = 10 2.65 2.79 2.93 V
D005 All Devices
BORV<1:0> = 01(2) 4.11 4.33 4.55 V
BORV<1:0> = 00 4.36 4.59 4.82 V
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in Sleep mode, or during a device Reset, without losing RAM data.
2: With BOR enabled, full-speed operation (FOSC = 40 MHz) is supported until a BOR occurs. This is valid although
VDD may be below the minimum voltage for this frequency.© 2008 Microchip Technology Inc. DS39631E-page 325
PIC18F2420/2520/4420/4520
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Power-Down Current (IPD)
(1)
PIC18LF2X2X/4X20 0.1 0.5 μA -40°C
VDD = 2.0V
(Sleep mode) 0.1 0.5 μA +25°C
0.2 2.5 μA +85°C
PIC18LF2X2X/4X20 0.1 0.7 μA -40°C
VDD = 3.0V
(Sleep mode) 0.1 0.7 μA +25°C
0.3 3.5 μA +85°C
All devices 0.1 1.0 μA -40°C
VDD = 5.0V
(Sleep mode)
0.2 1.0 μA +25°C
0.7 10 μA +85°C
Extended devices only 10 100 μA +125°C
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.PIC18F2420/2520/4420/4520
DS39631E-page 326 © 2008 Microchip Technology Inc.
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 13 25 μA -40°C
VDD = 2.0V
FOSC = 31 kHz
(RC_RUN mode,
INTRC source)
13 22 μA +25°C
14 25 μA +85°C
PIC18LF2X2X/4X20 42 61 μA -40°C
34 46 μA +25°C VDD = 3.0V
28 45 μA +85°C
All devices 103 160 μA -40°C
VDD = 5.0V
82 130 μA +25°C
67 120 μA +85°C
Extended devices only 71 230 μA +125°C
PIC18LF2X2X/4X20 320 440 μA -40°C
VDD = 2.0V
FOSC = 1 MHz
(RC_RUN mode,
INTOSC source)
330 440 μA +25°C
330 440 μA +85°C
PIC18LF2X2X/4X20 630 800 μA -40°C
590 720 μA +25°C VDD = 3.0V
570 700 μA +85°C
All devices 1.2 1.6 mA -40°C
VDD = 5.0V
1.0 1.5 mA +25°C
1.0 1.5 mA +85°C
Extended devices only 1.0 1.5 mA +125°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.© 2008 Microchip Technology Inc. DS39631E-page 327
PIC18F2420/2520/4420/4520
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 0.8 1.1 mA -40°C
VDD = 2.0V
FOSC = 4 MHz
(RC_RUN mode,
INTOSC source)
0.8 1.1 mA +25°C
0.8 1.1 mA +85°C
PIC18LF2X2X/4X20 1.3 1.7 mA -40°C
1.3 1.7 mA +25°C VDD = 3.0V
1.3 1.7 mA +85°C
All devices 2.5 3.5 mA -40°C
VDD = 5.0V
2.5 3.5 mA +25°C
2.5 3.5 mA +85°C
Extended devices only 2.5 3.5 mA +125°C
PIC18LF2X2X/4X20 2.9 5 μA -40°C
VDD = 2.0V
FOSC = 31 kHz
(RC_IDLE mode,
INTRC source)
3.1 5 μA +25°C
3.6 9.5 μA +85°C
PIC18LF2X2X/4X20 4.5 8 μA -40°C
4.8 8 μA +25°C VDD = 3.0V
5.8 15 μA +85°C
All devices 9.2 16 μA -40°C
VDD = 5.0V
9.8 16 μA +25°C
11.0 35 μA +85°C
Extended devices only 21 160 μA +125°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.PIC18F2420/2520/4420/4520
DS39631E-page 328 © 2008 Microchip Technology Inc.
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 165 250 μA -40°C
VDD = 2.0V
FOSC = 1 MHz
(RC_IDLE mode,
INTOSC source)
175 250 μA +25°C
190 270 μA +85°C
PIC18LF2X2X/4X20 250 360 μA -40°C
270 360 μA +25°C VDD = 3.0V
290 380 μA +85°C
All devices 500 700 μA -40°C
VDD = 5.0V
520 700 μA +25°C
550 700 μA +85°C
Extended devices only 0.6 1 mA +125°C
PIC18LF2X2X/4X20 340 500 μA -40°C
VDD = 2.0V
FOSC = 4 MHz
(RC_IDLE mode,
INTOSC source)
350 500 μA +25°C
360 500 μA +85°C
PIC18LF2X2X/4X20 520 800 μA -40°C
540 800 μA +25°C VDD = 3.0V
580 850 μA +85°C
All devices 1.0 1.6 mA -40°C
VDD = 5.0V
1.1 1.4 mA +25°C
1.1 1.4 mA +85°C
Extended devices only 1.1 2.0 mA +125°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.© 2008 Microchip Technology Inc. DS39631E-page 329
PIC18F2420/2520/4420/4520
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 250 350 μA -40°C
VDD = 2.0V
FOSC = 1 MHZ
(PRI_RUN,
EC oscillator)
260 350 μA +25°C
250 350 μA +85°C
PIC18LF2X2X/4X20 550 650 μA -40°C
480 640 μA +25°C VDD = 3.0V
460 600 μA +85°C
All devices 1.2 1.5 mA -40°C
VDD = 5.0V
1.1 1.4 mA +25°C
1.0 1.3 mA +85°C
Extended devices only 1.0 3.0 mA +125°C
PIC18LF2X2X/4X20 0.72 1.0 mA -40°C
VDD = 2.0V
FOSC = 4 MHz
(PRI_RUN,
EC oscillator)
0.74 1.0 mA +25°C
0.74 1.0 mA +85°C
PIC18LF2X2X/4X20 1.3 1.8 mA -40°C
1.3 1.8 mA +25°C VDD = 3.0V
1.3 1.8 mA +85°C
All devices 2.7 4.0 mA -40°C
VDD = 5.0V
2.6 4.0 mA +25°C
2.5 4.0 mA +85°C
Extended devices only 2.6 5.0 mA +125°C
Extended devices only 8.4 13 mA +125°C VDD = 4.2V FOSC = 25 MHz
(PRI_RUN,
EC oscillator)
11 16 mA +125°C VDD = 5.0V
All devices 15 20 mA -40°C
VDD = 4.2V
FOSC = 40 MHZ
(PRI_RUN,
EC oscillator)
15 20 mA +25°C
15 20 mA +85°C
All devices 20 25 mA -40°C
20 25 mA +25°C VDD = 5.0V
20 25 mA +85°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.PIC18F2420/2520/4420/4520
DS39631E-page 330 © 2008 Microchip Technology Inc.
Supply Current (IDD)
(2)
All devices 7.5 10 mA -40°C
VDD = 4.2V
FOSC = 4 MHZ,
16 MHz internal
(PRI_RUN HS+PLL)
7.4 10 mA +25°C
7.3 10 mA +85°C
Extended devices only 8.0 12 mA +125°C
All devices 10 12 mA -40°C
VDD = 5.0V
FOSC = 4 MHZ,
16 MHz internal
(PRI_RUN HS+PLL)
10 12 mA +25°C
9.7 12 mA +85°C
Extended devices only 10 14 mA +125°C
All devices 15 20 mA -40°C
VDD = 4.2V
FOSC = 10 MHZ,
40 MHz internal
(PRI_RUN HS+PLL)
15 20 mA +25°C
15 20 mA +85°C
All devices 20 25 mA -40°C
VDD = 5.0V
FOSC = 10 MHZ,
40 MHz internal
(PRI_RUN HS+PLL)
20 25 mA +25°C
20 25 mA +85°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.© 2008 Microchip Technology Inc. DS39631E-page 331
PIC18F2420/2520/4420/4520
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 65 100 μA -40°C
VDD = 2.0V
FOSC = 1 MHz
(PRI_IDLE mode,
EC oscillator)
65 100 μA +25°C
70 110 μA +85°C
PIC18LF2X2X/4X20 120 140 μA -40°C
120 140 μA +25°C VDD = 3.0V
130 160 μA +85°C
All devices 230 300 μA -40°C
VDD = 5.0V
235 300 μA +25°C
240 300 μA +85°C
Extended devices only 260 500 μA +125°C
PIC18LF2X2X/4X20 260 360 μA -40°C
VDD = 2.0V
FOSC = 4 MHz
(PRI_IDLE mode,
EC oscillator)
255 360 μA +25°C
270 360 μA +85°C
PIC18LF2X2X/4X20 420 620 μA -40°C
430 620 μA +25°C VDD = 3.0V
450 650 μA +85°C
All devices 0.9 1.2 mA -40°C
VDD = 5.0V
0.9 1.2 mA +25°C
0.9 1.2 mA +85°C
Extended devices only 1 1.3 mA +125°C
Extended devices only 2.8 6.0 mA +125°C VDD = 4.2V FOSC = 25 MHz
(PRI_IDLE mode,
EC oscillator)
4.3 8.0 mA +125°C VDD = 5.0V
All devices 6.0 10 mA -40°C
VDD = 4.2V
FOSC = 40 MHz
(PRI_IDLE mode,
EC oscillator)
6.2 10 mA +25°C
6.6 10 mA +85°C
All devices 8.1 13 mA -40°C
9.1 12 mA +25°C VDD = 5.0V
8.3 12 mA +85°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.PIC18F2420/2520/4420/4520
DS39631E-page 332 © 2008 Microchip Technology Inc.
Supply Current (IDD)
(2)
PIC18LF2X2X/4X20 10 25 μA -40°C(3)
VDD = 2.0V
FOSC = 32 kHz(3)
(SEC_RUN mode,
Timer1 as clock)
11 21 μA +25°C
12 25 μA +85°C
PIC18LF2X2X/4X20 42 57 μA -40°C(3)
33 45 μA +25°C VDD = 3.0V
29 45 μA +85°C
All devices 105 150 μA -40°C(3)
81 130 μA +25°C VDD = 5.0V
67 130 μA +85°C
PIC18LF2X2X/4X20 3.0 12 μA -40°C(3)
VDD = 2.0V
FOSC = 32 kHz(3)
(SEC_IDLE mode,
Timer1 as clock)
3.0 6 μA +25°C
3.7 10 μA +85°C
PIC18LF2X2X/4X20 5.0 15 μA -40°C(3)
5.4 10 μA +25°C VDD = 3.0V
6.3 15 μA +85°C
All devices 8.5 25 μA -40°C(3)
9.0 20 μA +25°C VDD = 5.0V
10.5 30 μA +85°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.© 2008 Microchip Technology Inc. DS39631E-page 333
PIC18F2420/2520/4420/4520
Module Differential Currents (ΔIWDT, ΔIBOR, ΔILVD, ΔIOSCB, ΔIAD)
D026
(ΔIAD)
A/D Converter 0.2 1.0 μA -40°C to +85°C VDD = 2.0V
A/D on, not converting
0.2 1.0 μA -40°C to +85°C VDD = 3.0V
0.2 1.0 μA -40°C to +85°C
VDD = 5.0V
0.5 4.0 μA -40°C to +125°C
D022
(ΔIWDT)
Watchdog Timer 1.3 2.2 μA -40°C
1.4 2.2 μA +25°C VDD = 2.0V
1.6 2.3 μA +85°C
1.9 3.5 μA -40°C
2.0 3.5 μA +25°C VDD = 3.0V
2.2 3.5 μA +85°C
3.0 7.5 μA -40°C
VDD = 5.0V
3.5 7.5 μA +25°C
3.5 7.8 μA +85°C
4.0 10 μA +125°C
D022A
(ΔIBOR)
Brown-out Reset(4) 35 50 μA -40°C to +85°C VDD = 3.0V
40 55 μA -40°C to +85°C
VDD = 5.0V
55 65 μA -40°C to +125°C
0 2 μA -40°C to +85°C Sleep mode,
0 5 μA -40°C to +125°C BOREN<1:0> = 10
D022B
(ΔILVD)
High/Low-Voltage
Detect(4)
22 38 μA -40°C to +85°C VDD = 2.0V
25 40 μA -40°C to +85°C VDD = 3.0V
29 45 μA -40°C to +85°C
VDD = 5.0V
30 45 μA -40°C to +125°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.PIC18F2420/2520/4420/4520
DS39631E-page 334 © 2008 Microchip Technology Inc.
D025L
(ΔIOSCB)
Timer1 Oscillator 4.5 9.0 μA -40°C(3)
VDD = 2.0V 32 kHz on Timer1
0.9 1.6 μA -10°C
0.9 1.6 μA +25°C
0.9 1.8 μA +85°C
4.8 10 μA -40°C(3)
VDD = 3.0V 32 kHz on Timer1
1.0 2.0 μA -10°C
1.0 2.0 μA +25°C
1.0 2.6 μA +85°C
6.0 11 μA -40°C(3)
VDD = 5.0V 32 kHz on Timer1
1.6 4.0 μA -10°C
1.6 4.0 μA +25°C
1.6 4.0 μA +85°C
26.2 DC Characteristics: Power-Down and Supply Current
PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Device Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: The power-down current in Sleep mode does not depend on the oscillator type. Power-down current is measured
with the part in Sleep mode, with all I/O pins in high-impedance state and tied to VDD or VSS and all features that
add delta current disabled (such as WDT, Timer1 Oscillator, BOR, etc.).
2: The supply current is mainly a function of operating voltage, frequency and mode. Other factors, such as I/O pin
loading and switching rate, oscillator type and circuit, internal code execution pattern and temperature, also have
an impact on the current consumption.
The test conditions for all IDD measurements in active operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD or VSS;
MCLR = VDD; WDT enabled/disabled as specified.
3: When operation below -10°C is expected, use T1OSC High-Power mode, where LPT1OSC (CONFIG3H<2>) = 0.
When operation will always be above -10°C, then the low-power Timer1 oscillator may be selected.
4: BOR and HLVD enable internal band gap reference. With both modules enabled, current consumption will be less
than the sum of both specifications.© 2008 Microchip Technology Inc. DS39631E-page 335
PIC18F2420/2520/4420/4520
26.3 DC Characteristics: PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial)
DC CHARACTERISTICS Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Symbol Characteristic Min Max Units Conditions
VIL Input Low Voltage
I/O Ports:
D030 with TTL Buffer VSS 0.15 VDD V VDD < 4.5V
D030A — 0.8 V 4.5V ≤ VDD ≤ 5.5V
D031 with Schmitt Trigger Buffer VSS 0.2 VDD V
D031A RC3 and RC4 VSS 0.3 VDD V I2C™ enabled
D031B VSS 0.8 V SMBus enabled
D032 MCLR VSS 0.2 VDD V
D033 OSC1 VSS 0.3 VDD V HS, HSPLL modes
D033A
D033B
D034
OSC1
OSC1
T13CKI
VSS
VSS
VSS
0.2 VDD
0.3
0.3
V
V
V
RC, EC modes(1)
XT, LP modes
VIH Input High Voltage
I/O Ports:
D040 with TTL Buffer 0.25 VDD + 0.8V VDD V VDD < 4.5V
D040A 2.0 VDD V 4.5V ≤ VDD ≤ 5.5V
D041 with Schmitt Trigger Buffer 0.8 VDD VDD V
D041A RC3 and RC4 0.7 VDD VDD V I2C enabled
D041B 2.1 VDD V SMBus enabled
D042 MCLR 0.8 VDD VDD V
D043 OSC1 0.7 VDD VDD V HS, HSPLL modes
D043A
D043B
D043C
D044
OSC1
OSC1
OSC1
T13CKI
0.8 VDD
0.9 VDD
1.6
1.6
VDD
VDD
VDD
VDD
V
V
V
V
EC mode
RC mode(1)
XT, LP modes
IIL Input Leakage Current(2,3)
D060 I/O Ports — ±200
±50
nA
nA
VDD < 5.5V,
VSS ≤ VPIN ≤ VDD,
Pin at high-impedance
VDD < 3V,
VSS ≤ VPIN ≤ VDD,
Pin at high-impedance
D061 MCLR — ±1 μA Vss ≤ VPIN ≤ VDD
D063 OSC1 — ±1 μA Vss ≤ VPIN ≤ VDD
IPU Weak Pull-up Current
D070 IPURB PORTB Weak Pull-up Current 50 400 μA VDD = 5V, VPIN = VSS
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PIC® device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.PIC18F2420/2520/4420/4520
DS39631E-page 336 © 2008 Microchip Technology Inc.
VOL Output Low Voltage
D080 I/O Ports — 0.6 V IOL = 8.5 mA, VDD = 4.5V,
-40°C to +85°C
D083 OSC2/CLKO
(RC, RCIO, EC, ECIO modes)
— 0.6 V IOL = 1.6 mA, VDD = 4.5V,
-40°C to +85°C
VOH Output High Voltage(3)
D090 I/O Ports VDD – 0.7 — V IOH = -3.0 mA, VDD = 4.5V,
-40°C to +85°C
D092 OSC2/CLKO
(RC, RCIO, EC, ECIO modes)
VDD – 0.7 — V IOH = -1.3 mA, VDD = 4.5V,
-40°C to +85°C
Capacitive Loading Specs
on Output Pins
D100 COSC2 OSC2 pin — 15 pF In XT, HS and LP modes
when external clock is
used to drive OSC1
D101 CIO All I/O pins and OSC2
(in RC mode)
— 50 pF To meet the AC Timing
Specifications
D102 CB SCL, SDA — 400 pF I2C™ Specification
26.3 DC Characteristics: PIC18F2420/2520/4420/4520 (Industrial)
PIC18LF2420/2520/4420/4520 (Industrial) (Continued)
DC CHARACTERISTICS Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Symbol Characteristic Min Max Units Conditions
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PIC® device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.© 2008 Microchip Technology Inc. DS39631E-page 337
PIC18F2420/2520/4420/4520
TABLE 26-1: MEMORY PROGRAMMING REQUIREMENTS
DC CHARACTERISTICS Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Sym Characteristic Min Typ† Max Units Conditions
Data EEPROM Memory
D120 ED Byte Endurance 100K 1M — E/W -40°C to +85°C
D121 VDRW VDD for Read/Write VMIN — 5.5 V Using EECON to read/write
VMIN = Minimum operating
voltage
D122 TDEW Erase/Write Cycle Time — 4 — ms
D123 TRETD Characteristic Retention 40 — — Year Provided no other
specifications are violated
D124 TREF Number of Total Erase/Write
Cycles before Refresh(1)
1M 10M — E/W -40°C to +85°C
D125 IDDP Supply Current during
Programming
— 10 — mA
Program Flash Memory
D130 EP Cell Endurance 10K 100K — E/W -40°C to +85°C
D131 VPR VDD for Read VMIN — 5.5 V VMIN = Minimum operating
voltage
D132 VIE VDD for Block Erase 3.0 — 5.5 V Using ICSP™ port, +25°C
D132A VIW VDD for Externally Timed Erase
or Write
4.5 — 5.5 V Using ICSP™ port, +25°C
D132B VPEW VDD for Self-Timed Write VMIN — 5.5 V VMIN = Minimum operating
voltage
D133 TIE ICSP Block Erase Cycle Time — 4 — ms VDD ≥ 4.5V
D133A TIW ICSP Erase or Write Cycle Time
(externally timed)
1 — — ms VDD ≥ 4.5V, +25°C
D133A TIW Self-Timed Write Cycle Time — 2 — ms
D134 TRETD Characteristic Retention 40 100 — Year Provided no other
specifications are violated
D135 IDDP Supply Current during
Programming
— 10 — mA
† Data in “Typ” column is at 5.0V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
Note 1: Refer to Section 7.8 “Using the Data EEPROM” for a more detailed discussion on data EEPROM
endurance.PIC18F2420/2520/4420/4520
DS39631E-page 338 © 2008 Microchip Technology Inc.
TABLE 26-2: COMPARATOR SPECIFICATIONS
TABLE 26-3: VOLTAGE REFERENCE SPECIFICATIONS
Operating Conditions: 3.0V < VDD < 5.5V, -40°C < TA < +85°C (unless otherwise stated).
Param
No. Sym Characteristics Min Typ Max Units Comments
D300 VIOFF Input Offset Voltage — ±5.0 ±10 mV
D301 VICM Input Common Mode Voltage 0 — VDD – 1.5 V
D302 CMRR Common Mode Rejection Ratio 55 — — dB
300 TRESP Response Time(1) — 150 400 ns PIC18FXXXX
300A — 150 600 ns PIC18LFXXXX,
VDD = 2.0V
301 TMC2OV Comparator Mode Change to
Output Valid
— — 10 μs
Note 1: Response time measured with one comparator input at (VDD – 1.5)/2, while the other input transitions
from VSS to VDD.
Operating Conditions: 3.0V < VDD < 5.5V, -40°C < TA < +85°C (unless otherwise stated).
Param
No. Sym Characteristics Min Typ Max Units Comments
D310 VRES Resolution VDD/24 — VDD/32 LSb
D311 VRAA Absolute Accuracy — — 1/2 LSb
D312 VRUR Unit Resistor Value (R) — 2k — Ω
310 TSET Settling Time(1) — — 10 μs
Note 1: Settling time measured while CVRR = 1 and CVR3:CVR0 transitions from ‘0000’ to ‘1111’.© 2008 Microchip Technology Inc. DS39631E-page 339
PIC18F2420/2520/4420/4520
FIGURE 26-4: HIGH/LOW-VOLTAGE DETECT CHARACTERISTICS
TABLE 26-4: HIGH/LOW-VOLTAGE DETECT CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Sym Characteristic Min Typ Max Units Conditions
D420 HLVD Voltage on VDD
Transition High-to-Low
HLVDL<3:0> = 0000 2.06 2.17 2.28 V
HLVDL<3:0> = 0001 2.12 2.23 2.34 V
HLVDL<3:0> = 0010 2.24 2.36 2.48 V
HLVDL<3:0> = 0011 2.32 2.44 2.56 V
HLVDL<3:0> = 0100 2.47 2.60 2.73 V
HLVDL<3:0> = 0101 2.65 2.79 2.93 V
HLVDL<3:0> = 0110 2.74 2.89 3.04 V
HLVDL<3:0> = 0111 2.96 3.12 3.28 V
HLVDL<3:0> = 1000 3.22 3.39 3.56 V
HLVDL<3:0> = 1001 3.37 3.55 3.73 V
HLVDL<3:0> = 1010 3.52 3.71 3.90 V
HLVDL<3:0> = 1011 3.70 3.90 4.10 V
HLVDL<3:0> = 1100 3.90 4.11 4.32 V
HLVDL<3:0> = 1101 4.11 4.33 4.55 V
HLVDL<3:0> = 1110 4.36 4.59 4.82 V
VLVD
HLVDIF(1)
VDD
(HLVDIF set by hardware)
(HLVDIF can be
cleared in software)
Note 1: VDIRMAG = 0.PIC18F2420/2520/4420/4520
DS39631E-page 340 © 2008 Microchip Technology Inc.
26.4 AC (Timing) Characteristics
26.4.1 TIMING PARAMETER SYMBOLOGY
The timing parameter symbols have been created
using one of the following formats:
1. TppS2ppS 3. TCC:ST (I2C specifications only)
2. TppS 4. Ts (I2C specifications only)
T
F Frequency T Time
Lowercase letters (pp) and their meanings:
pp
cc CCP1 osc OSC1
ck CLKO rd RD
cs CS rw RD or WR
di SDI sc SCK
do SDO ss SS
dt Data in t0 T0CKI
io I/O port t1 T13CKI
mc MCLR wr WR
Uppercase letters and their meanings:
S
F Fall P Period
H High R Rise
I Invalid (High-impedance) V Valid
L Low Z High-impedance
I
2C only
AA output access High High
BUF Bus free Low Low
TCC:ST (I2C specifications only)
CC
HD Hold SU Setup
ST
DAT DATA input hold STO Stop condition
STA Start condition© 2008 Microchip Technology Inc. DS39631E-page 341
PIC18F2420/2520/4420/4520
26.4.2 TIMING CONDITIONS
The temperature and voltages specified in Table 26-5
apply to all timing specifications unless otherwise
noted. Figure 26-5 specifies the load conditions for the
timing specifications.
TABLE 26-5: TEMPERATURE AND VOLTAGE SPECIFICATIONS – AC
FIGURE 26-5: LOAD CONDITIONS FOR DEVICE TIMING SPECIFICATIONS
Note: Because of space limitations, the generic
terms “PIC18FXXXX” and “PIC18LFXXXX”
are used throughout this section to refer to
the PIC18F2420/2520/4420/4520 and
PIC18LF2420/2520/4420/4520 families of
devices specifically and only those devices.
AC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Operating voltage VDD range as described in DC specification Section 26.1 and
Section 26.3.
LF parts operate for industrial temperatures only.
VDD/2
CL
RL
Pin
Pin
VSS
VSS
CL
RL = 464Ω
CL = 50 pF for all pins except OSC2/CLKO
and including D and E outputs as ports
Load Condition 1 Load Condition 2PIC18F2420/2520/4420/4520
DS39631E-page 342 © 2008 Microchip Technology Inc.
26.4.3 TIMING DIAGRAMS AND SPECIFICATIONS
FIGURE 26-6: EXTERNAL CLOCK TIMING (ALL MODES EXCEPT PLL)
TABLE 26-6: EXTERNAL CLOCK TIMING REQUIREMENTS
Param.
No. Symbol Characteristic Min Max Units Conditions
1A FOSC External CLKI Frequency(1) DC 1 MHz XT, RC Oscillator mode
DC 25 MHz HS Oscillator mode
DC 31.25 kHz LP Oscillator mode
DC 40 MHz EC Oscillator mode
Oscillator Frequency(1) DC 4 MHz RC Oscillator mode
0.1 4 MHz XT Oscillator mode
4 25 MHz HS Oscillator mode
4 10 MHz HS + PLL Oscillator mode
5 200 kHz LP Oscillator mode
1 TOSC External CLKI Period(1) 1000 — ns XT, RC Oscillator mode
40 — ns HS Oscillator mode
32 — μs LP Oscillator mode
25 — ns EC Oscillator mode
Oscillator Period(1) 250 — ns RC Oscillator mode
0.25 10 μs XT Oscillator mode
40 250 ns HS Oscillator mode
100 250 ns HS + PLL Oscillator mode
5 200 μs LP Oscillator mode
2 TCY Instruction Cycle Time(1) 100 — ns TCY = 4/FOSC, Industrial
160 — ns TCY = 4/FOSC, Extended
3 TOSL,
TOSH
External Clock in (OSC1)
High or Low Time
30 — ns XT Oscillator mode
2.5 — μs LP Oscillator mode
10 — ns HS Oscillator mode
4 TOSR,
TOSF
External Clock in (OSC1)
Rise or Fall Time
— 20 ns XT Oscillator mode
— 50 ns LP Oscillator mode
— 7.5 ns HS Oscillator mode
Note 1: Instruction cycle period (TCY) equals four times the input oscillator time base period for all configurations
except PLL. All specified values are based on characterization data for that particular oscillator type under
standard operating conditions with the device executing code. Exceeding these specified limits may result
in an unstable oscillator operation and/or higher than expected current consumption. All devices are tested
to operate at “min.” values with an external clock applied to the OSC1/CLKI pin. When an external clock
input is used, the “max.” cycle time limit is “DC” (no clock) for all devices.
OSC1
CLKO
Q4 Q1 Q2 Q3 Q4 Q1
1
2
3 3 4 4© 2008 Microchip Technology Inc. DS39631E-page 343
PIC18F2420/2520/4420/4520
TABLE 26-7: PLL CLOCK TIMING SPECIFICATIONS (VDD = 4.2V TO 5.5V)
TABLE 26-8: AC CHARACTERISTICS: INTERNAL RC ACCURACY
PIC18F2420/2520/4420/4520 (INDUSTRIAL)
PIC18LF2420/2520/4420/4520 (INDUSTRIAL)
Param
No. Sym Characteristic Min Typ† Max Units Conditions
F10 FOSC Oscillator Frequency Range 4 — 10 MHz HS mode only
F11 FSYS On-Chip VCO System Frequency 16 — 40 MHz HS mode only
F12 trc PLL Start-up Time (Lock Time) — — 2 ms
F13 ΔCLK CLKO Stability (Jitter) -2 — +2 %
† Data in “Typ” column is at 5V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
PIC18LF2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18F2420/2520/4420/4520
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
Param
No. Device Min Typ Max Units Conditions
INTOSC Accuracy @ Freq = 8 MHz, 4 MHz, 2 MHz, 1 MHz, 500 kHz, 250 kHz, 125 kHz, 31 kHz(1)
PIC18LF2420/2520/4420/4520 -2 +/-1 2 % +25°C VDD = 2.7-3.3V
-5 +/-1 5 % -40°C to +85°C VDD = 2.7-3.3V
PIC18F2420/2520/4420/4520 -2 +/-1 2 % +25°C VDD = 4.5-5.5V
-5 +/-1 5 % -40°C to +85°C VDD = 4.5-5.5V
INTRC Accuracy @ Freq = 31 kHz
PIC18LF2420/2520/4420/4520 26.562 — 35.938 kHz -40°C to +85°C VDD = 2.7-3.3V
PIC18F2420/2520/4420/4520 26.562 — 35.938 kHz -40°C to +85°C VDD = 4.5-5.5V
Legend: Shading of rows is to assist in readability of the table.
Note 1: Frequency calibrated at 25°C. OSCTUNE register can be used to compensate for temperature drift.PIC18F2420/2520/4420/4520
DS39631E-page 344 © 2008 Microchip Technology Inc.
FIGURE 26-7: CLKO AND I/O TIMING
TABLE 26-9: CLKO AND I/O TIMING REQUIREMENTS
Param
No. Symbol Characteristic Min Typ Max Units Conditions
10 TosH2ckL OSC1 ↑ to CLKO ↓ — 75 200 ns (Note 1)
11 TosH2ckH OSC1 ↑ to CLKO ↑ — 75 200 ns (Note 1)
12 TckR CLKO Rise Time — 35 100 ns (Note 1)
13 TckF CLKO Fall Time — 35 100 ns (Note 1)
14 TckL2ioV CLKO ↓ to Port Out Valid — — 0.5 TCY + 20 ns (Note 1)
15 TioV2ckH Port In Valid before CLKO ↑ 0.25 TCY + 25 — — ns (Note 1)
16 TckH2ioI Port In Hold after CLKO ↑ 0 — — ns (Note 1)
17 TosH2ioV OSC1 ↑ (Q1 cycle) to Port Out Valid — 50 150 ns
18 TosH2ioI OSC1 ↑ (Q2 cycle) to
Port Input Invalid
(I/O in hold time)
PIC18FXXXX 100 — — ns
18A PIC18LFXXXX 200 — — ns VDD = 2.0V
19 TioV2osH Port Input Valid to OSC1 ↑ (I/O in setup
time)
0 — — ns
20 TioR Port Output Rise Time PIC18FXXXX — 10 25 ns
20A PIC18LFXXXX — — 60 ns VDD = 2.0V
21 TioF Port Output Fall Time PIC18FXXXX — 10 25 ns
21A PIC18LFXXXX — — 60 ns VDD = 2.0V
22† TINP INTx pin High or Low Time TCY — — ns
23† TRBP RB<7:4> Change INTx High or Low Time TCY — — ns
† These parameters are asynchronous events not related to any internal clock edges.
Note 1: Measurements are taken in RC mode, where CLKO output is 4 x TOSC.
Note: Refer to Figure 26-5 for load conditions.
OSC1
CLKO
I/O pin
(Input)
I/O pin
(Output)
Q4 Q1 Q2 Q3
10
13
14
17
20, 21
19 18
15
11
12
16
Old Value New Value© 2008 Microchip Technology Inc. DS39631E-page 345
PIC18F2420/2520/4420/4520
FIGURE 26-8: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER AND
POWER-UP TIMER TIMING
FIGURE 26-9: BROWN-OUT RESET TIMING
TABLE 26-10: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER, POWER-UP TIMER
AND BROWN-OUT RESET REQUIREMENTS
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
30 TmcL MCLR Pulse Width (low) 2 — — μs
31 TWDT Watchdog Timer Time-out Period
(no postscaler)
3.4 4.1 4.71 ms
32 TOST Oscillation Start-up Timer Period 1024 TOSC — 1024 TOSC — TOSC = OSC1 period
33 TPWRT Power-up Timer Period 55.6 65.5 75.4 ms
34 TIOZ I/O High-Impedance from MCLR
Low or Watchdog Timer Reset
—2— μs
35 TBOR Brown-out Reset Pulse Width 200 — — μs VDD ≤ BVDD (see D005)
36 TIRVST Time for Internal Reference
Voltage to become Stable
— 20 50 μs
37 TLVD High/Low-Voltage Detect Pulse Width 200 — — μs VDD ≤ VLVD
38 TCSD CPU Start-up Time — 10 — μs
39 TIOBST Time for INTOSC to Stabilize — 1 — μs
VDD
MCLR
Internal
POR
PWRT
Time-out
OSC
Time-out
Internal
Reset
Watchdog Timer
Reset
33
32
30
31
34
I/O pins
34
Note: Refer to Figure 26-5 for load conditions.
VDD BVDD
35
VIRVST
Enable Internal
Internal Reference
36
Reference Voltage
Voltage StablePIC18F2420/2520/4420/4520
DS39631E-page 346 © 2008 Microchip Technology Inc.
FIGURE 26-10: TIMER0 AND TIMER1 EXTERNAL CLOCK TIMINGS
TABLE 26-11: TIMER0 AND TIMER1 EXTERNAL CLOCK REQUIREMENTS
Param
No. Symbol Characteristic Min Max Units Conditions
40 Tt0H T0CKI High Pulse Width No prescaler 0.5 TCY + 20 — ns
With prescaler 10 — ns
41 Tt0L T0CKI Low Pulse Width No prescaler 0.5 TCY + 20 — ns
With prescaler 10 — ns
42 Tt0P T0CKI Period No prescaler TCY + 10 — ns
With prescaler Greater of:
20 ns or
(TCY + 40)/N
— ns N = prescale
value
(1, 2, 4,..., 256)
45 Tt1H T13CKI
High Time
Synchronous, no prescaler 0.5 TCY + 20 — ns
Synchronous,
with prescaler
PIC18FXXXX 10 — ns
PIC18LFXXXX 25 — ns VDD = 2.0V
Asynchronous PIC18FXXXX 30 — ns
PIC18LFXXXX 50 — ns VDD = 2.0V
46 Tt1L T13CKI
Low Time
Synchronous, no prescaler 0.5 TCY + 5 — ns
Synchronous,
with prescaler
PIC18FXXXX 10 — ns
PIC18LFXXXX 25 — ns VDD = 2.0V
Asynchronous PIC18FXXXX 30 — ns
PIC18LFXXXX 50 — ns VDD = 2.0V
47 Tt1P T13CKI
Input
Period
Synchronous Greater of:
20 ns or
(TCY + 40)/N
— ns N = prescale
value (1, 2, 4, 8)
Asynchronous 60 — ns
Ft1 T13CKI Oscillator Input Frequency Range DC 50 kHz
48 Tcke2tmrI Delay from External T13CKI Clock Edge to
Timer Increment
2 TOSC 7 TOSC —
Note: Refer to Figure 26-5 for load conditions.
46
47
45
48
41
42
40
T0CKI
T1OSO/T13CKI
TMR0 or
TMR1© 2008 Microchip Technology Inc. DS39631E-page 347
PIC18F2420/2520/4420/4520
FIGURE 26-11: CAPTURE/COMPARE/PWM TIMINGS (ALL CCP MODULES)
TABLE 26-12: CAPTURE/COMPARE/PWM REQUIREMENTS (ALL CCP MODULES)
Param
No. Symbol Characteristic Min Max Units Conditions
50 TccL CCPx Input Low
Time
No prescaler 0.5 TCY + 20 — ns
With
prescaler
PIC18FXXXX 10 — ns
PIC18LFXXXX 20 — ns VDD = 2.0V
51 TccH CCPx Input
High Time
No prescaler 0.5 TCY + 20 — ns
With
prescaler
PIC18FXXXX 10 — ns
PIC18LFXXXX 20 — ns VDD = 2.0V
52 TccP CCPx Input Period 3 TCY + 40
N
— ns N = prescale
value (1, 4 or 16)
53 TccR CCPx Output Fall Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
54 TccF CCPx Output Fall Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
Note: Refer to Figure 26-5 for load conditions.
CCPx
(Capture Mode)
50 51
52
CCPx
53 54
(Compare or PWM Mode)PIC18F2420/2520/4420/4520
DS39631E-page 348 © 2008 Microchip Technology Inc.
FIGURE 26-12: PARALLEL SLAVE PORT TIMING (PIC18F4420/4520)
TABLE 26-13: PARALLEL SLAVE PORT REQUIREMENTS (PIC18F4420, PIC18F4520)
Param.
No. Symbol Characteristic Min Max Units Conditions
62 TdtV2wrH Data In Valid before WR ↑ or CS ↑ (setup
time)
20 — ns
63 TwrH2dtI WR ↑ or CS ↑ to Data–In
Invalid (hold time)
PIC18FXXXX 20 — ns
PIC18LFXXXX 35 — ns VDD = 2.0V
64 TrdL2dtV RD ↓ and CS ↓ to Data–Out Valid — 80 ns
65 TrdH2dtI RD ↑ or CS ↓ to Data–Out Invalid 10 30 ns
66 TibfINH Inhibit of the IBF Flag bit being Cleared from
WR ↑ or CS ↑
— 3 TCY
Note: Refer to Figure 26-5 for load conditions.
RE2/CS
RE0/RD
RE1/WR
RD<7:0>
62
63
64
65© 2008 Microchip Technology Inc. DS39631E-page 349
PIC18F2420/2520/4420/4520
FIGURE 26-13: EXAMPLE SPI MASTER MODE TIMING (CKE = 0)
TABLE 26-14: EXAMPLE SPI MODE REQUIREMENTS (MASTER MODE, CKE = 0)
Param
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS ↓ to SCK ↓ or SCK ↑ Input TCY — ns
73 TdiV2scH,
TdiV2scL
Setup Time of SDI Data Input to SCK Edge 20 — ns
73A Tb2b Last Clock Edge of Byte 1 to the 1st Clock Edge
of Byte 2
1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold Time of SDI Data Input to SCK Edge 40 — ns
75 TdoR SDO Data Output Rise Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
76 TdoF SDO Data Output Fall Time — 25 ns
78 TscR SCK Output Rise Time
(Master mode)
PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
79 TscF SCK Output Fall Time (Master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO Data Output Valid after
SCK Edge
PIC18FXXXX — 50 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
Note 1: Requires the use of Parameter #73A.
2: Only if Parameter #71A and #72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76
79 78 80
78 79
MSb LSb bit 6 - - - - - -1
MSb In bit 6 - - - -1 LSb In
Note: Refer to Figure 26-5 for load conditions.PIC18F2420/2520/4420/4520
DS39631E-page 350 © 2008 Microchip Technology Inc.
FIGURE 26-14: EXAMPLE SPI MASTER MODE TIMING (CKE = 1)
TABLE 26-15: EXAMPLE SPI MODE REQUIREMENTS (MASTER MODE, CKE = 1)
Param.
No. Symbol Characteristic Min Max Units Conditions
73 TdiV2scH,
TdiV2scL
Setup Time of SDI Data Input to SCK Edge 20 — ns
73A Tb2b Last Clock Edge of Byte 1 to the 1st Clock Edge
of Byte 2
1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold Time of SDI Data Input to SCK Edge 40 — ns
75 TdoR SDO Data Output Rise Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
76 TdoF SDO Data Output Fall Time — 25 ns
78 TscR SCK Output Rise Time
(Master mode)
PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
79 TscF SCK Output Fall Time (Master mode) — 25 ns
80 TscH2doV,
TscL2doV
SDO Data Output Valid after
SCK Edge
PIC18FXXXX — 50 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
81 TdoV2scH,
TdoV2scL
SDO Data Output Setup to SCK Edge TCY — ns
Note 1: Requires the use of Parameter #73A.
2: Only if Parameter #71A and #72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
81
71 72
74
75, 76
78
80
MSb
79
73
MSb In
bit 6 - - - - - -1
bit 6 - - - -1 LSb In
LSb
Note: Refer to Figure 26-5 for load conditions.© 2008 Microchip Technology Inc. DS39631E-page 351
PIC18F2420/2520/4420/4520
FIGURE 26-15: EXAMPLE SPI SLAVE MODE TIMING (CKE = 0)
TABLE 26-16: EXAMPLE SPI MODE REQUIREMENTS (SLAVE MODE TIMING, CKE = 0)
Param
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS ↓ to SCK ↓ or SCK ↑ Input 3 TCY — ns
71 TscH SCK Input High Time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK Input Low Time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup Time of SDI Data Input to SCK Edge 20 — ns
73A Tb2b Last Clock Edge of Byte 1 to the First Clock Edge of Byte 2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold Time of SDI Data Input to SCK Edge 40 — ns
75 TdoR SDO Data Output Rise Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
76 TdoF SDO Data Output Fall Time — 25 ns
77 TssH2doZ SS ↑ to SDO Output High-Impedance 10 50 ns
80 TscH2doV,
TscL2doV
SDO Data Output Valid after SCK Edge PIC18FXXXX — 50 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK edge 1.5 TCY + 40 — ns
Note 1: Requires the use of Parameter #73A.
2: Only if Parameter #71A and #72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76 77
79 78 80
78 79
SDI
MSb LSb bit 6 - - - - - -1
bit 6 - - - -1 LSb In
83
Note: Refer to Figure 26-5 for load conditions.
MSb InPIC18F2420/2520/4420/4520
DS39631E-page 352 © 2008 Microchip Technology Inc.
FIGURE 26-16: EXAMPLE SPI SLAVE MODE TIMING (CKE = 1)
TABLE 26-17: EXAMPLE SPI SLAVE MODE REQUIREMENTS (CKE = 1)
Param
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS ↓ to SCK ↓ or SCK ↑ Input 3 TCY — ns
71 TscH SCK Input High Time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK Input Low Time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73A Tb2b Last Clock Edge of Byte 1 to the First Clock Edge of Byte 2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold Time of SDI Data Input to SCK Edge 40 — ns
75 TdoR SDO Data Output Rise Time PIC18FXXXX — 25 ns
PIC18LFXXXX — 45 ns VDD = 2.0V
76 TdoF SDO Data Output Fall Time — 25 ns
77 TssH2doZ SS ↑ to SDO Output High-Impedance 10 50 ns
80 TscH2doV,
TscL2doV
SDO Data Output Valid after SCK
Edge
PIC18FXXXX — 50 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
82 TssL2doV SDO Data Output Valid after SS ↓
Edge
PIC18FXXXX — 50 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK Edge 1.5 TCY + 40 — ns
Note 1: Requires the use of Parameter #73A.
2: Only if Parameter #71A and #72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
82
74
75, 76
MSb bit 6 - - - - - -1 LSb
77
MSb In bit 6 - - - -1 LSb In
80
83
Note: Refer to Figure 26-5 for load conditions.© 2008 Microchip Technology Inc. DS39631E-page 353
PIC18F2420/2520/4420/4520
FIGURE 26-17: I2C™ BUS START/STOP BITS TIMING
TABLE 26-18: I2C™ BUS START/STOP BITS REQUIREMENTS (SLAVE MODE)
FIGURE 26-18: I2C™ BUS DATA TIMING
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA Start Condition 100 kHz mode 4700 — ns Only relevant for Repeated
Setup Time 400 kHz mode 600 — Start condition
91 THD:STA Start Condition 100 kHz mode 4000 — ns After this period, the first
Hold Time 400 kHz mode 600 — clock pulse is generated
92 TSU:STO Stop Condition 100 kHz mode 4700 — ns
Setup Time 400 kHz mode 600 —
93 THD:STO Stop Condition 100 kHz mode 4000 — ns
Hold Time 400 kHz mode 600 —
Note: Refer to Figure 26-5 for load conditions.
91
92
93
SCL
SDA
Start
Condition
Stop
Condition
90
Note: Refer to Figure 26-5 for load conditions.
90
91 92
100
101
103
106 107
109 109
110
102
SCL
SDA
In
SDA
OutPIC18F2420/2520/4420/4520
DS39631E-page 354 © 2008 Microchip Technology Inc.
TABLE 26-19: I2C™ BUS DATA REQUIREMENTS (SLAVE MODE)
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock High Time 100 kHz mode 4.0 — μs
400 kHz mode 0.6 — μs
MSSP module 1.5 TCY —
101 TLOW Clock Low Time 100 kHz mode 4.7 — μs
400 kHz mode 1.3 — μs
MSSP module 1.5 TCY —
102 TR SDA and SCL Rise
Time
100 kHz mode — 1000 ns
400 kHz mode 20 + 0.1 CB 300 ns CB is specified to be from
10 to 400 pF
103 TF SDA and SCL Fall
Time
100 kHz mode — 300 ns
400 kHz mode 20 + 0.1 CB 300 ns CB is specified to be from
10 to 400 pF
90 TSU:STA Start Condition
Setup Time
100 kHz mode 4.7 — μs Only relevant for Repeated
Start condition 400 kHz mode 0.6 — μs
91 THD:STA Start Condition
Hold Time
100 kHz mode 4.0 — μs After this period, the first
clock pulse is generated 400 kHz mode 0.6 — μs
106 THD:DAT Data Input Hold
Time
100 kHz mode 0 — ns
400 kHz mode 0 0.9 μs
107 TSU:DAT Data Input Setup
Time
100 kHz mode 250 — ns (Note 2)
400 kHz mode 100 — ns
92 TSU:STO Stop Condition
Setup Time
100 kHz mode 4.7 — μs
400 kHz mode 0.6 — μs
109 TAA Output Valid from
Clock
100 kHz mode — 3500 ns (Note 1)
400 kHz mode — — ns
110 TBUF Bus Free Time 100 kHz mode 4.7 — μs Time the bus must be free
before a new transmission
can start
400 kHz mode 1.3 — μs
D102 CB Bus Capacitive Loading — 400 pF
Note 1: As a transmitter, the device must provide this internal minimum delay time to bridge the undefined region
(min. 300 ns) of the falling edge of SCL to avoid unintended generation of Start or Stop conditions.
2: A Fast mode I2C bus device can be used in a Standard mode I2C bus system, but the requirement
TSU:DAT ≥ 250 ns must then be met. This will automatically be the case if the device does not stretch the
LOW period of the SCL signal. If such a device does stretch the LOW period of the SCL signal, it must
output the next data bit to the SDA line, TR max. + TSU:DAT = 1000 + 250 = 1250 ns (according to the
Standard mode I2C bus specification), before the SCL line is released. © 2008 Microchip Technology Inc. DS39631E-page 355
PIC18F2420/2520/4420/4520
FIGURE 26-19: MASTER SSP I2C™ BUS START/STOP BITS TIMING WAVEFORMS
TABLE 26-20: MASTER SSP I2C™ BUS START/STOP BITS REQUIREMENTS
FIGURE 26-20: MASTER SSP I2C™ BUS DATA TIMING
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA Start Condition 100 kHz mode 2(TOSC)(BRG + 1) — ns Only relevant for
Repeated Start
condition Setup Time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
91 THD:STA Start Condition 100 kHz mode 2(TOSC)(BRG + 1) — ns After this period, the
first clock pulse is
generated Hold Time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
92 TSU:STO Stop Condition 100 kHz mode 2(TOSC)(BRG + 1) — ns
Setup Time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
93 THD:STO Stop Condition 100 kHz mode 2(TOSC)(BRG + 1) — ns
Hold Time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
Note: Refer to Figure 26-5 for load conditions.
91 93 SCL
SDA
Start
Condition
Stop
Condition
90 92
Note: Refer to Figure 26-5 for load conditions.
90
91 92
100
101
103
106
107
109 109 110
102
SCL
SDA
In
SDA
OutPIC18F2420/2520/4420/4520
DS39631E-page 356 © 2008 Microchip Technology Inc.
TABLE 26-21: MASTER SSP I2C™ BUS DATA REQUIREMENTS
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock High Time 100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
101 TLOW Clock Low Time 100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
102 TR SDA and SCL
Rise Time
100 kHz mode — 1000 ns CB is specified to be from
10 to 400 pF 400 kHz mode 20 + 0.1 CB 300 ns
1 MHz mode(1) — 300 ns
103 TF SDA and SCL
Fall Time
100 kHz mode — 300 ns CB is specified to be from
10 to 400 pF 400 kHz mode 20 + 0.1 CB 300 ns
1 MHz mode(1) — 100 ns
90 TSU:STA Start Condition
Setup Time
100 kHz mode 2(TOSC)(BRG + 1) — ms Only relevant for
Repeated Start
condition 400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
91 THD:STA Start Condition
Hold Time
100 kHz mode 2(TOSC)(BRG + 1) — ms After this period, the first
clock pulse is generated 400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
106 THD:DAT Data Input
Hold Time
100 kHz mode 0 — ns
400 kHz mode 0 0.9 ms
107 TSU:DAT Data Input
Setup Time
100 kHz mode 250 — ns (Note 2)
400 kHz mode 100 — ns
92 TSU:STO Stop Condition
Setup Time
100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
109 TAA Output Valid
from Clock
100 kHz mode — 3500 ns
400 kHz mode — 1000 ns
1 MHz mode(1) — — ns
110 TBUF Bus Free Time 100 kHz mode 4.7 — ms Time the bus must be free
before a new transmission
can start
400 kHz mode 1.3 — ms
D102 CB Bus Capacitive Loading — 400 pF
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
2: A Fast mode I2C bus device can be used in a Standard mode I2C bus system, but parameter 107 ≥ 250 ns
must then be met. This will automatically be the case if the device does not stretch the LOW period of the
SCL signal. If such a device does stretch the LOW period of the SCL signal, it must output the next data bit
to the SDA line, parameter 102 + parameter 107 = 1000 + 250 = 1250 ns (for 100 kHz mode), before the
SCL line is released.© 2008 Microchip Technology Inc. DS39631E-page 357
PIC18F2420/2520/4420/4520
FIGURE 26-21: EUSART SYNCHRONOUS TRANSMISSION (MASTER/SLAVE) TIMING
TABLE 26-22: EUSART SYNCHRONOUS TRANSMISSION REQUIREMENTS
Param
No. Symbol Characteristic Min Max Units Conditions
120 TckH2dtV SYNC XMIT (MASTER & SLAVE)
Clock High to Data Out Valid PIC18FXXXX — 40 ns
PIC18LFXXXX — 100 ns VDD = 2.0V
121 Tckrf Clock Out Rise Time and Fall Time
(Master mode)
PIC18FXXXX — 20 ns
PIC18LFXXXX — 50 ns VDD = 2.0V
122 Tdtrf Data Out Rise Time and Fall Time PIC18FXXXX — 20 ns
PIC18LFXXXX — 50 ns VDD = 2.0V
121 121
120
122
RC6/TX/CK
RC7/RX/DT
pin
pin
Note: Refer to Figure 26-5 for load conditions.PIC18F2420/2520/4420/4520
DS39631E-page 358 © 2008 Microchip Technology Inc.
FIGURE 26-22: EUSART SYNCHRONOUS RECEIVE (MASTER/SLAVE) TIMING
TABLE 26-23: EUSART SYNCHRONOUS RECEIVE REQUIREMENTS
TABLE 26-24: A/D CONVERTER CHARACTERISTICS: PIC18F2420/2520/4420/4520 (INDUSTRIAL)
PIC18LF2420/2520/4420/4520 (INDUSTRIAL)
Param.
No. Symbol Characteristic Min Max Units Conditions
125 TdtV2ckl SYNC RCV (MASTER & SLAVE)
Data Hold before CK ↓ (DT hold time) 10 — ns
126 TckL2dtl Data Hold after CK ↓ (DT hold time) 15 — ns
Param
No. Symbol Characteristic Min Typ Max Units Conditions
A01 NR Resolution — — 10 bit ΔVREF ≥ 3.0V
A03 EIL Integral Linearity Error — — <±1 LSb ΔVREF ≥ 3.0V
A04 EDL Differential Linearity Error — — <±1 LSb ΔVREF ≥ 3.0V
A06 EOFF Offset Error — — <±2.0 LSb ΔVREF ≥ 3.0V
A07 EGN Gain Error — — <±1 LSb ΔVREF ≥ 3.0V
A10 — Monotonicity Guaranteed(1) — VSS ≤ VAIN ≤ VREF
A20 ΔVREF Reference Voltage Range
(VREFH – VREFL)
1.8
3
—
—
—
—
V
V
VDD < 3.0V
VDD ≥ 3.0V
A21 VREFH Reference Voltage High VSS — VREFH V
A22 VREFL Reference Voltage Low VSS – 0.3V — VDD – 3.0V V
A25 VAIN Analog Input Voltage VREFL — VREFH V
A30 ZAIN Recommended Impedance of
Analog Voltage Source
— — 2.5 kΩ
A40 IAD A/D Current from
VDD
PIC18FXXXX — 180 — μA Average current during
PIC18 conversion LFXX20 — 90 — μA
A50 IREF VREF Input Current(2) —
—
—
—
5
150
μA
μA
During VAIN acquisition.
During A/D conversion
cycle.
Note 1: The A/D conversion result never decreases with an increase in the input voltage and has no missing
codes.
2: VREFH current is from RA3/AN3/VREF+ pin or VDD, whichever is selected as the VREFH source.
VREFL current is from RA2/AN2/VREF-/CVREF pin or VSS, whichever is selected as the VREFL source.
125
126
RC6/TX/CK
RC7/RX/DT
pin
pin
Note: Refer to Figure 26-5 for load conditions.© 2008 Microchip Technology Inc. DS39631E-page 359
PIC18F2420/2520/4420/4520
FIGURE 26-23: A/D CONVERSION TIMING
TABLE 26-25: A/D CONVERSION REQUIREMENTS
Param
No. Symbol Characteristic Min Max Units Conditions
130 TAD A/D Clock Period PIC18FXXXX 0.7 25.0(1) μs TOSC based, VREF ≥ 3.0V
PIC18LFXXXX 1.4 25.0(1) μs VDD = 2.0V;
TOSC based, VREF full range
PIC18FXXXX — 1 μs A/D RC mode
PIC18LFXXXX — 3 μs VDD = 2.0V; A/D RC mode
131 TCNV Conversion Time
(not including acquisition time) (Note 2)
11 12 TAD
132 TACQ Acquisition Time (Note 3) 1.4 — μs -40°C to +85°C
135 TSWC Switching Time from Convert → Sample — (Note 4)
TBD TDIS Discharge Time 0.2 — μs
Note 1: The time of the A/D clock period is dependent on the device frequency and the TAD clock divider.
2: ADRES register may be read on the following TCY cycle.
3: The time for the holding capacitor to acquire the “New” input voltage when the voltage changes full scale
after the conversion (VDD to VSS or VSS to VDD). The source impedance (RS) on the input channels is 50Ω.
4: On the following cycle of the device clock.
131
130
132
BSF ADCON0, GO
Q4
A/D CLK(1)
A/D DATA
ADRES
ADIF
GO
SAMPLE
OLD_DATA
SAMPLING STOPPED
DONE
NEW_DATA
(Note 2)
9 87 2 1 0
Note 1: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts. This allows the SLEEP instruction
to be executed.
2: This is a minimal RC delay (typically 100 ns), which also disconnects the holding capacitor from the analog input.
. . . . . .
TCYPIC18F2420/2520/4420/4520
DS39631E-page 360 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 361
PIC18F2420/2520/4420/4520
27.0 DC AND AC CHARACTERISTICS GRAPHS AND TABLES
“Typical” represents the mean of the distribution at 25°C. “Maximum” or “minimum” represents (mean + 3σ) or (mean – 3σ)
respectively, where σ is a standard deviation, over the whole temperature range.
FIGURE 27-1: SLEEP MODE
Note: The graphs and tables provided following this note are a statistical summary based on a limited number of
samples and are provided for informational purposes only. The performance characteristics listed herein
are not tested or guaranteed. In some graphs or tables, the data presented may be outside the specified
operating range (e.g., outside specified power supply range) and therefore, outside the warranted range.
0.01
0.1
1
10
100
-50 -25 0 25 50 75 100 125
Temp (C)
Ipd (uA)
5.5
5.0
4.5
4.0
3.5
3.0
2.5
2.0
Test instrument results are compressed to about 0.05 μA for actual values below 0.05 mA.
Measurements below 0.01 mA are suspect and considered unmeasurable.
This is supported by the instrument specifications.PIC18F2420/2520/4420/4520
DS39631E-page 362 © 2008 Microchip Technology Inc.
FIGURE 27-2: TYPICAL IPD vs. VDD ACROSS TEMPERATURE (SLEEP MODE)
FIGURE 27-3: MAXIMUM IPD vs. VDD ACROSS TEMPERATURE (SLEEP MODE)
0.01
0.1
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
125°C
85°C
25°C
-40°C
0.01
0.1
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
125°C
85°C
25°C
-40°C© 2008 Microchip Technology Inc. DS39631E-page 363
PIC18F2420/2520/4420/4520
FIGURE 27-4: TYPICAL T1OSC DELTA CURRENT vs. VDD ACROSS TEMP. (DEVICE IN SLEEP,
T1OSC IN LOW-POWER MODE)
FIGURE 27-5: MAXIMUM T1OSC DELTA CURRENT vs. VDD ACROSS TEMP. (DEVICE IN SLEEP,
TIOSC IN LOW-POWER MODE)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
85°C
25°C
-10°C
0
1
2
3
4
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
85°C 25°C
-10°CPIC18F2420/2520/4420/4520
DS39631E-page 364 © 2008 Microchip Technology Inc.
FIGURE 27-6: TYPICAL T1OSC DELTA CURRENT vs. VDD ACROSS TEMP. (DEVICE IN SLEEP,
T1OSC IN HIGH-POWER MODE)
FIGURE 27-7: MAXIMUM T1OSC DELTA CURRENT vs. VDD ACROSS TEMP. (DEVICE IN SLEEP,
T1OSC IN HIGH-POWER MODE)
0
2
4
6
8
10
12
14
16
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
DD
IPD (uA)
85°C
25°C
-40°C
0
5
10
15
20
25
30
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
V DD (V)
IPD (uA)
85°C
25°C
-40°C© 2008 Microchip Technology Inc. DS39631E-page 365
PIC18F2420/2520/4420/4520
FIGURE 27-8: TYPICAL BOR DELTA CURRENT vs. VDD ACROSS TEMP.
(BORV = 2.7V, SLEEP MODE)
20.00
25.00
30.00
35.00
40.00
45.00
50.00
55.00
2 2.5 3 3.5 4 4.5 5 5.5
VDD (V)
IPD (uA)
MAX (85°C)
MAX
TYP (25°C)
MIN (-40°C)
Device
in
SLEEP
Device
Held in
RESETPIC18F2420/2520/4420/4520
DS39631E-page 366 © 2008 Microchip Technology Inc.
FIGURE 27-9: TYPICAL WDT CURRENT vs. VDD ACROSS TEMPERATURE
(WDT DELTA CURRENT IN SLEEP MODE)
FIGURE 27-10: MAXIMUM WDT CURRENT vs. VDD ACROSS TEMPERATURE
(WDT DELTA CURRENT IN SLEEP MODE)
0.00
1.00
2.00
3.00
4.00
5.00
6.00
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
125°C 85°C
25°C
-40°C
0.0
2.0
4.0
6.0
8.0
10.0
12.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
125°C
85°C
25°C -40°C© 2008 Microchip Technology Inc. DS39631E-page 367
PIC18F2420/2520/4420/4520
FIGURE 27-11: TYPICAL IDD ACROSS VDD (RC_RUN MODE, +25°C)
FIGURE 27-12: MAXIMUM IDD ACROSS VDD (RC_RUN MODE, +85°C)
0.1
1
10
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (mA)
8 MHz
4 MHz
2 MHz
1 MHz
250 kHz
500 kHz
125 kHz
4.2V
0.1
1
10
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (mA)
8 MHz
4.2V
4 MHz
2 MHz 1 MHz
250 kHz 500 kHz
125 kHzPIC18F2420/2520/4420/4520
DS39631E-page 368 © 2008 Microchip Technology Inc.
FIGURE 27-13: TYPICAL AND MAXIMUM IDD ACROSS VDD (RC_RUN MODE, 31 kHz)
FIGURE 27-14: TYPICAL IDD ACROSS VDD (RC_IDLE MODE, +25°C)
10
100
1000
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (uA)
Maximum
(-40°C)
Typical
(25°C)
0.01
0.1
1
10
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (mA)
8 MHz 4.2V
4 MHz
2 MHz
1 MHz
250 kHz 500 kHz
125 kHz© 2008 Microchip Technology Inc. DS39631E-page 369
PIC18F2420/2520/4420/4520
FIGURE 27-15: MAXIMUM IDD ACROSS VDD (RC_IDLE MODE, -40°C TO +85°C)
FIGURE 27-16: TYPICAL AND MAXIMUM IDD ACROSS VDD (RC_IDLE MODE, 31 kHz)
0.1
1
10
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (mA)
8 MHz
4.2V
4 MHz
2 MHz
1 MHz
250 kHz 500 kHz
125 kHz
0
5
10
15
20
25
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (uA)
Maximum
(85°C)
Typical
(25°C)PIC18F2420/2520/4420/4520
DS39631E-page 370 © 2008 Microchip Technology Inc.
FIGURE 27-17: TYPICAL AND MAXIMUM SEC_RUN CURRENT vs. VDD ACROSS TEMPERATURE
(T1OSC IN LOW-POWER MODE)
FIGURE 27-18: TYPICAL AND MAXIMUM SEC_IDLE CURRENT vs. VDD ACROSS TEMPERATURE
(T1OSC IN LOW-POWER MODE)
0.0
20.0
40.0
60.0
80.0
100.0
120.0
140.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (uA)
Max (-10°C)
Typ (25°C) Typ (85°C)
Typ (-10°C)
0.0
2.0
4.0
6.0
8.0
10.0
12.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (uA)
Max (85°C)
14.0
Typ (85°C)
Typ (-10°C)
Typ (25°C)© 2008 Microchip Technology Inc. DS39631E-page 371
PIC18F2420/2520/4420/4520
FIGURE 27-19: TYPICAL IDD vs. FOSC, 500 kHz TO 4 MHz (PRI_RUN MODE (EC CLOCK), +25°C)
FIGURE 27-20: MAXIMUM IDD vs. FOSC, 500 kHz TO 4 MHz (PRI_RUN MODE (EC CLOCK),
-40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0VPIC18F2420/2520/4420/4520
DS39631E-page 372 © 2008 Microchip Technology Inc.
FIGURE 27-21: TYPICAL IDD vs. FOSC, 4 MHz TO 40 MHz (PRI_RUN MODE (EC CLOCK), +25°C)
FIGURE 27-22: MAXIMUM IDD vs. FOSC, 4 MHz TO 40 MHz (PRI_RUN MODE (EC CLOCK),
-40°C TO +125°C)
0
2
4
6
8
10
12
14
16
18
20
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
0
2
4
6
8
10
12
14
16
18
20
22
24
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V© 2008 Microchip Technology Inc. DS39631E-page 373
PIC18F2420/2520/4420/4520
FIGURE 27-23: TYPICAL IDD vs. FOSC, HS/PLL (PRI_RUN MODE, +25°C)
FIGURE 27-24: MAXIMUM IDD vs. FOSC, HS/PLL (PRI_RUN MODE, -40°C)
4
6
8
10
12
14
16
18
20
22
24
16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2V
4
6
8
10
12
14
16
18
20
22
24
16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2VPIC18F2420/2520/4420/4520
DS39631E-page 374 © 2008 Microchip Technology Inc.
FIGURE 27-25: TYPICAL IDD vs. FOSC, 500 kHz TO 4 MHz (PRI_IDLE MODE, +25°C)
FIGURE 27-26: MAXIMUM IDD vs. FOSC, 500 kHz TO 4 MHz (PRI_IDLE MODE, -40°C TO +125°C)
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
Fosc (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
Fosc (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V© 2008 Microchip Technology Inc. DS39631E-page 375
PIC18F2420/2520/4420/4520
FIGURE 27-27: TYPICAL IDD vs. FOSC, 4 MHz TO 40 MHz (PRI_IDLE MODE, +25°C)
FIGURE 27-28: MAXIMUM IDD vs. FOSC, 4 MHz TO 40 MHz (PRI_IDLE MODE, -40°C TO +125°C)
0
1
2
3
4
5
6
7
8
9
10
11
12
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5V
0
1
2
3
4
5
6
7
8
9
10
11
12
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.0V
5.5V
4.0V
4.5V
3.0V
3.5V
2.0V
2.5VPIC18F2420/2520/4420/4520
DS39631E-page 376 © 2008 Microchip Technology Inc.
FIGURE 27-29: TYPICAL IDD vs. FOSC, HS/PLL (PRI_IDLE MODE, +25°C)
FIGURE 27-30: MAXIMUM IDD vs. FOSC, HS/PLL (PRI_IDLE MODE, -40°C)
0
1
2
3
4
5
6
7
8
9
10
11
12
16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2V
0
1
2
3
4
5
6
7
8
9
10
11
12
16 18 20 22 24 26 28 30 32 34 36 38 40
Fosc (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2V© 2008 Microchip Technology Inc. DS39631E-page 377
PIC18F2420/2520/4420/4520
FIGURE 27-31: VIN (ST) vs. VDD, +25°C (-40°C TO +125°C)
FIGURE 27-32: VIN (TTL) vs. VDD, +25°C (-40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
VIN (V)
VIH Max
(125°C)
VIH Typ
(25°C)
VIH Min
(-40°C)
VIL Min
(125°C)
VIL Typ
(25°C)
VIL Max
(-40°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
VIN (V)
VIH Min
(125°C)
VIH Typ
(25°C)
VIH Max
(-40°C)PIC18F2420/2520/4420/4520
DS39631E-page 378 © 2008 Microchip Technology Inc.
FIGURE 27-33: VOL vs. IOL (VDD = 3.0V, -40°C TO +85°C)
FIGURE 27-34: VOL vs. IOL (VDD = 5.0V, -40°C TO +125°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
0 5 10 15 20 25
IOL (-ma)
VOL (V)
Typ (25°C)
Min (-40°C)
Max (85°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
0 5 10 15 20 25
IOL (-ma)
VOL (V)
Min (-40°C)
Max (85°C)
Typ (25°C)© 2008 Microchip Technology Inc. DS39631E-page 379
PIC18F2420/2520/4420/4520
FIGURE 27-35: VOH vs. IOH (VDD = 3.0V, -40°C TO +85°C)
FIGURE 27-36: VOH vs. IOH (VDD = 5.0V, -40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
0 5 10 15 20 25
IOH (-ma)
VOH (V)
Max (-40°C)
Typ (25°C) Min (85°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
0 5 10 15 20 25
IOH (-ma)
VOH (V)
Max (-40°C)
Typ (25°C)
Min (125°C)PIC18F2420/2520/4420/4520
DS39631E-page 380 © 2008 Microchip Technology Inc.
FIGURE 27-37: INTOSC FREQUENCY vs. VDD, TEMPERATURE (-40°C, +25°C, +85°C, +125°C)
FIGURE 27-38: INTRC vs. VDD ACROSS TEMPERATURE (-40°C TO +125°C)
7.6
7.7
7.8
7.9
8.0
8.1
8.2
8.3
8.4
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (MHz)
Max Freq
125°C Typ
85°C Typ
25°C Typ
-40°C Typ
Min Freq
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (kHz)
Max (125°C)
Max (-40°C)
Typ (25°C)
Min (85°C)
Min (125°C)© 2008 Microchip Technology Inc. DS39631E-page 381
PIC18F2420/2520/4420/4520
FIGURE 27-39: WDT PERIOD vs. VDD ACROSS TEMPERATURE
(1:1 POSTSCALER, -40°C TO +125°C)
3.0
3.2
3.4
3.6
3.8
4.0
4.2
4.4
4.6
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Period (ms)
Longest
Typical (25°C)
Shortest (85°C)
Shortest (125°C)PIC18F2420/2520/4420/4520
DS39631E-page 382 © 2008 Microchip Technology Inc.
NOTES:© 2008 Microchip Technology Inc. DS39631E-page 383
PIC18F2420/2520/4420/4520
28.0 PACKAGING INFORMATION
28.1 Package Marking Information
28-Lead SPDIP
XXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F2520-I/SP
0810017
28-Lead SOIC
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F2520-E/SO
0810017
Legend: XX...X Customer-specific information
Y Year code (last digit of calendar year)
YY Year code (last 2 digits of calendar year)
WW Week code (week of January 1 is week ‘01’)
NNN Alphanumeric traceability code
Pb-free JEDEC designator for Matte Tin (Sn)
* This package is Pb-free. The Pb-free JEDEC designator ( )
can be found on the outer packaging for this package.
Note: In the event the full Microchip part number cannot be marked on one line, it will
be carried over to the next line, thus limiting the number of available
characters for customer-specific information.
e3
e3
e3
e3
28-Lead QFN
XXXXXXXX
XXXXXXXX
YYWWNNN
Example
18F2420
-I/ML
0810017
e3PIC18F2420/2520/4420/4520
DS39631E-page 384 © 2008 Microchip Technology Inc.
Package Marking Information (Continued)
44-Lead TQFP
XXXXXXXXXX
XXXXXXXXXX
XXXXXXXXXX
YYWWNNN
Example
PIC18F4420
-I/PT
0810017
XXXXXXXXXX
44-Lead QFN
XXXXXXXXXX
XXXXXXXXXX
YYWWNNN
PIC18F4520
Example
-I/ML
0810017
e3
e3
40-Lead PDIP
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F4420-I/P
0810017
© 2006 Microchip Technology Inc. DS39564C
PIC18FXX2
Data Sheet
High-Performance, Enhanced Flash
Microcontrollers with 10-Bit A/DDS39564C-page ii © 2006 Microchip Technology Inc.
Information contained in this publication regarding device
applications and the like is provided only for your convenience
and may be superseded by updates. It is your responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART,
PRO MATE, PowerSmart, rfPIC and SmartShunt are
registered trademarks of Microchip Technology Incorporated
in the U.S.A. and other countries.
AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB,
SEEVAL, SmartSensor and The Embedded Control Solutions
Company are registered trademarks of Microchip Technology
Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, ECAN,
ECONOMONITOR, FanSense, FlexROM, fuzzyLAB,
In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active
Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, PICkit,
PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal,
PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB,
rfPICDEM, Select Mode, Smart Serial, SmartTel, Total
Endurance, UNI/O, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2006, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
Printed on recycled paper.
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona, Gresham, Oregon and Mountain View, California. The
Company’s quality system processes and procedures are for its
PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial
EEPROMs, microperipherals, nonvolatile memory and analog
products. In addition, Microchip’s quality system for the design and
manufacture of development systems is ISO 9001:2000 certified.© 2006 Microchip Technology Inc. DS39564C-page 1
PIC18FXX2
High Performance RISC CPU:
• C compiler optimized architecture/instruction set
- Source code compatible with the PIC16 and
PIC17 instruction sets
• Linear program memory addressing to 32 Kbytes
• Linear data memory addressing to 1.5 Kbytes
• Up to 10 MIPs operation:
- DC - 40 MHz osc./clock input
- 4 MHz - 10 MHz osc./clock input with PLL active
• 16-bit wide instructions, 8-bit wide data path
• Priority levels for interrupts
• 8 x 8 Single Cycle Hardware Multiplier
Peripheral Features:
• High current sink/source 25 mA/25 mA
• Three external interrupt pins
• Timer0 module: 8-bit/16-bit timer/counter with
8-bit programmable prescaler
• Timer1 module: 16-bit timer/counter
• Timer2 module: 8-bit timer/counter with 8-bit
period register (time-base for PWM)
• Timer3 module: 16-bit timer/counter
• Secondary oscillator clock option - Timer1/Timer3
• Two Capture/Compare/PWM (CCP) modules.
CCP pins that can be configured as:
- Capture input: capture is 16-bit,
max. resolution 6.25 ns (TCY/16)
- Compare is 16-bit, max. resolution 100 ns (TCY)
- PWM output: PWM resolution is 1- to 10-bit,
max. PWM freq. @: 8-bit resolution = 156 kHz
10-bit resolution = 39 kHz
• Master Synchronous Serial Port (MSSP) module,
Two modes of operation:
- 3-wire SPI™ (supports all 4 SPI modes)
- I2C™ Master and Slave mode
Peripheral Features (Continued):
• Addressable USART module:
- Supports RS-485 and RS-232
• Parallel Slave Port (PSP) module
Analog Features:
• Compatible 10-bit Analog-to-Digital Converter
module (A/D) with:
- Fast sampling rate
- Conversion available during SLEEP
- Linearity ≤ 1 LSb
• Programmable Low Voltage Detection (PLVD)
- Supports interrupt on-Low Voltage Detection
• Programmable Brown-out Reset (BOR)
Special Microcontroller Features:
• 100,000 erase/write cycle Enhanced FLASH
program memory typical
• 1,000,000 erase/write cycle Data EEPROM
memory
• FLASH/Data EEPROM Retention: > 40 years
• Self-reprogrammable under software control
• Power-on Reset (POR), Power-up Timer (PWRT)
and Oscillator Start-up Timer (OST)
• Watchdog Timer (WDT) with its own On-Chip RC
Oscillator for reliable operation
• Programmable code protection
• Power saving SLEEP mode
• Selectable oscillator options including:
- 4X Phase Lock Loop (of primary oscillator)
- Secondary Oscillator (32 kHz) clock input
• Single supply 5V In-Circuit Serial Programming™
(ICSP™) via two pins
• In-Circuit Debug (ICD) via two pins
CMOS Technology:
• Low power, high speed FLASH/EEPROM
technology
• Fully static design
• Wide operating voltage range (2.0V to 5.5V)
• Industrial and Extended temperature ranges
• Low power consumption:
- < 1.6 mA typical @ 5V, 4 MHz
- 25 μA typical @ 3V, 32 kHz
- < 0.2 μA typical standby current
Device
On-Chip Program
Memory On-Chip
RAM
(bytes)
Data
EEPROM
FLASH (bytes)
(bytes)
# Single Word
Instructions
PIC18F242 16K 8192 768 256
PIC18F252 32K 16384 1536 256
PIC18F442 16K 8192 768 256
PIC18F452 32K 16384 1536 256
28/40-pin High Performance, Enhanced FLASH
Microcontrollers with 10-Bit A/DPIC18FXX2
DS39564C-page 2 © 2006 Microchip Technology Inc.
Pin Diagrams
10
11
12
13
14
15
16
1718
19
20
21
22
23
24
25
26
44
8
7
6
5
4
3
2
1
27
28
29
30
31
32
33
34
35
36
37
38
39
43
42
41
40
9
PIC18F442
RA4/T0CKI
RA5/AN4/SS/LVDIN
RE0/RD/AN5
OSC2/CLKO/RA6
NC
RE1/WR/AN6
RE2/CS/AN7
VDD
OSC1/CLKI
RB3/CCP2* RB2/INT2
RB1/INT1
RB0/INT0
VDD
VSS
RD7/PSP7
RD6/PSP6
RD5/PSP5
RD4/PSP4
RC7/RX/DT
RA3/AN3/VREF+
RA2/AN2/VREFRA1/AN1
RA0/AN0
MCLR/VPP
NC
RB7/PGD
RB6/PGC
RB5/PGM
RB4
NC
RC1/T1OSI/CCP2
RC2/CCP1
RC3/SCK/SCL
RD0/PSP0
RD1/PSP1
RD2/PSP2
RD3/PSP3
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
NC
*
10
11
2
3
4
5
6
1
12
13
14
15
18
19
20
21
22
38
8
7
44
43
42
41
40
39
16
17
29
30
31
32
33
23
24
25
26
27
28
36
35
34
9
PIC18F44237
RA3/AN3/VREF+
RA2/AN2/VREFMCLR
RA0/AN0 RA1/AN1 /VPP
NC
NC
RB4
RB5/PGM
RB6/PGC
RB7/PGD
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
RD1/PSP1
RD0/PSP0
RC3/SCK/SCL
RC2/CCP1
RC1/T1OSI/CCP2*
NC
NC
RC0/T1OSO/T1CKI
OSC2/CLKO/RA6
OSC1/CLKI
VSS
VDD
RE2/AN7/CS
RE1/AN6/WR
RE0/AN5/RD
RA5/AN4/SS/LVDIN
RA4/T0CKI
RC7/RX/DT
RD4/PSP4
RD5/PSP5
RD6/PSP6
RD7/PSP7
VSS
VDD
RB0/INT0
RB1/INT1
RB2/INT2
RB3/CCP2*
PLCC
TQFP
* RB3 is the alternate pin for the CCP2 pin multiplexing.
VSS
RC0/T1OSO/T1CKI
PIC18F452
PIC18F452© 2006 Microchip Technology Inc. DS39564C-page 3
PIC18FXX2
Pin Diagrams (Cont.’d)
RB7/PGD
RB6/PGC
RB5/PGM
RB4
RB3/CCP2*
RB2/INT2
RB1/INT1
RB0/INT0
VDD
VSS
RD7/PSP7
RD6/PSP6
RD5/PSP5
RD4/PSP4
RC7/RX/DT
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
RD3/PSP3
RD2/PSP2
MCLR/VPP
RA0/AN0
RA1/AN1
RA2/AN2/VREFRA3/AN3/VREF+
RA4/T0CKI
RA5/AN4/SS/LVDIN
RE0/RD/AN5
RE1/WR/AN6
RE2/CS/AN7
VDD
VSS
OSC1/CLKI
OSC2/CLKO/RA6
RC0/T1OSO/T1CKI
RC1/T1OSI/CCP2*
RC2/CCP1
RC3/SCK/SCL
RD0/PSP0
RD1/PSP1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
40
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
PIC18F442
10
PIC18F242
11
2
3
4
5
6
1
8
7
9
12
13
14 15
16
17
18
19
20
23
24
25
26
27
28
22
21
MCLR/VPP
RA0/AN0
RA1/AN1
RA2/AN2/VREFRA3/AN3/VREF+
RA4/T0CKI
RA5/AN4/SS/LVDIN
VSS
OSC1/CLKI
OSC2/CLKO/RA6
RC0/T1OSO/T1CKI
RC1/T1OSI/CCP2*
RC2/CCP1
RC3/SCK/SCL
RB7/PGD
RB6/PGC
RB5/PGM
RB4
RB3/CCP2*
RB2/INT2
RB1/INT1
RB0/INT0
VDD
VSS
RC7/RX/DT
RC6/TX/CK
RC5/SDO
RC4/SDI/SDA
* RB3 is the alternate pin for the CCP2 pin multiplexing.
DIP
DIP, SOIC
Note: Pin compatible with 40-pin PIC16C7X devices.
PIC18F452
PIC18F252PIC18FXX2
DS39564C-page 4 © 2006 Microchip Technology Inc.
Table of Contents
1.0 Device Overview .......................................................................................................................................................................... 7
2.0 Oscillator Configurations ............................................................................................................................................................ 17
3.0 Reset .......................................................................................................................................................................................... 25
4.0 Memory Organization ................................................................................................................................................................. 35
5.0 FLASH Program Memory ........................................................................................................................................................... 55
6.0 Data EEPROM Memory ............................................................................................................................................................. 65
7.0 8 X 8 Hardware Multiplier ........................................................................................................................................................... 71
8.0 Interrupts .................................................................................................................................................................................... 73
9.0 I/O Ports ..................................................................................................................................................................................... 87
10.0 Timer0 Module ......................................................................................................................................................................... 103
11.0 Timer1 Module ......................................................................................................................................................................... 107
12.0 Timer2 Module ......................................................................................................................................................................... 111
13.0 Timer3 Module ......................................................................................................................................................................... 113
14.0 Capture/Compare/PWM (CCP) Modules ................................................................................................................................. 117
15.0 Master Synchronous Serial Port (MSSP) Module .................................................................................................................... 125
16.0 Addressable Universal Synchronous Asynchronous Receiver Transmitter (USART).............................................................. 165
17.0 Compatible 10-bit Analog-to-Digital Converter (A/D) Module................................................................................................... 181
18.0 Low Voltage Detect .................................................................................................................................................................. 189
19.0 Special Features of the CPU.................................................................................................................................................... 195
20.0 Instruction Set Summary .......................................................................................................................................................... 211
21.0 Development Support............................................................................................................................................................... 253
22.0 Electrical Characteristics .......................................................................................................................................................... 259
23.0 DC and AC Characteristics Graphs and Tables....................................................................................................................... 289
24.0 Packaging Information.............................................................................................................................................................. 305
Appendix A: Revision History............................................................................................................................................................ 313
Appendix B: Device Differences........................................................................................................................................................ 313
Appendix C: Conversion Considerations........................................................................................................................................... 314
Appendix D: Migration from Baseline to Enhanced Devices ............................................................................................................. 314
Appendix E: Migration from Mid-range to Enhanced Devices........................................................................................................... 315
Appendix F: Migration from High-end to Enhanced Devices ............................................................................................................ 315
Index .................................................................................................................................................................................................. 317
On-Line Support................................................................................................................................................................................. 327
Reader Response .............................................................................................................................................................................. 328
PIC18FXX2 Product Identification System......................................................................................................................................... 329© 2006 Microchip Technology Inc. DS39564C-page 5
PIC18FXX2
TO OUR VALUED CUSTOMERS
It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip
products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined and
enhanced as new volumes and updates are introduced.
If you have any questions or comments regarding this publication, please contact the Marketing Communications Department via
E-mail at docerrors@microchip.com or fax the Reader Response Form in the back of this data sheet to (480) 792-4150. We
welcome your feedback.
Most Current Data Sheet
To obtain the most up-to-date version of this data sheet, please register at our Worldwide Web site at:
http://www.microchip.com
You can determine the version of a data sheet by examining its literature number found on the bottom outside corner of any page.
The last character of the literature number is the version number, (e.g., DS30000A is version A of document DS30000).
Errata
An errata sheet, describing minor operational differences from the data sheet and recommended workarounds, may exist for current
devices. As device/documentation issues become known to us, we will publish an errata sheet. The errata will specify the revision
of silicon and revision of document to which it applies.
To determine if an errata sheet exists for a particular device, please check with one of the following:
• Microchip’s Worldwide Web site; http://www.microchip.com
• Your local Microchip sales office (see last page)
When contacting a sales office, please specify which device, revision of silicon and data sheet (include literature number) you are
using.
Customer Notification System
Register on our web site at www.microchip.com to receive the most current information on all of our products.PIC18FXX2
DS39564C-page 6 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 7
PIC18FXX2
1.0 DEVICE OVERVIEW
This document contains device specific information for
the following devices:
These devices come in 28-pin and 40/44-pin packages.
The 28-pin devices do not have a Parallel Slave Port
(PSP) implemented and the number of Analog-toDigital
(A/D) converter input channels is reduced to 5.
An overview of features is shown in Table 1-1.
The following two figures are device block diagrams
sorted by pin count: 28-pin for Figure 1-1 and 40/44-pin
for Figure 1-2. The 28-pin and 40/44-pin pinouts are
listed in Table 1-2 and Table 1-3, respectively.
TABLE 1-1: DEVICE FEATURES
• PIC18F242 • PIC18F442
• PIC18F252 • PIC18F452
Features PIC18F242 PIC18F252 PIC18F442 PIC18F452
Operating Frequency DC - 40 MHz DC - 40 MHz DC - 40 MHz DC - 40 MHz
Program Memory (Bytes) 16K 32K 16K 32K
Program Memory (Instructions) 8192 16384 8192 16384
Data Memory (Bytes) 768 1536 768 1536
Data EEPROM Memory (Bytes) 256 256 256 256
Interrupt Sources 17 17 18 18
I/O Ports Ports A, B, C Ports A, B, C Ports A, B, C, D, E Ports A, B, C, D, E
Timers 4 4 4 4
Capture/Compare/PWM Modules 2 2 2 2
Serial Communications
MSSP,
Addressable
USART
MSSP,
Addressable
USART
MSSP,
Addressable
USART
MSSP,
Addressable
USART
Parallel Communications — — PSP PSP
10-bit Analog-to-Digital Module 5 input channels 5 input channels 8 input channels 8 input channels
RESETS (and Delays)
POR, BOR,
RESET Instruction,
Stack Full,
Stack Underflow
(PWRT, OST)
POR, BOR,
RESET Instruction,
Stack Full,
Stack Underflow
(PWRT, OST)
POR, BOR,
RESET Instruction,
Stack Full,
Stack Underflow
(PWRT, OST)
POR, BOR,
RESET Instruction,
Stack Full,
Stack Underflow
(PWRT, OST)
Programmable Low Voltage
Detect
Yes Yes Yes Yes
Programmable Brown-out Reset Yes Yes Yes Yes
Instruction Set 75 Instructions 75 Instructions 75 Instructions 75 Instructions
Packages 28-pin DIP
28-pin SOIC
28-pin DIP
28-pin SOIC
40-pin DIP
44-pin PLCC
44-pin TQFP
40-pin DIP
44-pin PLCC
44-pin TQFPPIC18FXX2
DS39564C-page 8 © 2006 Microchip Technology Inc.
FIGURE 1-1: PIC18F2X2 BLOCK DIAGRAM
Instruction
Decode &
Control
PORTA
PORTB
PORTC
RA4/T0CKI
RA5/AN4/SS/LVDIN
RC0/T1OSO/T1CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1
RC3/SCK/SCL
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
RC7/RX/DT
Note 1: Optional multiplexing of CCP2 input/output with RB3 is enabled by selection of configuration bit.
2: The high order bits of the Direct Address for the RAM are from the BSR register (except for the MOVFF instruction).
3: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions. The multiplexing combinations
are device dependent.
Addressable
CCP1 Synchronous
Timer0 Timer1 Timer2
Serial Port
RA3/AN3/VREF+
RA2/AN2/VREFRA1/AN1
RA0/AN0
A/D Converter
Data Latch
Data RAM
Address Latch
Address<12>
12(2)
BSR FSR0
FSR1
FSR2
4 12 4
PCH PCL
PCLATH
8
31 Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
WREG
8
BIT OP
8 8
ALU<8>
8
Address Latch
Program Memory
(up to 2 Mbytes)
Data Latch
21
21
16
8
8
8
inc/dec logic
21
8
Data Bus<8>
8
Instruction
12
3
ROM Latch
Timer3
CCP2
Bank0, F
PCLATU
PCU
RA6
USART
Master
8
Register
Table Latch
Table Pointer
inc/dec
Decode logic
RB0/INT0
RB4
RB1/INT1
RB2/INT2
RB3/CCP2(1)
RB5/PGM
RB6/PCG
RB7/PGD
Data EEPROM
Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
OSC1/CLKI
OSC2/CLKO
MCLR
VDD, VSS
Brown-out
Reset
Timing
Generation
4X PLL
T1OSCI
T1OSCO
Precision
Reference
Voltage
Low Voltage
Programming
In-Circuit
Debugger© 2006 Microchip Technology Inc. DS39564C-page 9
PIC18FXX2
FIGURE 1-2: PIC18F4X2 BLOCK DIAGRAM
Power-up
Timer
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
Instruction
Decode &
Control
OSC1/CLKI
OSC2/CLKO
MCLR
VDD, VSS
PORTA
PORTB
PORTC
RA4/T0CKI
RA5/AN4/SS/LVDIN
RB0/INT0
RB4
RC0/T1OSO/T1CKI
RC1/T1OSI/CCP2(1)
RC2/CCP1
RC3/SCK/SCL
RC4/SDI/SDA
RC5/SDO
RC6/TX/CK
RC7/RX/DT
Brown-out
Reset
Note 1: Optional multiplexing of CCP2 input/output with RB3 is enabled by selection of configuration bit.
2: The high order bits of the Direct Address for the RAM are from the BSR register (except for the MOVFF instruction).
3: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions. The multiplexing combinations
are device dependent.
Addressable CCP1
Master
Timer0 Timer1 Timer2
Serial Port
RA3/AN3/VREF+
RA2/AN2/VREFRA1/AN1
RA0/AN0
Parallel Slave Port
Timing
Generation
4X PLL
A/D Converter
RB1/INT1
Data Latch
Data RAM
(up to 4K
address reach)
Address Latch
Address<12>
12(2)
BSR FSR0 Bank0, F
FSR1
FSR2
4 12 4
PCH PCL
PCLATH
8
31 Level Stack
Program Counter
PRODH PRODL
8 x 8 Multiply
WREG
8
BIT OP
8 8
ALU<8>
8
Address Latch
Program Memory
(up to 2 Mbytes)
Data Latch
21
21
16
8
8
8
inc/dec logic
21
8
Data Bus<8>
Table Latch
8
Instruction
12
3
ROM Latch
Timer3
PORTD
PORTE
RE0/AN5/RD
RE1/AN6/WR
RE2/AN7/CS
CCP2
RB2/INT2
RB3/CCP2(1)
T1OSCI
T1OSCO
PCLATU
PCU
RA6
Precision
Reference
Voltage
Synchronous USART
Register
8
Table Pointer
inc/dec
logic Decode
RD0/PSP0
RD1/PSP1
RD2/PSP2
RD3/PSP3
RD4/PSP4
RD5/PSP5
RD6/PSP6
RD7/PSP7
Low Voltage
Programming
In-Circuit
Debugger
Data EEPROM
RB5/PGM
RB6/PCG
RB7/PGDPIC18FXX2
DS39564C-page 10 © 2006 Microchip Technology Inc.
TABLE 1-2: PIC18F2X2 PINOUT I/O DESCRIPTIONS
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP SOIC
MCLR/VPP
MCLR
VPP
1 1
I
I
ST
ST
Master Clear (input) or high voltage ICSP programming
enable pin.
Master Clear (Reset) input. This pin is an active low
RESET to the device.
High voltage ICSP programming enable pin.
NC — — — — These pins should be left unconnected.
OSC1/CLKI
OSC1
CLKI
9 9
I
I
ST
CMOS
Oscillator crystal or external clock input.
Oscillator crystal input or external clock source input.
ST buffer when configured in RC mode, CMOS otherwise.
External clock source input. Always associated with
pin function OSC1. (See related OSC1/CLKI,
OSC2/CLKO pins.)
OSC2/CLKO/RA6
OSC2
CLKO
RA6
10 10
O
O
I/O
—
—
TTL
Oscillator crystal or clock output.
Oscillator crystal output. Connects to crystal or
resonator in Crystal Oscillator mode.
In RC mode, OSC2 pin outputs CLKO which has 1/4
the frequency of OSC1, and denotes the instruction
cycle rate.
General Purpose I/O pin.
PORTA is a bi-directional I/O port.
RA0/AN0
RA0
AN0
2 2
I/O
I
TTL
Analog
Digital I/O.
Analog input 0.
RA1/AN1
RA1
AN1
3 3
I/O
I
TTL
Analog
Digital I/O.
Analog input 1.
RA2/AN2/VREFRA2
AN2
VREF-
4 4
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 2.
A/D Reference Voltage (Low) input.
RA3/AN3/VREF+
RA3
AN3
VREF+
5 5
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 3.
A/D Reference Voltage (High) input.
RA4/T0CKI
RA4
T0CKI
6 6
I/O
I
ST/OD
ST
Digital I/O. Open drain when configured as output.
Timer0 external clock input.
RA5/AN4/SS/LVDIN
RA5
AN4
SS
LVDIN
7 7
I/O
I
I
I
TTL
Analog
ST
Analog
Digital I/O.
Analog input 4.
SPI Slave Select input.
Low Voltage Detect Input.
RA6 See the OSC2/CLKO/RA6 pin.
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) © 2006 Microchip Technology Inc. DS39564C-page 11
PIC18FXX2
PORTB is a bi-directional I/O port. PORTB can be software
programmed for internal weak pull-ups on all inputs.
RB0/INT0
RB0
INT0
21 21
I/O
I
TTL
ST
Digital I/O.
External Interrupt 0.
RB1/INT1
RB1
INT1
22 22
I/O
I
TTL
ST External Interrupt 1.
RB2/INT2
RB2
INT2
23 23
I/O
I
TTL
ST
Digital I/O.
External Interrupt 2.
RB3/CCP2
RB3
CCP2
24 24
I/O
I/O
TTL
ST
Digital I/O.
Capture2 input, Compare2 output, PWM2 output.
RB4 25 25 I/O TTL Digital I/O.
Interrupt-on-change pin.
RB5/PGM
RB5
PGM
26 26
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
Low Voltage ICSP programming enable pin.
RB6/PGC
RB6
PGC
27 27
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming clock pin.
RB7/PGD
RB7
PGD
28 28
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming data pin.
TABLE 1-2: PIC18F2X2 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP SOIC
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) PIC18FXX2
DS39564C-page 12 © 2006 Microchip Technology Inc.
PORTC is a bi-directional I/O port.
RC0/T1OSO/T1CKI
RC0
T1OSO
T1CKI
11 11
I/O
O
I
ST
—
ST
Digital I/O.
Timer1 oscillator output.
Timer1/Timer3 external clock input.
RC1/T1OSI/CCP2
RC1
T1OSI
CCP2
12 12
I/O
I
I/O
ST
CMOS
ST
Digital I/O.
Timer1 oscillator input.
Capture2 input, Compare2 output, PWM2 output.
RC2/CCP1
RC2
CCP1
13 13
I/O
I/O
ST
ST
Digital I/O.
Capture1 input/Compare1 output/PWM1 output.
RC3/SCK/SCL
RC3
SCK
SCL
14 14
I/O
I/O
I/O
ST
ST
ST
Digital I/O.
Synchronous serial clock input/output for SPI mode.
Synchronous serial clock input/output for I2C mode
RC4/SDI/SDA
RC4
SDI
SDA
15 15
I/O
I
I/O
ST
ST
ST
Digital I/O.
SPI Data In.
I
2C Data I/O.
RC5/SDO
RC5
SDO
16 16
I/O
O
ST
—
Digital I/O.
SPI Data Out.
RC6/TX/CK
RC6
TX
CK
17 17
I/O
O
I/O
ST
—
ST
Digital I/O.
USART Asynchronous Transmit.
USART Synchronous Clock (see related RX/DT).
RC7/RX/DT
RC7
RX
DT
18 18
I/O
I
I/O
ST
ST
ST
Digital I/O.
USART Asynchronous Receive.
USART Synchronous Data (see related TX/CK).
VSS 8, 19 8, 19 P — Ground reference for logic and I/O pins.
VDD 20 20 P — Positive supply for logic and I/O pins.
TABLE 1-2: PIC18F2X2 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP SOIC
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) © 2006 Microchip Technology Inc. DS39564C-page 13
PIC18FXX2
TABLE 1-3: PIC18F4X2 PINOUT I/O DESCRIPTIONS
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP PLCC TQFP
MCLR/VPP
MCLR
VPP
1 2 18
I
I
ST
ST
Master Clear (input) or high voltage ICSP
programming enable pin.
Master Clear (Reset) input. This pin is an active
low RESET to the device.
High voltage ICSP programming enable pin.
NC — — — These pins should be left unconnected.
OSC1/CLKI
OSC1
CLKI
13 14 30
I
I
ST
CMOS
Oscillator crystal or external clock input.
Oscillator crystal input or external clock source
input. ST buffer when configured in RC mode,
CMOS otherwise.
External clock source input. Always associated
with pin function OSC1. (See related OSC1/CLKI,
OSC2/CLKO pins.)
OSC2/CLKO/RA6
OSC2
CLKO
RA6
14 15 31
O
O
I/O
—
—
TTL
Oscillator crystal or clock output.
Oscillator crystal output. Connects to crystal
or resonator in Crystal Oscillator mode.
In RC mode, OSC2 pin outputs CLKO,
which has 1/4 the frequency of OSC1 and
denotes the instruction cycle rate.
General Purpose I/O pin.
PORTA is a bi-directional I/O port.
RA0/AN0
RA0
AN0
2 3 19
I/O
I
TTL
Analog
Digital I/O.
Analog input 0.
RA1/AN1
RA1
AN1
3 4 20
I/O
I
TTL
Analog
Digital I/O.
Analog input 1.
RA2/AN2/VREFRA2
AN2
VREF-
4 5 21
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 2.
A/D Reference Voltage (Low) input.
RA3/AN3/VREF+
RA3
AN3
VREF+
5 6 22
I/O
I
I
TTL
Analog
Analog
Digital I/O.
Analog input 3.
A/D Reference Voltage (High) input.
RA4/T0CKI
RA4
T0CKI
6 7 23
I/O
I
ST/OD
ST
Digital I/O. Open drain when configured as output.
Timer0 external clock input.
RA5/AN4/SS/LVDIN
RA5
AN4
SS
LVDIN
7 8 24
I/O
I
I
I
TTL
Analog
ST
Analog
Digital I/O.
Analog input 4.
SPI Slave Select input.
Low Voltage Detect Input.
RA6 (See the OSC2/CLKO/RA6 pin.)
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) PIC18FXX2
DS39564C-page 14 © 2006 Microchip Technology Inc.
PORTB is a bi-directional I/O port. PORTB can be
software programmed for internal weak pull-ups on all
inputs.
RB0/INT0
RB0
INT0
33 36 8
I/O
I
TTL
ST
Digital I/O.
External Interrupt 0.
RB1/INT1
RB1
INT1
34 37 9
I/O
I
TTL
ST External Interrupt 1.
RB2/INT2
RB2
INT2
35 38 10
I/O
I
TTL
ST
Digital I/O.
External Interrupt 2.
RB3/CCP2
RB3
CCP2
36 39 11
I/O
I/O
TTL
ST
Digital I/O.
Capture2 input, Compare2 output, PWM2 output.
RB4 37 41 14 I/O TTL Digital I/O. Interrupt-on-change pin.
RB5/PGM
RB5
PGM
38 42 15
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
Low Voltage ICSP programming enable pin.
RB6/PGC
RB6
PGC
39 43 16
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming clock
pin.
RB7/PGD
RB7
PGD
40 44 17
I/O
I/O
TTL
ST
Digital I/O. Interrupt-on-change pin.
In-Circuit Debugger and ICSP programming data
pin.
TABLE 1-3: PIC18F4X2 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP PLCC TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) © 2006 Microchip Technology Inc. DS39564C-page 15
PIC18FXX2
PORTC is a bi-directional I/O port.
RC0/T1OSO/T1CKI
RC0
T1OSO
T1CKI
15 16 32
I/O
O
I
ST
—
ST
Digital I/O.
Timer1 oscillator output.
Timer1/Timer3 external clock input.
RC1/T1OSI/CCP2
RC1
T1OSI
CCP2
16 18 35
I/O
I
I/O
ST
CMOS
ST
Digital I/O.
Timer1 oscillator input.
Capture2 input, Compare2 output, PWM2 output.
RC2/CCP1
RC2
CCP1
17 19 36
I/O
I/O
ST
ST
Digital I/O.
Capture1 input/Compare1 output/PWM1 output.
RC3/SCK/SCL
RC3
SCK
SCL
18 20 37
I/O
I/O
I/O
ST
ST
ST
Digital I/O.
Synchronous serial clock input/output for
SPI mode.
Synchronous serial clock input/output for
I
2C mode.
RC4/SDI/SDA
RC4
SDI
SDA
23 25 42
I/O
I
I/O
ST
ST
ST
Digital I/O.
SPI Data In.
I
2C Data I/O.
RC5/SDO
RC5
SDO
24 26 43
I/O
O
ST
—
Digital I/O.
SPI Data Out.
RC6/TX/CK
RC6
TX
CK
25 27 44
I/O
O
I/O
ST
—
ST
Digital I/O.
USART Asynchronous Transmit.
USART Synchronous Clock (see related RX/DT).
RC7/RX/DT
RC7
RX
DT
26 29 1
I/O
I
I/O
ST
ST
ST
Digital I/O.
USART Asynchronous Receive.
USART Synchronous Data (see related TX/CK).
TABLE 1-3: PIC18F4X2 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP PLCC TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) PIC18FXX2
DS39564C-page 16 © 2006 Microchip Technology Inc.
PORTD is a bi-directional I/O port, or a Parallel Slave
Port (PSP) for interfacing to a microprocessor port.
These pins have TTL input buffers when PSP module
is enabled.
RD0/PSP0 19 21 38 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD1/PSP1 20 22 39 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD2/PSP2 21 23 40 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD3/PSP3 22 24 41 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD4/PSP4 27 30 2 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD5/PSP5 28 31 3 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD6/PSP6 29 32 4 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
RD7/PSP7 30 33 5 I/O ST
TTL
Digital I/O.
Parallel Slave Port Data.
PORTE is a bi-directional I/O port.
RE0/RD/AN5
RE0
RD
AN5
8 9 25 I/O
ST
TTL
Analog
Digital I/O.
Read control for parallel slave port
(see also WR and CS pins).
Analog input 5.
RE1/WR/AN6
RE1
WR
AN6
9 10 26 I/O
ST
TTL
Analog
Digital I/O.
Write control for parallel slave port
(see CS and RD pins).
Analog input 6.
RE2/CS/AN7
RE2
CS
AN7
10 11 27 I/O
ST
TTL
Analog
Digital I/O.
Chip Select control for parallel slave port
(see related RD and WR).
Analog input 7.
VSS 12, 31 13, 34 6, 29 P — Ground reference for logic and I/O pins.
VDD 11, 32 12, 35 7, 28 P — Positive supply for logic and I/O pins.
TABLE 1-3: PIC18F4X2 PINOUT I/O DESCRIPTIONS (CONTINUED)
Pin Name
Pin Number Pin
Type
Buffer
Type Description
DIP PLCC TQFP
Legend: TTL = TTL compatible input CMOS = CMOS compatible input or output
ST = Schmitt Trigger input with CMOS levels I = Input
O = Output P = Power
OD = Open Drain (no P diode to VDD) © 2006 Microchip Technology Inc. DS39564C-page 17
PIC18FXX2
2.0 OSCILLATOR
CONFIGURATIONS
2.1 Oscillator Types
The PIC18FXX2 can be operated in eight different
Oscillator modes. The user can program three configuration
bits (FOSC2, FOSC1, and FOSC0) to select one
of these eight modes:
1. LP Low Power Crystal
2. XT Crystal/Resonator
3. HS High Speed Crystal/Resonator
4. HS + PLL High Speed Crystal/Resonator
with PLL enabled
5. RC External Resistor/Capacitor
6. RCIO External Resistor/Capacitor with
I/O pin enabled
7. EC External Clock
8. ECIO External Clock with I/O pin
enabled
2.2 Crystal Oscillator/Ceramic
Resonators
In XT, LP, HS or HS+PLL Oscillator modes, a crystal or
ceramic resonator is connected to the OSC1 and
OSC2 pins to establish oscillation. Figure 2-1 shows
the pin connections.
The PIC18FXX2 oscillator design requires the use of a
parallel cut crystal.
FIGURE 2-1: CRYSTAL/CERAMIC
RESONATOR OPERATION
(HS, XT OR LP
CONFIGURATION)
TABLE 2-1: CAPACITOR SELECTION FOR
CERAMIC RESONATORS
Note: Use of a series cut crystal may give a frequency
out of the crystal manufacturers
specifications.
Note 1: See Table 2-1 and Table 2-2 for
recommended values of C1 and C2.
2: A series resistor (RS) may be required for
AT strip cut crystals.
3: RF varies with the Oscillator mode chosen.
C1(1)
C2(1)
XTAL
OSC2
OSC1
RF(3)
SLEEP
To
Logic
PIC18FXXX
RS(2)
Internal
Ranges Tested:
Mode Freq C1 C2
XT 455 kHz
2.0 MHz
4.0 MHz
68 - 100 pF
15 - 68 pF
15 - 68 pF
68 - 100 pF
15 - 68 pF
15 - 68 pF
HS 8.0 MHz
16.0 MHz
10 - 68 pF
10 - 22 pF
10 - 68 pF
10 - 22 pF
These values are for design guidance only.
See notes following this table.
Resonators Used:
455 kHz Panasonic EFO-A455K04B ± 0.3%
2.0 MHz Murata Erie CSA2.00MG ± 0.5%
4.0 MHz Murata Erie CSA4.00MG ± 0.5%
8.0 MHz Murata Erie CSA8.00MT ± 0.5%
16.0 MHz Murata Erie CSA16.00MX ± 0.5%
All resonators used did not have built-in capacitors.
Note 1: Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time.
2: When operating below 3V VDD, or when
using certain ceramic resonators at any
voltage, it may be necessary to use
high-gain HS mode, try a lower frequency
resonator, or switch to a crystal oscillator.
3: Since each resonator/crystal has its own
characteristics, the user should consult the
resonator/crystal manufacturer for appropriate
values of external components, or
verify oscillator performance. PIC18FXX2
DS39564C-page 18 © 2006 Microchip Technology Inc.
TABLE 2-2: CAPACITOR SELECTION FOR
CRYSTAL OSCILLATOR
An external clock source may also be connected to the
OSC1 pin in the HS, XT and LP modes, as shown in
Figure 2-2.
FIGURE 2-2: EXTERNAL CLOCK INPUT
OPERATION (HS, XT OR LP
OSC CONFIGURATION)
2.3 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, the resistor (REXT) and capacitor (CEXT) values
and the operating temperature. 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 R
and C components used. Figure 2-3 shows how the
R/C combination is connected.
In the RC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes or to synchronize other
logic.
FIGURE 2-3: RC OSCILLATOR MODE
The RCIO Oscillator mode functions like the RC mode,
except that the OSC2 pin becomes an additional general
purpose I/O pin. The I/O pin becomes bit 6 of
PORTA (RA6).
Ranges Tested:
Mode Freq C1 C2
LP 32.0 kHz 33 pF 33 pF
200 kHz 15 pF 15 pF
XT 200 kHz 22-68 pF 22-68 pF
1.0 MHz 15 pF 15 pF
4.0 MHz 15 pF 15 pF
HS 4.0 MHz 15 pF 15 pF
8.0 MHz 15-33 pF 15-33 pF
20.0 MHz 15-33 pF 15-33 pF
25.0 MHz 15-33 pF 15-33 pF
These values are for design guidance only.
See notes following this table.
Crystals Used
32.0 kHz Epson C-001R32.768K-A ± 20 PPM
200 kHz STD XTL 200.000KHz ± 20 PPM
1.0 MHz ECS ECS-10-13-1 ± 50 PPM
4.0 MHz ECS ECS-40-20-1 ± 50 PPM
8.0 MHz Epson CA-301 8.000M-C ± 30 PPM
20.0 MHz Epson CA-301 20.000M-C ± 30 PPM
Note 1: Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time.
2: Rs may be required in HS mode, as well
as XT mode, to avoid overdriving crystals
with low drive level specification.
3: Since each resonator/crystal has its own
characteristics, the user should consult the
resonator/crystal manufacturer for appropriate
values of external components., or
verify oscillator performance.
OSC1
Open OSC2
Clock from
Ext. System PIC18FXXX
Note: If the oscillator frequency divided by 4 signal
is not required in the application, it is
recommended to use RCIO mode to save
current.
OSC2/CLKO
CEXT
REXT
PIC18FXXX
OSC1
FOSC/4
Internal
Clock
VDD
VSS
Recommended values:3 kΩ ≤ REXT ≤ 100 kΩ
CEXT > 20pF© 2006 Microchip Technology Inc. DS39564C-page 19
PIC18FXX2
2.4 External Clock Input
The EC and ECIO Oscillator modes require an external
clock source to be connected to the OSC1 pin. The
feedback device between OSC1 and OSC2 is turned
off in these modes to save current. There is no oscillator
start-up time required after a Power-on Reset or
after a recovery from SLEEP mode.
In the EC Oscillator mode, the oscillator frequency
divided by 4 is available on the OSC2 pin. This signal
may be used for test purposes or to synchronize other
logic. Figure 2-4 shows the pin connections for the EC
Oscillator mode.
FIGURE 2-4: EXTERNAL CLOCK INPUT
OPERATION
(EC CONFIGURATION)
The ECIO Oscillator mode functions like the EC mode,
except that the OSC2 pin becomes an additional general
purpose I/O pin. The I/O pin becomes bit 6 of
PORTA (RA6). Figure 2-5 shows the pin connections
for the ECIO Oscillator mode.
FIGURE 2-5: EXTERNAL CLOCK INPUT
OPERATION
(ECIO CONFIGURATION)
2.5 HS/PLL
A Phase Locked Loop 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 HS mode. If they are
programmed for any other mode, the PLL is not
enabled and the system clock will come directly from
OSC1.
The PLL is one of the modes of the FOSC<2:0> configuration
bits. The Oscillator mode is specified during
device programming.
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 TPLL.
FIGURE 2-6: PLL BLOCK DIAGRAM
OSC1
FOSC/4 OSC2
Clock from
Ext. System PIC18FXXX
OSC1
RA6 I/O (OSC2)
Clock from
Ext. System PIC18FXXX MUX
VCO Loop
Filter
Divide by 4
Crystal
Osc
OSC2
OSC1
PLL Enable
FIN
FOUT SYSCLK
Phase
Comparator
(from Configuration HS Osc
bit Register)PIC18FXX2
DS39564C-page 20 © 2006 Microchip Technology Inc.
2.6 Oscillator Switching Feature
The PIC18FXX2 devices include a feature that allows
the system clock source to be switched from the main
oscillator to an alternate low frequency clock source.
For the PIC18FXX2 devices, this alternate clock source
is the Timer1 oscillator. If a low frequency crystal (32
kHz, for example) has been attached to the Timer1
oscillator pins and the Timer1 oscillator has been
enabled, the device can switch to a Low Power Execution
mode. Figure 2-7 shows a block diagram of the
system clock sources. The clock switching feature is
enabled by programming the Oscillator Switching
Enable (OSCSEN) bit in Configuration Register1H to a
’0’. Clock switching is disabled in an erased device.
See Section 11.0 for further details of the Timer1 oscillator.
See Section 19.0 for Configuration Register
details.
FIGURE 2-7: DEVICE CLOCK SOURCES
PIC18FXXX
TOSC
4 x PLL
TT1P
TSCLK
Clock
Source MUX
TOSC/4
Timer1 Oscillator
T1OSCEN
Enable
Oscillator
T1OSO
T1OSI
Clock Source option
for other modules
OSC1
OSC2
SLEEP
Main Oscillator© 2006 Microchip Technology Inc. DS39564C-page 21
PIC18FXX2
2.6.1 SYSTEM CLOCK SWITCH BIT
The system clock source switching is performed under
software control. The system clock switch bit, SCS
(OSCCON<0>) controls the clock switching. When the
SCS bit is ’0’, the system clock source comes from the
main oscillator that is selected by the FOSC configuration
bits in Configuration Register1H. When the SCS bit
is set, the system clock source will come from the
Timer1 oscillator. The SCS bit is cleared on all forms of
RESET.
REGISTER 2-1: OSCCON REGISTER
Note: The Timer1 oscillator must be enabled and
operating 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.
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-1
— — — — — — — SCS
bit 7 bit 0
bit 7-1 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
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 ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 22 © 2006 Microchip Technology Inc.
2.6.2 OSCILLATOR TRANSITIONS
The PIC18FXX2 devices contain circuitry to prevent
“glitches” when switching between oscillator sources.
Essentially, the circuitry waits for eight rising edges of
the clock source that the processor is switching to. This
ensures that the new clock source is stable and that its
pulse width will not be less than the shortest pulse
width of the two clock sources.
A timing diagram indicating the transition from the main
oscillator to the Timer1 oscillator is shown in
Figure 2-8. The Timer1 oscillator is assumed to be running
all the time. After the SCS bit is set, the processor
is frozen at the next occurring Q1 cycle. After eight synchronization
cycles are counted from the Timer1 oscillator,
operation resumes. No additional delays are
required after the synchronization cycles.
FIGURE 2-8: TIMING DIAGRAM FOR TRANSITION FROM OSC1 TO TIMER1 OSCILLATOR
The sequence of events that takes place when switching
from the Timer1 oscillator to the main oscillator will
depend on the mode of the main oscillator. In addition
to eight clock cycles of the main oscillator, additional
delays may take place.
If the main oscillator is configured for an external crystal
(HS, XT, LP), then the transition will take place after
an oscillator start-up time (TOST) has occurred. A timing
diagram, indicating the transition from the Timer1 oscillator
to the main oscillator for HS, XT and LP modes, is
shown in Figure 2-9.
FIGURE 2-9: TIMING FOR TRANSITION BETWEEN TIMER1 AND OSC1 (HS, XT, LP)
Q2 Q3 Q4 Q1 Q2 Q3
OSC1
Internal
SCS
(OSCCON<0>)
Program PC PC + 2
Note 1: Delay on internal system clock is eight oscillator cycles for synchronization.
Q1
T1OSI
Q4 Q1
PC + 4
Q1
Tscs
Clock
Counter
System
Q2 Q3 Q4 Q1
TDLY
TT1P
TOSC
1 34 5678 2
Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3
OSC1
Internal System
SCS
(OSCCON<0>)
Program Counter PC PC + 2
Note 1: TOST = 1024 TOSC (drawing not to scale).
T1OSI
Clock
OSC2
TOST
Q1
PC + 6
TT1P
TOSC
TSCS
1 2 34 567 8© 2006 Microchip Technology Inc. DS39564C-page 23
PIC18FXX2
If the main oscillator is configured for HS-PLL mode, an
oscillator start-up time (TOST) plus an additional PLL
time-out (TPLL) will occur. The PLL time-out is typically
2 ms and allows the PLL to lock to the main oscillator
frequency. A timing diagram indicating the transition
from the Timer1 oscillator to the main oscillator for
HS-PLL mode is shown in Figure 2-10.
FIGURE 2-10: TIMING FOR TRANSITION BETWEEN TIMER1 AND OSC1 (HS WITH PLL)
If the main oscillator is configured in the RC, RCIO, EC
or ECIO modes, there is no oscillator start-up time-out.
Operation will resume after eight cycles of the main
oscillator have been counted. A timing diagram, indicating
the transition from the Timer1 oscillator to the
main oscillator for RC, RCIO, EC and ECIO modes, is
shown in Figure 2-11.
FIGURE 2-11: TIMING FOR TRANSITION BETWEEN TIMER1 AND OSC1 (RC, EC)
Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2
OSC1
Internal System
SCS
(OSCCON<0>)
Program Counter PC PC + 2
Note 1: TOST = 1024 TOSC (drawing not to scale).
T1OSI
Clock
TOST
Q3
PC + 4
TPLL
TOSC
TT1P
TSCS
Q4
OSC2
PLL Clock
Input 1 234 5678
Q3 Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2 Q3
OSC1
Internal System
SCS
(OSCCON<0>)
Program Counter PC PC + 2
Note 1: RC Oscillator mode assumed.
PC + 4
T1OSI
Clock
OSC2
Q4 TT1P
TOSC
TSCS
1 2 3 4 5 6 7 8PIC18FXX2
DS39564C-page 24 © 2006 Microchip Technology Inc.
2.7 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 during SLEEP. The user can wake from
SLEEP through external RESET, Watchdog Timer
Reset, or through an interrupt.
TABLE 2-3: OSC1 AND OSC2 PIN STATES IN SLEEP MODE
2.8 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 Section 3.0.
The first timer is the Power-up Timer (PWRT), which
optionally provides a fixed delay of 72 ms (nominal) on
power-up only (POR and BOR). The second timer is
the Oscillator Start-up Timer (OST), intended to keep
the chip in RESET until the crystal oscillator is stable.
With the PLL enabled (HS/PLL Oscillator mode), the
time-out sequence following a Power-on Reset is different
from other Oscillator modes. The time-out
sequence is as follows: First, the PWRT time-out is
invoked after a POR time delay has expired. Then, the
Oscillator Start-up Timer (OST) is invoked. However,
this is still not a sufficient amount of time to allow the
PLL to lock at high frequencies. The PWRT timer is
used to provide an additional fixed 2 ms (nominal)
time-out to allow the PLL ample time to lock to the
incoming clock frequency.
OSC Mode OSC1 Pin OSC2 Pin
RC Floating, external resistor
should pull high
At logic low
RCIO Floating, external resistor
should pull high
Configured as PORTA, bit 6
ECIO Floating Configured as PORTA, bit 6
EC Floating At logic low
LP, XT, and HS Feedback inverter disabled, at
quiescent voltage level
Feedback inverter disabled, at
quiescent voltage level
Note: See Table 3-1, in the “Reset” section, for time-outs due to SLEEP and MCLR Reset.© 2006 Microchip Technology Inc. DS39564C-page 25
PIC18FXX2
3.0 RESET
The PIC18FXXX differentiates between various kinds
of RESET:
a) Power-on Reset (POR)
b) MCLR Reset during normal operation
c) MCLR Reset during SLEEP
d) Watchdog Timer (WDT) Reset (during normal
operation)
e) Programmable Brown-out Reset (BOR)
f) RESET Instruction
g) Stack Full Reset
h) 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, Brownout
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-2. These bits
are used in software to determine the nature of the
RESET. See Table 3-3 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.
The Enhanced MCU devices have a MCLR noise filter
in the MCLR Reset path. The filter will detect and
ignore small pulses.
The MCLR pin is not driven low by any internal
RESETS, including the WDT.
FIGURE 3-1: SIMPLIFIED BLOCK DIAGRAM OF ON-CHIP RESET CIRCUIT
S
R Q
External Reset
MCLR
VDD
OSC1
WDT
Module
VDD Rise
Detect
OST/PWRT
On-chip
RC OSC(1)
WDT
Time-out
Power-on Reset
OST
10-bit Ripple Counter
PWRT
Chip_Reset
10-bit Ripple Counter
Reset
Enable OST(2)
Enable PWRT
SLEEP
Note 1: This is a separate oscillator from the RC oscillator of the CLKI pin.
2: See Table 3-1 for time-out situations.
Brown-out
Reset BOREN
RESET
Instruction
Stack
Pointer Stack Full/Underflow ResetPIC18FXX2
DS39564C-page 26 © 2006 Microchip Technology Inc.
3.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 circuitry,
just tie the MCLR pin directly (or through a resistor)
to VDD. This will eliminate external RC components
usually needed to create a Power-on Reset delay. A
minimum rise rate for VDD is specified
(parameter D004). For a slow rise time, see Figure 3-2.
When the device starts normal operation (i.e., exits the
RESET condition), device operating parameters (voltage,
frequency, temperature, etc.) must be met to
ensure operation. If these conditions are not met, the
device must be held in RESET until the operating
conditions are met.
FIGURE 3-2: EXTERNAL POWER-ON
RESET CIRCUIT (FOR
SLOW VDD POWER-UP)
3.2 Power-up Timer (PWRT)
The Power-up Timer provides a fixed nominal time-out
(parameter 33) only on power-up from the POR. The
Power-up Timer operates on an internal RC oscillator.
The chip is kept in RESET as long as the PWRT is
active. The PWRT’s time delay allows VDD to rise to an
acceptable level. A configuration bit is provided to
enable/disable the PWRT.
The power-up time delay will vary from chip-to-chip due
to VDD, temperature and process variation. See DC
parameter D033 for details.
3.3 Oscillator Start-up Timer (OST)
The Oscillator Start-up Timer (OST) provides a 1024
oscillator cycle (from OSC1 input) delay after the
PWRT delay is over (parameter 32). This ensures that
the crystal oscillator or resonator has started and
stabilized.
The OST time-out is invoked only for XT, LP and HS
modes and only on Power-on Reset or wake-up from
SLEEP.
3.4 PLL Lock Time-out
With the PLL 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) is typically 2 ms and follows the oscillator
start-up time-out (OST).
3.5 Brown-out Reset (BOR)
A configuration bit, BOREN, can disable (if clear/
programmed), or enable (if set) the Brown-out Reset
circuitry. If VDD falls below parameter D005 for greater
than parameter 35, the brown-out situation will reset
the chip. A RESET may not occur if VDD falls below
parameter D005 for less than parameter 35. The chip
will remain in Brown-out Reset until VDD rises above
BVDD. If the Power-up Timer is enabled, it will be
invoked after VDD rises above BVDD; it then will keep
the chip in RESET for an additional time delay
(parameter 33). If VDD drops below BVDD while the
Power-up Timer is running, the chip will go back into a
Brown-out Reset and the Power-up Timer will be initialized.
Once VDD rises above BVDD, the Power-up Timer
will execute the additional time delay.
3.6 Time-out Sequence
On power-up, the time-out sequence is as follows:
First, PWRT time-out is invoked after the POR time
delay has expired. Then, OST is activated. The total
time-out will vary based on oscillator configuration and
the status of the PWRT. For example, in RC mode with
the PWRT disabled, there will be no time-out at all.
Figure 3-3, Figure 3-4, Figure 3-5, Figure 3-6 and
Figure 3-7 depict time-out sequences on power-up.
Since the time-outs occur from the POR pulse, if MCLR
is kept low long enough, the time-outs will expire.
Bringing MCLR high will begin execution immediately
(Figure 3-5). This is useful for testing purposes or to
synchronize more than one PIC18FXXX device operating
in parallel.
Table 3-2 shows the RESET conditions for some
Special Function Registers, while Table 3-3 shows the
RESET conditions for all the registers.
Note 1: External Power-on Reset circuit is required
only if the VDD power-up slope is too slow.
The diode D helps discharge the capacitor
quickly when VDD powers down.
2: R < 40 kΩ is recommended to make sure that
the voltage drop across R does not violate
the device’s electrical specification.
3: 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).
C
R1
D R
VDD
MCLR
PIC18FXXX© 2006 Microchip Technology Inc. DS39564C-page 27
PIC18FXX2
TABLE 3-1: TIME-OUT IN VARIOUS SITUATIONS
REGISTER 3-1: RCON REGISTER BITS AND POSITIONS
TABLE 3-2: STATUS BITS, THEIR SIGNIFICANCE AND THE INITIALIZATION CONDITION FOR
RCON REGISTER
Oscillator
Configuration
Power-up(2)
Brown-out
Wake-up from
SLEEP or
PWRTE = 0 PWRTE = 1 Oscillator Switch
HS with PLL enabled(1) 72 ms + 1024 TOSC
+ 2ms
1024 TOSC
+ 2 ms
72 ms(2) + 1024 TOSC
+ 2 ms 1024 TOSC + 2 ms
HS, XT, LP 72 ms + 1024 TOSC 1024 TOSC 72 ms(2) + 1024 TOSC 1024 TOSC
EC 72 ms — 72 ms(2) —
External RC 72 ms — 72 ms(2) —
Note 1: 2 ms is the nominal time required for the 4x PLL to lock.
2: 72 ms is the nominal power-up timer delay, if implemented.
R/W-0 U-0 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN — — RI TO PD POR BOR
bit 7 bit 0
Note 1: Refer to Section 4.14 (page 53) for bit definitions.
Condition Program
Counter
RCON
Register RI TO PD POR BOR STKFUL STKUNF
Power-on Reset 0000h 0--1 1100 1 1 1 0 0 u u
MCLR Reset during normal
operation
0000h 0--u uuuu u u u u u u u
Software Reset during normal
operation
0000h 0--0 uuuu 0 u u u u u u
Stack Full Reset during normal
operation
0000h 0--u uu11 u u u u u u 1
Stack Underflow Reset during
normal operation
0000h 0--u uu11 u u u u u 1 u
MCLR Reset during SLEEP 0000h 0--u 10uu u 1 0 u u u u
WDT Reset 0000h 0--u 01uu 1 0 1 u u u u
WDT Wake-up PC + 2 u--u 00uu u 0 0 u u u u
Brown-out Reset 0000h 0--1 11u0 1 1 1 1 0 u u
Interrupt wake-up from SLEEP PC + 2(1) u--u 00uu u 1 0 u u u u
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0'
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 (0x000008h or 0x000018h).PIC18FXX2
DS39564C-page 28 © 2006 Microchip Technology Inc.
TABLE 3-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
TOSU 242 442 252 452 ---0 0000 ---0 0000 ---0 uuuu(3)
TOSH 242 442 252 452 0000 0000 0000 0000 uuuu uuuu(3)
TOSL 242 442 252 452 0000 0000 0000 0000 uuuu uuuu(3)
STKPTR 242 442 252 452 00-0 0000 uu-0 0000 uu-u uuuu(3)
PCLATU 242 442 252 452 ---0 0000 ---0 0000 ---u uuuu
PCLATH 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
PCL 242 442 252 452 0000 0000 0000 0000 PC + 2(2)
TBLPTRU 242 442 252 452 --00 0000 --00 0000 --uu uuuu
TBLPTRH 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
TBLPTRL 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
TABLAT 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
PRODH 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
PRODL 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
INTCON 242 442 252 452 0000 000x 0000 000u uuuu uuuu(1)
INTCON2 242 442 252 452 1111 -1-1 1111 -1-1 uuuu -u-u(1)
INTCON3 242 442 252 452 11-0 0-00 11-0 0-00 uu-u u-uu(1)
INDF0 242 442 252 452 N/A N/A N/A
POSTINC0 242 442 252 452 N/A N/A N/A
POSTDEC0 242 442 252 452 N/A N/A N/A
PREINC0 242 442 252 452 N/A N/A N/A
PLUSW0 242 442 252 452 N/A N/A N/A
FSR0H 242 442 252 452 ---- xxxx ---- uuuu ---- uuuu
FSR0L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
WREG 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
INDF1 242 442 252 452 N/A N/A N/A
POSTINC1 242 442 252 452 N/A N/A N/A
POSTDEC1 242 442 252 452 N/A N/A N/A
PREINC1 242 442 252 452 N/A N/A N/A
PLUSW1 242 442 252 452 N/A N/A N/A
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt
vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 3-2 for RESET value for specific condition.
5: Bit 6 of PORTA, LATA, and TRISA are enabled in ECIO and RCIO Oscillator modes only. In all other
Oscillator modes, they are disabled and read ’0’.
6: Bit 6 of PORTA, LATA and TRISA are not available on all devices. When unimplemented, they are read ’0’. © 2006 Microchip Technology Inc. DS39564C-page 29
PIC18FXX2
FSR1H 242 442 252 452 ---- xxxx ---- uuuu ---- uuuu
FSR1L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
BSR 242 442 252 452 ---- 0000 ---- 0000 ---- uuuu
INDF2 242 442 252 452 N/A N/A N/A
POSTINC2 242 442 252 452 N/A N/A N/A
POSTDEC2 242 442 252 452 N/A N/A N/A
PREINC2 242 442 252 452 N/A N/A N/A
PLUSW2 242 442 252 452 N/A N/A N/A
FSR2H 242 442 252 452 ---- xxxx ---- uuuu ---- uuuu
FSR2L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
STATUS 242 442 252 452 ---x xxxx ---u uuuu ---u uuuu
TMR0H 242 442 252 452 0000 0000 uuuu uuuu uuuu uuuu
TMR0L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
T0CON 242 442 252 452 1111 1111 1111 1111 uuuu uuuu
OSCCON 242 442 252 452 ---- ---0 ---- ---0 ---- ---u
LVDCON 242 442 252 452 --00 0101 --00 0101 --uu uuuu
WDTCON 242 442 252 452 ---- ---0 ---- ---0 ---- ---u
RCON(4) 242 442 252 452 0--q 11qq 0--q qquu u--u qquu
TMR1H 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
TMR1L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
T1CON 242 442 252 452 0-00 0000 u-uu uuuu u-uu uuuu
TMR2 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
PR2 242 442 252 452 1111 1111 1111 1111 1111 1111
T2CON 242 442 252 452 -000 0000 -000 0000 -uuu uuuu
SSPBUF 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
SSPADD 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
SSPSTAT 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
SSPCON1 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
SSPCON2 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
TABLE 3-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt
vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 3-2 for RESET value for specific condition.
5: Bit 6 of PORTA, LATA, and TRISA are enabled in ECIO and RCIO Oscillator modes only. In all other
Oscillator modes, they are disabled and read ’0’.
6: Bit 6 of PORTA, LATA and TRISA are not available on all devices. When unimplemented, they are read ’0’. PIC18FXX2
DS39564C-page 30 © 2006 Microchip Technology Inc.
ADRESH 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
ADRESL 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
ADCON0 242 442 252 452 0000 00-0 0000 00-0 uuuu uu-u
ADCON1 242 442 252 452 00-- 0000 00-- 0000 uu-- uuuu
CCPR1H 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
CCPR1L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
CCP1CON 242 442 252 452 --00 0000 --00 0000 --uu uuuu
CCPR2H 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
CCPR2L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
CCP2CON 242 442 252 452 --00 0000 --00 0000 --uu uuuu
TMR3H 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
TMR3L 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
T3CON 242 442 252 452 0000 0000 uuuu uuuu uuuu uuuu
SPBRG 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
RCREG 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
TXREG 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
TXSTA 242 442 252 452 0000 -010 0000 -010 uuuu -uuu
RCSTA 242 442 252 452 0000 000x 0000 000x uuuu uuuu
EEADR 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
EEDATA 242 442 252 452 0000 0000 0000 0000 uuuu uuuu
EECON1 242 442 252 452 xx-0 x000 uu-0 u000 uu-0 u000
EECON2 242 442 252 452 ---- ---- ---- ---- ---- ----
TABLE 3-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt
vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 3-2 for RESET value for specific condition.
5: Bit 6 of PORTA, LATA, and TRISA are enabled in ECIO and RCIO Oscillator modes only. In all other
Oscillator modes, they are disabled and read ’0’.
6: Bit 6 of PORTA, LATA and TRISA are not available on all devices. When unimplemented, they are read ’0’. © 2006 Microchip Technology Inc. DS39564C-page 31
PIC18FXX2
IPR2 242 442 252 452 ---1 1111 ---1 1111 ---u uuuu
PIR2 242 442 252 452 ---0 0000 ---0 0000 ---u uuuu(1)
PIE2 242 442 252 452 ---0 0000 ---0 0000 ---u uuuu
IPR1
242 442 252 452 1111 1111 1111 1111 uuuu uuuu
242 442 252 452 -111 1111 -111 1111 -uuu uuuu
PIR1
242 442 252 452 0000 0000 0000 0000 uuuu uuuu(1)
242 442 252 452 -000 0000 -000 0000 -uuu uuuu(1)
PIE1
242 442 252 452 0000 0000 0000 0000 uuuu uuuu
242 442 252 452 -000 0000 -000 0000 -uuu uuuu
TRISE 242 442 252 452 0000 -111 0000 -111 uuuu -uuu
TRISD 242 442 252 452 1111 1111 1111 1111 uuuu uuuu
TRISC 242 442 252 452 1111 1111 1111 1111 uuuu uuuu
TRISB 242 442 252 452 1111 1111 1111 1111 uuuu uuuu
TRISA(5,6) 242 442 252 452 -111 1111(5) -111 1111(5) -uuu uuuu(5)
LATE 242 442 252 452 ---- -xxx ---- -uuu ---- -uuu
LATD 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
LATC 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
LATB 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
LATA(5,6) 242 442 252 452 -xxx xxxx(5) -uuu uuuu(5) -uuu uuuu(5)
PORTE 242 442 252 452 ---- -000 ---- -000 ---- -uuu
PORTD 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
PORTC 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
PORTB 242 442 252 452 xxxx xxxx uuuu uuuu uuuu uuuu
PORTA(5,6) 242 442 252 452 -x0x 0000(5) -u0u 0000(5) -uuu uuuu(5)
TABLE 3-3: INITIALIZATION CONDITIONS FOR ALL REGISTERS (CONTINUED)
Register Applicable Devices Power-on Reset,
Brown-out Reset
MCLR Resets
WDT Reset
RESET Instruction
Stack Resets
Wake-up via WDT
or Interrupt
Legend: u = unchanged, x = unknown, - = unimplemented bit, read as '0', q = value depends on condition.
Shaded cells indicate conditions do not apply for the designated device.
Note 1: One or more bits in the INTCONx or PIRx registers will be affected (to cause wake-up).
2: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the PC is loaded with the interrupt
vector (0008h or 0018h).
3: When the wake-up is due to an interrupt and the GIEL or GIEH bit is set, the TOSU, TOSH and TOSL are
updated with the current value of the PC. The STKPTR is modified to point to the next location in the
hardware stack.
4: See Table 3-2 for RESET value for specific condition.
5: Bit 6 of PORTA, LATA, and TRISA are enabled in ECIO and RCIO Oscillator modes only. In all other
Oscillator modes, they are disabled and read ’0’.
6: Bit 6 of PORTA, LATA and TRISA are not available on all devices. When unimplemented, they are read ’0’. PIC18FXX2
DS39564C-page 32 © 2006 Microchip Technology Inc.
FIGURE 3-3: TIME-OUT SEQUENCE ON POWER-UP (MCLR TIED TO VDD)
FIGURE 3-4: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 1
FIGURE 3-5: TIME-OUT SEQUENCE ON POWER-UP (MCLR NOT TIED TO VDD): CASE 2
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
TPWRT
TOST© 2006 Microchip Technology Inc. DS39564C-page 33
PIC18FXX2
FIGURE 3-6: SLOW RISE TIME (MCLR TIED TO VDD)
FIGURE 3-7: TIME-OUT SEQUENCE ON POR W/ PLL ENABLED (MCLR TIED TO VDD)
VDD
MCLR
INTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
0V 1V
5V
TPWRT
TOST
TPWRT
TOST
VDD
MCLR
IINTERNAL POR
PWRT TIME-OUT
OST TIME-OUT
INTERNAL RESET
PLL TIME-OUT
TPLL
Note: TOST = 1024 clock cycles.
TPLL ≈ 2 ms max. First three stages of the PWRT timer.PIC18FXX2
DS39564C-page 34 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 35
PIC18FXX2
4.0 MEMORY ORGANIZATION
There are three memory blocks in Enhanced MCU
devices. These memory blocks are:
• Program Memory
• Data RAM
• Data EEPROM
Data and program memory use separate busses,
which allows for concurrent access of these blocks.
Additional detailed information for FLASH program
memory and Data EEPROM is provided in Section 5.0
and Section 6.0, respectively.
4.1 Program Memory Organization
A 21-bit program counter is capable of addressing the
2-Mbyte program memory space. Accessing a location
between the physically implemented memory and the
2-Mbyte address will cause a read of all ’0’s (a NOP
instruction).
The PIC18F252 and PIC18F452 each have 32 Kbytes
of FLASH memory, while the PIC18F242 and
PIC18F442 have 16 Kbytes of FLASH. This means that
PIC18FX52 devices can store up to 16K of single word
instructions, and PIC18FX42 devices can store up to
8K of single word instructions.
The RESET vector address is at 0000h and the
interrupt vector addresses are at 0008h and 0018h.
Figure 4-1 shows the Program Memory Map for
PIC18F242/442 devices and Figure 4-2 shows the
Program Memory Map for PIC18F252/452 devices.PIC18FXX2
DS39564C-page 36 © 2006 Microchip Technology Inc.
FIGURE 4-1: PROGRAM MEMORY MAP
AND STACK FOR
PIC18F442/242
FIGURE 4-2: PROGRAM MEMORY MAP
AND STACK FOR
PIC18F452/252
PC<20:0>
Stack Level 1 •
Stack Level 31
RESET Vector
Low Priority Interrupt Vector
•
•
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
On-Chip
Program Memory
High Priority Interrupt Vector 0008h
User Memory Space
1FFFFFh
4000h
3FFFh
Read '0'
200000h
PC<20:0>
Stack Level 1 •
Stack Level 31
RESET Vector
Low Priority Interrupt Vector
•
•
CALL,RCALL,RETURN
RETFIE,RETLW
21
0000h
0018h
8000h
7FFFh
On-Chip
Program Memory
High Priority Interrupt Vector 0008h
User Memory Space
Read '0'
1FFFFFh
200000h© 2006 Microchip Technology Inc. DS39564C-page 37
PIC18FXX2
4.2 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 or CALL instructions.
The stack operates as a 31-word by 21-bit RAM and a
5-bit stack pointer, with the stack pointer initialized to
00000b after all RESETS. There is no RAM associated
with stack pointer 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 are
transferred to the PC and then the stack pointer is
decremented.
The stack space is not part of either program or data
space. The stack pointer is readable and writable, and
the address on the top of the stack is readable and writable
through SFR registers. Data can also be pushed
to, or popped from, the stack using the top-of-stack
SFRs. Status bits indicate if the stack pointer is at, or
beyond the 31 levels provided.
4.2.1 TOP-OF-STACK ACCESS
The top of the stack 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.
4.2.2 RETURN STACK POINTER
(STKPTR)
The STKPTR register contains the stack pointer value,
the STKFUL (stack full) status bit, and the STKUNF
(stack underflow) status bits. Register 4-1 shows the
STKPTR register. The value of the stack pointer can be
0 through 31. The stack pointer increments when values
are pushed onto the stack and decrements when
values are popped off the stack. At RESET, the stack
pointer value will be 0. The user may read and write the
stack pointer value. This feature can be used by a Real
Time Operating System for return stack maintenance.
After the PC is pushed onto the stack 31 times (without
popping any values off the stack), the STKFUL bit is
set. The STKFUL bit can only be cleared in software or
by a POR.
The action that takes place when the stack becomes
full depends on the state of the STVREN (Stack Overflow
Reset Enable) configuration bit. Refer to
Section 20.0 for a description of the device configuration
bits. If STVREN is set (default), the 31st push will
push the (PC + 2) value onto the stack, set the STKFUL
bit, and reset the device. The STKFUL bit will remain
set and the stack pointer will be set to ‘0’.
If STVREN is cleared, the STKFUL bit will be set on the
31st push and the stack pointer will increment to 31.
Any additional pushes will not overwrite the 31st push,
and STKPTR will remain at 31.
When the stack has been popped enough times to
unload the stack, the next pop will return a value of zero
to the PC and sets the STKUNF bit, while the stack
pointer remains at 0. The STKUNF bit will remain set
until cleared in software or a POR occurs.
Note: Returning a value of 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.PIC18FXX2
DS39564C-page 38 © 2006 Microchip Technology Inc.
REGISTER 4-1: STKPTR REGISTER
FIGURE 4-3: RETURN ADDRESS STACK AND ASSOCIATED REGISTERS
4.2.3 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 a return address on the
stack.
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.
4.2.4 STACK FULL/UNDERFLOW RESETS
These resets are enabled by programming the
STVREN configuration bit. When the STVREN bit is
disabled, a full or underflow condition will set the appropriate
STKFUL or STKUNF bit, but not cause a device
RESET. When the STVREN bit is enabled, a full or
underflow will set the appropriate STKFUL or STKUNF
bit and then cause a device RESET. The STKFUL or
STKUNF bits are only cleared by the user software or
a POR Reset.
R/C-0 R/C-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
STKOVF STKUNF — SP4 SP3 SP2 SP1 SP0
bit 7 bit 0
bit 7(1) STKOVF: Stack Full Flag bit
1 = Stack became full or overflowed
0 = Stack has not become full or overflowed
bit 6(1) STKUNF: Stack Underflow Flag bit
1 = Stack underflow occurred
0 = Stack underflow did not occur
bit 5 Unimplemented: Read as '0'
bit 4-0 SP4:SP0: Stack Pointer Location bits
Note 1: Bit 7 and bit 6 can only be cleared in user software or by a POR.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
00011
0x001A34
11111
11110
11101
00010
00001
00000
00010
Return Address Stack
Top of Stack 0x000D58
TOSU TOSH TOSL
0x00 0x1A 0x34
STKPTR<4:0>© 2006 Microchip Technology Inc. DS39564C-page 39
PIC18FXX2
4.3 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 not readable or 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.
A low or high priority interrupt source will push 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. If a high priority
interrupt occurs while servicing a low priority interrupt,
the stack register values stored by the low priority interrupt
will be overwritten.
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.
Example 4-1 shows a source code example that uses
the fast register stack.
EXAMPLE 4-1: FAST REGISTER STACK
CODE EXAMPLE
4.4 PCL, PCLATH and PCLATU
The program counter (PC) specifies the address of the
instruction to fetch for execution. The PC is 21-bits
wide. The low byte is called the PCL register. This register
is readable and writable. The high byte is called
the PCH register. This register contains the PC<15:8>
bits and is not directly readable or writable. Updates to
the PCH register may be performed through the
PCLATH register. The upper byte is called PCU. This
register contains the PC<20:16> bits and is not directly
readable or writable. Updates to the PCU register may
be performed through the PCLATU register.
The PC addresses bytes in the program memory. To
prevent the PC from becoming misaligned with word
instructions, the LSB of PCL is fixed to a value of ’0’.
The PC increments by 2 to address sequential
instructions in the program memory.
The CALL, RCALL, GOTO and program branch
instructions write to the program counter directly. For
these instructions, the contents of PCLATH and
PCLATU are not transferred to the program counter.
The contents of PCLATH and PCLATU will be transferred
to the program counter by an operation that
writes PCL. Similarly, the upper two bytes of the program
counter will be transferred to PCLATH and
PCLATU by an operation that reads PCL. This is useful
for computed offsets to the PC (see Section 4.8.1).
4.5 Clocking Scheme/Instruction
Cycle
The clock input (from OSC1) is internally divided by
four to generate four non-overlapping quadrature
clocks, namely Q1, Q2, Q3 and Q4. Internally, the program
counter (PC) is incremented every Q1, the
instruction is fetched from the program memory and
latched into the instruction register in Q4. The instruction
is decoded and executed during the following Q1
through Q4. The clocks and instruction execution flow
are shown in Figure 4-4.
FIGURE 4-4: CLOCK/INSTRUCTION CYCLE
CALL SUB1, FAST ;STATUS, WREG, BSR
;SAVED IN FAST REGISTER
;STACK
•
•
SUB1 •
•
•
RETURN FAST ;RESTORE VALUES SAVED
;IN FAST REGISTER STACK
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
Q1
Q2
Q3
Q4
PC
OSC2/CLKO
(RC mode)
PC PC+2 PC+4
Fetch INST (PC)
Execute INST (PC-2)
Fetch INST (PC+2)
Execute INST (PC)
Fetch INST (PC+4)
Execute INST (PC+2)
Internal
Phase
ClockPIC18FXX2
DS39564C-page 40 © 2006 Microchip Technology Inc.
4.6 Instruction Flow/Pipelining
An “Instruction Cycle” consists of four Q cycles (Q1,
Q2, Q3 and Q4). The instruction fetch and execute are
pipelined such that fetch takes one instruction cycle,
while decode and execute takes another instruction
cycle. However, due to the pipelining, each instruction
effectively executes in one cycle. If an instruction
causes the program counter to change (e.g., GOTO)
then two cycles are required to complete the instruction
(Example 4-2).
A fetch cycle begins with the program counter (PC)
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-2: INSTRUCTION PIPELINE FLOW
4.7 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 4-5 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’ (see Section 4.4).
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 4-5 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. Section 20.0 provides further
details of the instruction set.
FIGURE 4-5: INSTRUCTIONS IN PROGRAM MEMORY
All instructions are single cycle, except for any program branches. These take two cycles since the fetch instruction
is “flushed” from the pipeline while the new instruction is being fetched and then executed.
TCY0 TCY1 TCY2 TCY3 TCY4 TCY5
1. MOVLW 55h Fetch 1 Execute 1
2. MOVWF PORTB Fetch 2 Execute 2
3. BRA SUB_1 Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP) Fetch 4 Flush (NOP)
5. Instruction @ address SUB_1 Fetch SUB_1 Execute SUB_1
Word Address
LSB = 1 LSB = 0 ↓
Program Memory
Byte Locations →
000000h
000002h
000004h
000006h
Instruction 1: MOVLW 055h 0Fh 55h 000008h
Instruction 2: GOTO 000006h EFh 03h 00000Ah
F0h 00h 00000Ch
Instruction 3: MOVFF 123h, 456h C1h 23h 00000Eh
F4h 56h 000010h
000012h
000014h© 2006 Microchip Technology Inc. DS39564C-page 41
PIC18FXX2
4.7.1 TWO-WORD INSTRUCTIONS
The PIC18FXX2 devices have four two-word instructions:
MOVFF, CALL, GOTO and LFSR. The second
word of these instructions has the 4 MSBs set to 1’s
and is a special kind of NOP instruction. The lower 12
bits of the second word contain data to be used by the
instruction. If the first word of the instruction is executed,
the data in the second word is accessed. If the
second word of the instruction is executed by itself (first
word was skipped), it will execute as a NOP. This action
is necessary when the two-word instruction is preceded
by a conditional instruction that changes the PC. A program
example that demonstrates this concept is shown
in Example 4-3. Refer to Section 20.0 for further details
of the instruction set.
EXAMPLE 4-3: TWO-WORD INSTRUCTIONS
4.8 Lookup Tables
Lookup tables are implemented two ways. These are:
• Computed GOTO
• Table Reads
4.8.1 COMPUTED GOTO
A computed GOTO is accomplished by adding an offset
to the program counter (ADDWF PCL).
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.
The offset value (value in WREG) specifies the number
of bytes that the program counter should advance.
In this method, only one data byte may be stored in
each instruction location and room on the return
address stack is required.
4.8.2 TABLE READS/TABLE WRITES
A better method of storing data in program memory
allows 2 bytes of data to be stored in each instruction
location.
Lookup table data may be stored 2 bytes per program
word by using table reads and writes. The table pointer
(TBLPTR) specifies the byte address and the table
latch (TABLAT) contains the data that is read from, or
written to program memory. Data is transferred to/from
program memory, one byte at a time.
A description of the Table Read/Table Write operation
is shown in Section 3.0.
CASE 1:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; No, execute 2-word instruction
1111 0100 0101 0110 ; 2nd operand holds address of REG2
0010 0100 0000 0000 ADDWF REG3 ; continue code
CASE 2:
Object Code Source Code
0110 0110 0000 0000 TSTFSZ REG1 ; is RAM location 0?
1100 0001 0010 0011 MOVFF REG1, REG2 ; Yes
1111 0100 0101 0110 ; 2nd operand becomes NOP
0010 0100 0000 0000 ADDWF REG3 ; continue code
Note: The ADDWF PCL instruction does not
update PCLATH and PCLATU. A read
operation on PCL must be performed to
update PCLATH and PCLATU.PIC18FXX2
DS39564C-page 42 © 2006 Microchip Technology Inc.
4.9 Data Memory Organization
The data memory is implemented as static RAM. Each
register in the data memory has a 12-bit address,
allowing up to 4096 bytes of data memory. Figure 4-6
and Figure 4-7 show the data memory organization for
the PIC18FXX2 devices.
The data memory map is divided into as many as 16
banks that contain 256 bytes each. The lower 4 bits of
the Bank Select Register (BSR<3:0>) select which
bank will be accessed. The upper 4 bits for the BSR are
not implemented.
The data memory contains Special Function Registers
(SFR) and General Purpose Registers (GPR). The
SFRs are used for control and status of the controller
and peripheral functions, while GPRs are used for data
storage and scratch pad operations in the user’s application.
The SFRs start at the last location of Bank 15
(0xFFF) and extend downwards. Any remaining space
beyond the SFRs in the Bank may be implemented as
GPRs. GPRs start at the first location of Bank 0 and
grow upwards. Any read of an unimplemented location
will read as ’0’s.
The entire data memory may be accessed directly or
indirectly. Direct addressing may require the use of the
BSR register. Indirect addressing requires the use of a
File Select Register (FSRn) and a corresponding Indirect
File Operand (INDFn). Each FSR holds a 12-bit
address value that can be used to access any location
in the Data Memory map without banking.
The instruction set and architecture allow operations
across all banks. This may be accomplished by indirect
addressing or by the use of the MOVFF instruction. The
MOVFF instruction is a two-word/two-cycle instruction
that moves a value from one register to another.
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. A segment of Bank 0 and a segment of
Bank 15 comprise the Access RAM. Section 4.10
provides a detailed description of the Access RAM.
4.9.1 GENERAL PURPOSE REGISTER
FILE
The register file can be accessed either directly or indirectly.
Indirect addressing operates using a File Select
Register and corresponding Indirect File Operand. The
operation of indirect addressing is shown in
Section 4.12.
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.
Data RAM is available for use as GPR registers by all
instructions. The top half of Bank 15 (0xF80 to 0xFFF)
contains SFRs. All other banks of data memory contain
GPR registers, starting with Bank 0.
4.9.2 SPECIAL FUNCTION REGISTERS
The Special Function Registers (SFRs) are registers
used by the CPU and Peripheral Modules for controlling
the desired operation of the device. These registers
are implemented as static RAM. A list of these
registers is given in Table 4-1 and Table 4-2.
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.
The unused SFR locations will be unimplemented and
read as '0's. See Table 4-1 for addresses for the SFRs.© 2006 Microchip Technology Inc. DS39564C-page 43
PIC18FXX2
FIGURE 4-6: DATA MEMORY MAP FOR PIC18F242/442
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000
= 0001
= 1111
080h
07Fh
F80h
FFFh
00h
7Fh
80h
FFh
Access Bank
When a = 0,
the BSR is ignored and the
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).
When a = 1,
the BSR is used to specify the
RAM location that the
instruction uses.
F7Fh
F00h
EFFh
1FFh
100h
0FFh
000h Access RAM
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
SFR
Unused
Access RAM high
Access RAM low
Bank 3
to
200h
Unused
= 1110 Read ’00h’
= 0011
(SFRs)
GPR
2FFh
300h
FFh
00h
Bank 2 = 0010PIC18FXX2
DS39564C-page 44 © 2006 Microchip Technology Inc.
FIGURE 4-7: DATA MEMORY MAP FOR PIC18F252/452
Bank 0
Bank 1
Bank 14
Bank 15
BSR<3:0> Data Memory Map
= 0000
= 0001
= 1110
= 1111
080h
07Fh
F80h
FFFh
00h
7Fh
80h
FFh
Access Bank
When a = 0,
the BSR is ignored and the
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).
When a = 1,
the BSR is used to specify the
RAM location that the
instruction uses.
Bank 4
Bank 3
Bank 2
F7Fh
F00h
EFFh
3FFh
300h
2FFh
200h
1FFh
100h
0FFh
000h
= 0110
= 0101
= 0011
= 0010
Access RAM
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
FFh
00h
GPR
GPR
GPR
GPR
SFR
Unused
Access RAM high
Access RAM low
Bank 5
GPR
GPR
Bank 6
to
4FFh
400h
5FFh
500h
600h
Unused
Read ’00h’
= 0100
(SFR’s)© 2006 Microchip Technology Inc. DS39564C-page 45
PIC18FXX2
TABLE 4-1: SPECIAL FUNCTION REGISTER MAP
Address Name Address Name Address Name Address Name
FFFh TOSU FDFh INDF2(3) FBFh CCPR1H F9Fh IPR1
FFEh TOSH FDEh POSTINC2(3) FBEh CCPR1L F9Eh PIR1
FFDh TOSL FDDh POSTDEC2(3) FBDh CCP1CON F9Dh PIE1
FFCh STKPTR FDCh PREINC2(3) FBCh CCPR2H F9Ch —
FFBh PCLATU FDBh PLUSW2(3) 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(2)
FF5h TABLAT FD5h T0CON FB5h — F95h TRISD(2)
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(3) FCFh TMR1H FAFh SPBRG F8Fh —
FEEh POSTINC0(3) FCEh TMR1L FAEh RCREG F8Eh —
FEDh POSTDEC0(3) FCDh T1CON FADh TXREG F8Dh LATE(2)
FECh PREINC0(3) FCCh TMR2 FACh TXSTA F8Ch LATD(2)
FEBh PLUSW0(3) FCBh PR2 FABh RCSTA F8Bh LATC
FEAh FSR0H FCAh T2CON FAAh — F8Ah LATB
FE9h FSR0L FC9h SSPBUF FA9h EEADR F89h LATA
FE8h WREG FC8h SSPADD FA8h EEDATA F88h —
FE7h INDF1(3) FC7h SSPSTAT FA7h EECON2 F87h —
FE6h POSTINC1(3) FC6h SSPCON1 FA6h EECON1 F86h —
FE5h POSTDEC1(3) FC5h SSPCON2 FA5h — F85h —
FE4h PREINC1(3) FC4h ADRESH FA4h — F84h PORTE(2)
FE3h PLUSW1(3) FC3h ADRESL FA3h — F83h PORTD(2)
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 register is not available on PIC18F2X2 devices.
3: This is not a physical register.PIC18FXX2
DS39564C-page 46 © 2006 Microchip Technology Inc.
TABLE 4-2: REGISTER FILE SUMMARY
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
TOSU — — — Top-of-Stack upper Byte (TOS<20:16>) ---0 0000 37
TOSH Top-of-Stack High Byte (TOS<15:8>) 0000 0000 37
TOSL Top-of-Stack Low Byte (TOS<7:0>) 0000 0000 37
STKPTR STKFUL STKUNF — Return Stack Pointer 00-0 0000 38
PCLATU — — — Holding Register for PC<20:16> ---0 0000 39
PCLATH Holding Register for PC<15:8> 0000 0000 39
PCL PC Low Byte (PC<7:0>) 0000 0000 39
TBLPTRU — — bit21(2) Program Memory Table Pointer Upper Byte (TBLPTR<20:16>) --00 0000 58
TBLPTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 0000 0000 58
TBLPTRL Program Memory Table Pointer Low Byte (TBLPTR<7:0>) 0000 0000 58
TABLAT Program Memory Table Latch 0000 0000 58
PRODH Product Register High Byte xxxx xxxx 71
PRODL Product Register Low Byte xxxx xxxx 71
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 75
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 76
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 77
INDF0 Uses contents of FSR0 to address data memory - value of FSR0 not changed (not a physical register) n/a 50
POSTINC0 Uses contents of FSR0 to address data memory - value of FSR0 post-incremented (not a physical register) n/a 50
POSTDEC0 Uses contents of FSR0 to address data memory - value of FSR0 post-decremented (not a physical register) n/a 50
PREINC0 Uses contents of FSR0 to address data memory - value of FSR0 pre-incremented (not a physical register) n/a 50
PLUSW0 Uses contents of FSR0 to address data memory - value of FSR0 (not a physical register).
Offset by value in WREG.
n/a 50
FSR0H — — — — Indirect Data Memory Address Pointer 0 High Byte ---- 0000 50
FSR0L Indirect Data Memory Address Pointer 0 Low Byte xxxx xxxx 50
WREG Working Register xxxx xxxx n/a
INDF1 Uses contents of FSR1 to address data memory - value of FSR1 not changed (not a physical register) n/a 50
POSTINC1 Uses contents of FSR1 to address data memory - value of FSR1 post-incremented (not a physical register) n/a 50
POSTDEC1 Uses contents of FSR1 to address data memory - value of FSR1 post-decremented (not a physical register) n/a 50
PREINC1 Uses contents of FSR1 to address data memory - value of FSR1 pre-incremented (not a physical register) n/a 50
PLUSW1 Uses contents of FSR1 to address data memory - value of FSR1 (not a physical register).
Offset by value in WREG.
n/a 50
FSR1H — — — — Indirect Data Memory Address Pointer 1 High Byte ---- 0000 50
FSR1L Indirect Data Memory Address Pointer 1 Low Byte xxxx xxxx 50
BSR — — — — Bank Select Register ---- 0000 49
INDF2 Uses contents of FSR2 to address data memory - value of FSR2 not changed (not a physical register) n/a 50
POSTINC2 Uses contents of FSR2 to address data memory - value of FSR2 post-incremented (not a physical register) n/a 50
POSTDEC2 Uses contents of FSR2 to address data memory - value of FSR2 post-decremented (not a physical register) n/a 50
PREINC2 Uses contents of FSR2 to address data memory - value of FSR2 pre-incremented (not a physical register) n/a 50
PLUSW2 Uses contents of FSR2 to address data memory - value of FSR2 (not a physical register).
Offset by value in WREG.
n/a 50
FSR2H — — — — Indirect Data Memory Address Pointer 2 High Byte ---- 0000 50
FSR2L Indirect Data Memory Address Pointer 2 Low Byte xxxx xxxx 50
STATUS — — — N OV Z DC C ---x xxxx 52
TMR0H Timer0 Register High Byte 0000 0000 105
TMR0L Timer0 Register Low Byte xxxx xxxx 105
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 103
Legend: x = unknown, u = unchanged, - = unimplemented, q = value depends on condition
Note 1: RA6 and associated bits are configured as port pins in RCIO and ECIO Oscillator mode only and read '0' in all other Oscillator modes.
2: Bit 21 of the TBLPTRU allows access to the device configuration bits.
3: These registers and bits are reserved on the PIC18F2X2 devices; always maintain these clear.© 2006 Microchip Technology Inc. DS39564C-page 47
PIC18FXX2
OSCCON — — — — — — — SCS ---- ---0 21
LVDCON — — IRVST LVDEN LVDL3 LVDL2 LVDL1 LVDL0 --00 0101 191
WDTCON — — — — — — — SWDTE ---- ---0 203
RCON IPEN — — RI TO PD POR BOR 0--1 11qq 53, 28, 84
TMR1H Timer1 Register High Byte xxxx xxxx 107
TMR1L Timer1 Register Low Byte xxxx xxxx 107
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0-00 0000 107
TMR2 Timer2 Register 0000 0000 111
PR2 Timer2 Period Register 1111 1111 112
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 111
SSPBUF SSP Receive Buffer/Transmit Register xxxx xxxx 125
SSPADD SSP Address Register in I2C Slave mode. SSP Baud Rate Reload Register in I2C Master mode. 0000 0000 134
SSPSTAT SMP CKE D/A P S R/W UA BF 0000 0000 126
SSPCON1 WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 127
SSPCON2 GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN 0000 0000 137
ADRESH A/D Result Register High Byte xxxx xxxx 187,188
ADRESL A/D Result Register Low Byte xxxx xxxx 187,188
ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE — ADON 0000 00-0 181
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 00-- 0000 182
CCPR1H Capture/Compare/PWM Register1 High Byte xxxx xxxx 121, 123
CCPR1L Capture/Compare/PWM Register1 Low Byte xxxx xxxx 121, 123
CCP1CON — — DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 117
CCPR2H Capture/Compare/PWM Register2 High Byte xxxx xxxx 121, 123
CCPR2L Capture/Compare/PWM Register2 Low Byte xxxx xxxx 121, 123
CCP2CON — — DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0 --00 0000 117
TMR3H Timer3 Register High Byte xxxx xxxx 113
TMR3L Timer3 Register Low Byte xxxx xxxx 113
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0000 0000 113
SPBRG USART1 Baud Rate Generator 0000 0000 168
RCREG USART1 Receive Register 0000 0000 175, 178,
180
TXREG USART1 Transmit Register 0000 0000 173, 176,
179
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 166
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 000x 167
EEADR Data EEPROM Address Register 0000 0000 65, 69
EEDATA Data EEPROM Data Register 0000 0000 69
EECON2 Data EEPROM Control Register 2 (not a physical register) ---- ---- 65, 69
EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 66
TABLE 4-2: REGISTER FILE SUMMARY (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
Legend: x = unknown, u = unchanged, - = unimplemented, q = value depends on condition
Note 1: RA6 and associated bits are configured as port pins in RCIO and ECIO Oscillator mode only and read '0' in all other Oscillator modes.
2: Bit 21 of the TBLPTRU allows access to the device configuration bits.
3: These registers and bits are reserved on the PIC18F2X2 devices; always maintain these clear.PIC18FXX2
DS39564C-page 48 © 2006 Microchip Technology Inc.
IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 83
PIR2 — — — EEIF BCLIF LVDIF TMR3IF CCP2IF ---0 0000 79
PIE2 — — — EEIE BCLIE LVDIE TMR3IE CCP2IE ---0 0000 81
IPR1 PSPIP(3) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP 1111 1111 82
PIR1 PSPIF(3) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF 0000 0000 78
PIE1 PSPIE(3) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE 0000 0000 80
TRISE(3) IBF OBF IBOV PSPMODE — Data Direction bits for PORTE 0000 -111 98
TRISD(3) Data Direction Control Register for PORTD 1111 1111 96
TRISC Data Direction Control Register for PORTC 1111 1111 93
TRISB Data Direction Control Register for PORTB 1111 1111 90
TRISA — TRISA6(1) Data Direction Control Register for PORTA -111 1111 87
LATE(3) — — — — — Read PORTE Data Latch,
Write PORTE Data Latch
---- -xxx 99
LATD(3) Read PORTD Data Latch, Write PORTD Data Latch xxxx xxxx 95
LATC Read PORTC Data Latch, Write PORTC Data Latch xxxx xxxx 93
LATB Read PORTB Data Latch, Write PORTB Data Latch xxxx xxxx 90
LATA — LATA6(1) Read PORTA Data Latch, Write PORTA Data Latch(1) -xxx xxxx 87
PORTE(3) Read PORTE pins, Write PORTE Data Latch ---- -000 99
PORTD(3) Read PORTD pins, Write PORTD Data Latch xxxx xxxx 95
PORTC Read PORTC pins, Write PORTC Data Latch xxxx xxxx 93
PORTB Read PORTB pins, Write PORTB Data Latch xxxx xxxx 90
PORTA — RA6(1) Read PORTA pins, Write PORTA Data Latch(1) -x0x 0000 87
TABLE 4-2: REGISTER FILE SUMMARY (CONTINUED)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Value on
POR, BOR
Details
on page:
Legend: x = unknown, u = unchanged, - = unimplemented, q = value depends on condition
Note 1: RA6 and associated bits are configured as port pins in RCIO and ECIO Oscillator mode only and read '0' in all other Oscillator modes.
2: Bit 21 of the TBLPTRU allows access to the device configuration bits.
3: These registers and bits are reserved on the PIC18F2X2 devices; always maintain these clear.© 2006 Microchip Technology Inc. DS39564C-page 49
PIC18FXX2
4.10 Access Bank
The Access Bank is an architectural enhancement
which 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 128 bytes
in Bank 15 (SFRs) and the lower 128 bytes in Bank 0.
These two sections will be referred to as Access RAM
High and Access RAM Low, respectively. Figure 4-6
and Figure 4-7 indicate the Access RAM areas.
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 and modifying control bits.
4.11 Bank Select Register (BSR)
The need for a large general purpose memory space
dictates a RAM banking scheme. The data memory is
partitioned into sixteen banks. When using direct
addressing, the BSR should be configured for the
desired bank.
BSR<3:0> holds the upper 4 bits of the 12-bit RAM
address. The BSR<7:4> bits will always read ’0’s, and
writes will have no effect.
A MOVLB 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. The
STATUS register bits will be set/cleared as appropriate
for the instruction performed.
Each Bank extends up to FFh (256 bytes). All data
memory is implemented as static RAM.
A MOVFF instruction ignores the BSR, since the 12-bit
addresses are embedded into the instruction word.
Section 4.12 provides a description of indirect addressing,
which allows linear addressing of the entire RAM
space.
FIGURE 4-8: DIRECT ADDRESSING
Note 1: For register file map detail, see Table 4-1.
2: The access bit of the instruction can be used to force an override of the selected bank (BSR<3:0>) to the
registers of the Access Bank.
3: The MOVFF instruction embeds the entire 12-bit address in the instruction.
Data
Memory(1)
Direct Addressing
Bank Select(2) Location Select(3)
BSR<3:0> 7 From Opcode 0 (3)
00h 01h 0Eh 0Fh
Bank 0 Bank 1 Bank 14 Bank 15
1FFh
100h
0FFh
000h
EFFh
E00h
FFFh
F00hPIC18FXX2
DS39564C-page 50 © 2006 Microchip Technology Inc.
4.12 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 FSR 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 4-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 one of the
INDF registers. 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. The FSR
register contains a 12-bit address, which is shown in
Figure 4-10.
The INDFn register is not a physical register. Addressing
INDFn actually addresses the register whose
address is contained in the FSRn register (FSRn is a
pointer). This is indirect addressing.
Example 4-4 shows a simple use of indirect addressing
to clear the RAM in Bank1 (locations 100h-1FFh) in a
minimum number of instructions.
EXAMPLE 4-4: HOW TO CLEAR RAM
(BANK1) USING INDIRECT
ADDRESSING
There are three indirect addressing registers. To
address the entire data memory space (4096 bytes),
these registers are 12-bit 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 reads
the data from the address pointed to by
FSR1H:FSR1L. INDFn can be used in code anywhere
an operand can be used.
If INDF0, INDF1 or INDF2 are read indirectly via an
FSR, all '0's are read (zero bit is set). Similarly, if
INDF0, INDF1 or INDF2 are written to indirectly, the
operation will be equivalent to a NOP instruction and the
STATUS bits are not affected.
4.12.1 INDIRECT ADDRESSING
OPERATION
Each FSR register has an INDF register associated
with it, plus four additional register addresses. Performing
an operation on one of these five registers determines
how the FSR will be modified during indirect
addressing.
When data access is done to 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
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.
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.
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.
LFSR FSR0 ,0x100 ;
NEXT CLRF POSTINC0 ; Clear INDF
; register and
; inc pointer
BTFSS FSR0H, 1 ; All done with
; Bank1?
GOTO NEXT ; NO, clear next
CONTINUE ; YES, continue © 2006 Microchip Technology Inc. DS39564C-page 51
PIC18FXX2
FIGURE 4-9: INDIRECT ADDRESSING OPERATION
FIGURE 4-10: INDIRECT ADDRESSING
Opcode Address
File Address = access of an indirect addressing register
FSR
Instruction
Executed
Instruction
Fetched
RAM
Opcode File
12 12
12
BSR<3:0>
4 8
0h
FFFh
Note 1: For register file map detail, see Table 4-1.
Data
Memory(1)
Indirect Addressing
11 FSR Register 0
0FFFh
0000h
Location SelectPIC18FXX2
DS39564C-page 52 © 2006 Microchip Technology Inc.
4.13 STATUS Register
The STATUS register, shown in Register 4-2, 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 from the
STATUS register. For other instructions not affecting
any status bits, see Table 20-2.
REGISTER 4-2: STATUS REGISTER
Note: The C and DC bits operate as a borrow and
digit borrow bit respectively, in subtraction.
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: For borrow, the polarity is reversed. A subtraction is executed by adding the two’s
complement of the second operand. For rotate (RRF, RLF) instructions, this bit is
loaded with either the bit 4 or bit 3 of the source register.
bit 0 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 two’s
complement of the second operand. For rotate (RRF, RLF) instructions, this bit is
loaded with either the high or low order bit of the source register.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 53
PIC18FXX2
4.14 RCON Register
The Reset Control (RCON) register contains flag bits
that allow differentiation between the sources of a
device RESET. These flags include the TO, PD, POR,
BOR and RI bits. This register is readable and writable.
REGISTER 4-3: RCON REGISTER
Note 1: If the BOREN configuration bit is set
(Brown-out Reset enabled), the BOR bit is
’1’ on a Power-on Reset. After a Brownout
Reset has occurred, the BOR bit will
be cleared, and must be set by firmware to
indicate the occurrence of the next
Brown-out Reset.
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.
R/W-0 U-0 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN — — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (16CXXX Compatibility mode)
bit 6-5 Unimplemented: Read as '0'
bit 4 RI: RESET Instruction Flag bit
1 = The RESET instruction was not executed
0 = The RESET instruction was executed causing a device RESET
(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
(must be set in software after a Power-on Reset occurs)
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)
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 54 © 2006 Microchip Technology Inc.
NOTES: © 2006 Microchip Technology Inc. DS39564C-page 55
PIC18FXX2
5.0 FLASH PROGRAM MEMORY
The FLASH Program Memory is readable, writable,
and erasable during normal operation over the entire
VDD range.
A read from program memory is executed on one byte
at a time. A write to program memory is executed on
blocks of 8 bytes at a time. Program memory is erased
in blocks of 64 bytes at a time. A bulk erase operation
may not be issued from user code.
Writing or erasing program memory will cease instruction
fetches until the operation is complete. The program
memory cannot be accessed during the write or
erase, therefore, code cannot execute. An internal programming
timer terminates program memory writes
and erases.
A value written to program memory does not need to be
a valid instruction. Executing a program memory
location that forms an invalid instruction results in a
NOP.
5.1 Table Reads and Table Writes
In order to read and write program memory, there are
two operations that allow the processor to move bytes
between the program memory space and the data
RAM:
• Table Read (TBLRD)
• Table Write (TBLWT)
The program memory space is 16-bits wide, while the
data RAM space is 8-bits wide. Table Reads and Table
Writes move data between these two memory spaces
through an 8-bit register (TABLAT).
Table Read operations retrieve data from program
memory and places it into the data RAM space.
Figure 5-1 shows the operation of a Table Read with
program memory and data RAM.
Table Write operations store data from the data memory
space into holding registers in program memory.
The procedure to write the contents of the holding registers
into program memory is detailed in Section 5.5,
'”Writing to FLASH Program Memory”. Figure 5-2
shows the operation of a Table Write with program
memory and data RAM.
Table operations work with byte entities. A table block
containing data, rather than program instructions, is not
required to be word aligned. Therefore, a table block
can start and end at any byte address. If a Table Write
is being used to write executable code into program
memory, program instructions will need to be word
aligned.
FIGURE 5-1: TABLE READ OPERATION
Table Pointer(1)
Table Latch (8-bit)
Program Memory
TBLPTRH TBLPTRL
TABLAT
TBLPTRU
Instruction: TBLRD*
Note 1: Table Pointer points to a byte in program memory.
Program Memory
(TBLPTR)PIC18FXX2
DS39564C-page 56 © 2006 Microchip Technology Inc.
FIGURE 5-2: TABLE WRITE OPERATION
5.2 Control Registers
Several control registers are used in conjunction with
the TBLRD and TBLWT instructions. These include the:
• EECON1 register
• EECON2 register
• TABLAT register
• TBLPTR registers
5.2.1 EECON1 AND EECON2 REGISTERS
EECON1 is the control register for memory accesses.
EECON2 is not a physical register. Reading EECON2
will read all '0's. The EECON2 register is used
exclusively in the memory write and erase sequences.
Control bit EEPGD determines if the access will be a
program or data EEPROM memory access. When
clear, any subsequent operations will operate on the
data EEPROM memory. When set, any subsequent
operations will operate on the program memory.
Control bit CFGS determines if the access will be to the
configuration registers or to program memory/data
EEPROM memory. When set, subsequent operations
will operate on configuration registers, regardless of
EEPGD (see “Special Features of the CPU”,
Section 19.0). When clear, memory selection access is
determined by EEPGD.
The FREE bit, when set, will allow a program memory
erase operation. When the FREE bit is set, the erase
operation is initiated on the next WR command. When
FREE is clear, only writes are enabled.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is clear. The WRERR bit is
set when a write operation is interrupted by a MCLR
Reset or a WDT Time-out Reset during normal operation.
In these situations, the user can check the
WRERR bit and rewrite the location. It is necessary to
reload the data and address registers (EEDATA and
EEADR), due to RESET values of zero.
Control bit WR initiates write operations. This bit cannot
be cleared, only set, in software. It is cleared in hardware
at the completion of the write operation. The
inability to clear the WR bit in software prevents the
accidental or premature termination of a write
operation.
Table Pointer(1) Table Latch (8-bit)
TBLPTRH TBLPTRL TABLAT
Program Memory
(TBLPTR)
TBLPTRU
Instruction: TBLWT*
Note 1: Table Pointer actually points to one of eight holding registers, the address of which is determined by
TBLPTRL<2:0>. The process for physically writing data to the Program Memory Array is discussed in
Section 5.5.
Holding Registers
Program Memory
Note: Interrupt flag bit EEIF, in the PIR2 register,
is set when the write is complete. It must
be cleared in software.© 2006 Microchip Technology Inc. DS39564C-page 57
PIC18FXX2
REGISTER 5-1: EECON1 REGISTER (ADDRESS FA6h)
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR WREN WR RD
bit 7 bit 0
bit 7 EEPGD: FLASH Program or Data EEPROM Memory Select bit
1 = Access FLASH Program memory
0 = Access Data EEPROM memory
bit 6 CFGS: FLASH Program/Data EE or Configuration Select bit
1 = Access Configuration registers
0 = Access FLASH Program or Data EEPROM memory
bit 5 Unimplemented: Read as '0'
bit 4 FREE: FLASH Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command
(cleared by completion of erase operation)
0 = Perform write only
bit 3 WRERR: FLASH Program/Data EE Error Flag bit
1 = A write operation is prematurely terminated
(any RESET during self-timed programming in normal operation)
0 = The write operation completed
Note: When a WRERR occurs, the EEPGD and CFGS bits are not cleared. This allows
tracing of the error condition.
bit 2 WREN: FLASH Program/Data EE Write Enable bit
1 = Allows write cycles
0 = Inhibits write to the EEPROM
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle.
(The operation is self timed and the bit is cleared by hardware once write is complete. The
WR bit can only be set (not cleared) in software.)
0 = Write cycle to the EEPROM is complete
bit 0 RD: Read Control bit
1 = Initiates an EEPROM read
(Read takes one cycle. RD is cleared in hardware. The RD bit can only be set (not cleared)
in software. RD bit cannot be set when EEPGD = 1.)
0 = Does not initiate an EEPROM read
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 58 © 2006 Microchip Technology Inc.
5.2.2 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 RAM.
5.2.3 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, Table
Pointer High Byte and Table Pointer Low Byte
(TBLPTRU:TBLPTRH:TBLPTRL). These three registers
join to form a 22-bit wide pointer. The low order 21
bits allow the device to address up to 2 Mbytes 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 5-1. These
operations on the TBLPTR only affect the low order
21 bits.
5.2.4 TABLE POINTER BOUNDARIES
TBLPTR is used in reads, writes, and erases of the
FLASH program memory.
When a TBLRD is executed, all 22 bits of the Table
Pointer determine which byte is read from program
memory into TABLAT.
When a TBLWT is executed, the three LSbs of the Table
Pointer (TBLPTR<2:0>) determine which of the eight
program memory holding registers is written to. When
the timed write to program memory (long write) begins,
the 19 MSbs of the Table Pointer, TBLPTR
(TBLPTR<21:3>), will determine which program memory
block of 8 bytes is written to. For more detail, see
Section 5.5 (“Writing to FLASH Program Memory”).
When an erase of program memory is executed, the 16
MSbs of the Table Pointer (TBLPTR<21:6>) point to the
64-byte block that will be erased. The Least Significant
bits (TBLPTR<5:0>) are ignored.
Figure 5-3 describes the relevant boundaries of
TBLPTR based on FLASH program memory
operations.
TABLE 5-1: TABLE POINTER OPERATIONS WITH TBLRD AND TBLWT INSTRUCTIONS
FIGURE 5-3: TABLE POINTER BOUNDARIES BASED ON OPERATION
Example 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
21 16 15 8 7 0
ERASE - TBLPTR<21:6>
WRITE - TBLPTR<21:3>
READ - TBLPTR<21:0>
TBLPTRU TBLPTRH TBLPTRL© 2006 Microchip Technology Inc. DS39564C-page 59
PIC18FXX2
5.3 Reading the FLASH Program
Memory
The TBLRD instruction is used to retrieve data from program
memory and place into data RAM. Table Reads
from program memory are performed one byte at a
time.
TBLPTR points to a byte address in program space.
Executing TBLRD places the byte pointed to into
TABLAT. In addition, TBLPTR can be modified
automatically for the next Table Read operation.
The internal program memory is typically organized by
words. The Least Significant bit of the address selects
between the high and low bytes of the word. Figure 5-4
shows the interface between the internal program
memory and the TABLAT.
FIGURE 5-4: READS FROM FLASH PROGRAM MEMORY
EXAMPLE 5-1: READING A FLASH PROGRAM MEMORY WORD
(Even Byte Address)
Program Memory
(Odd Byte Address)
TBLRD TABLAT
TBLPTR = xxxxx1
FETCH Instruction Register
(IR) Read Register
TBLPTR = xxxxx0
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the word
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
READ_WORD
TBLRD*+ ; read into TABLAT and increment
MOVF TABLAT, W ; get data
MOVWF WORD_EVEN
TBLRD*+ ; read into TABLAT and increment
MOVF TABLAT, W ; get data
MOVWF WORD_ODDPIC18FXX2
DS39564C-page 60 © 2006 Microchip Technology Inc.
5.4 Erasing FLASH Program memory
The minimum erase block is 32 words or 64 bytes. Only
through the use of an external programmer, or through
ICSP control can larger blocks of program memory be
bulk erased. Word erase in the FLASH array is not
supported.
When initiating an erase sequence from the microcontroller
itself, a block of 64 bytes of program memory
is erased. The Most Significant 16 bits of the
TBLPTR<21:6> point to the block being erased.
TBLPTR<5:0> are ignored.
The EECON1 register commands the erase operation.
The EEPGD bit must be set to point to the FLASH program
memory. The WREN bit must be set to enable
write operations. The FREE bit is set to select an erase
operation.
For protection, the write initiate sequence for EECON2
must be used.
A long write is necessary for erasing the internal
FLASH. Instruction execution is halted while in a long
write cycle. The long write will be terminated by the
internal programming timer.
5.4.1 FLASH PROGRAM MEMORY
ERASE SEQUENCE
The sequence of events for erasing a block of internal
program memory location is:
1. Load table pointer with address of row being
erased.
2. Set EEPGD bit to point to program memory,
clear CFGS bit to access program memory, set
WREN bit to enable writes, and set FREE bit to
enable the erase.
3. Disable interrupts.
4. Write 55h to EECON2.
5. Write AAh to EECON2.
6. Set the WR bit. This will begin the row erase
cycle.
7. The CPU will stall for duration of the erase
(about 2 ms using internal timer).
8. Re-enable interrupts.
EXAMPLE 5-2: ERASING A FLASH PROGRAM MEMORY ROW
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
ERASE_ROW
BSF EECON1,EEPGD ; point to FLASH program memory
BCF EECON1,CFGS ; access FLASH program memory
BSF EECON1,WREN ; enable write to memory
BSF EECON1,FREE ; enable Row Erase operation
BCF INTCON,GIE ; disable interrupts
MOVLW 55h
Required MOVWF EECON2 ; write 55h
Sequence MOVLW AAh
MOVWF EECON2 ; write AAh
BSF EECON1,WR ; start erase (CPU stall)
BSF INTCON,GIE ; re-enable interrupts© 2006 Microchip Technology Inc. DS39564C-page 61
PIC18FXX2
5.5 Writing to FLASH Program
Memory
The minimum programming block is 4 words or 8 bytes.
Word or byte programming is not supported.
Table Writes are used internally to load the holding registers
needed to program the FLASH memory. There
are 8 holding registers used by the Table Writes for
programming.
Since the Table Latch (TABLAT) is only a single byte,
the TBLWT instruction has to be executed 8 times for
each programming operation. All of the Table Write
operations will essentially be short writes, because only
the holding registers are written. At the end of updating
8 registers, the EECON1 register must be written to, to
start the programming operation with a long write.
The long write is necessary for programming the internal
FLASH. Instruction execution is halted while in a
long write cycle. The long write will be terminated by
the internal programming timer.
The EEPROM on-chip timer controls the write time.
The write/erase voltages are generated by an on-chip
charge pump rated to operate over the voltage range of
the device for byte or word operations.
FIGURE 5-5: TABLE WRITES TO FLASH PROGRAM MEMORY
5.5.1 FLASH PROGRAM MEMORY WRITE
SEQUENCE
The sequence of events for programming an internal
program memory location should be:
1. Read 64 bytes into RAM.
2. Update data values in RAM as necessary.
3. Load Table Pointer with address being erased.
4. Do the row erase procedure.
5. Load Table Pointer with address of first byte
being written.
6. Write the first 8 bytes into the holding registers
with auto-increment (TBLWT*+ or TBLWT+*).
7. Set EEPGD bit to point to program memory,
clear the CFGS bit to access program memory,
and set WREN to enable byte writes.
8. Disable interrupts.
9. Write 55h to EECON2.
10. Write AAh to EECON2.
11. Set the WR bit. This will begin the write cycle.
12. The CPU will stall for duration of the write (about
2 ms using internal timer).
13. Re-enable interrupts.
14. Repeat steps 6-14 seven times, to write
64 bytes.
15. Verify the memory (Table Read).
This procedure will require about 18 ms to update one
row of 64 bytes of memory. An example of the required
code is given in Example 5-3.
Holding Register
TABLAT
Holding Register
TBLPTR = xxxxx7
Holding Register
TBLPTR = xxxxx1
Holding Register
TBLPTR = xxxxx0
8 8 8 8
Write Register
TBLPTR = xxxxx2
Program Memory
Note: Before setting the WR bit, the table pointer
address needs to be within the intended
address range of the 8 bytes in the holding
registers.PIC18FXX2
DS39564C-page 62 © 2006 Microchip Technology Inc.
EXAMPLE 5-3: WRITING TO FLASH PROGRAM MEMORY
MOVLW D'64 ; number of bytes in erase block
MOVWF COUNTER
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
MOVLW CODE_ADDR_UPPER ; Load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
READ_BLOCK
TBLRD*+ ; read into TABLAT, and inc
MOVF TABLAT, W ; get data
MOVWF POSTINC0 ; store data
DECFSZ COUNTER ; done?
BRA READ_BLOCK ; repeat
MODIFY_WORD
MOVLW DATA_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW DATA_ADDR_LOW
MOVWF FSR0L
MOVLW NEW_DATA_LOW ; update buffer word
MOVWF POSTINC0
MOVLW NEW_DATA_HIGH
MOVWF INDF0
ERASE_BLOCK
MOVLW CODE_ADDR_UPPER ; load TBLPTR with the base
MOVWF TBLPTRU ; address of the memory block
MOVLW CODE_ADDR_HIGH
MOVWF TBLPTRH
MOVLW CODE_ADDR_LOW
MOVWF TBLPTRL
BSF EECON1,EEPGD ; point to FLASH program memory
BCF EECON1,CFGS ; access FLASH program memory
BSF EECON1,WREN ; enable write to memory
BSF EECON1,FREE ; enable Row Erase operation
BCF INTCON,GIE ; disable interrupts
MOVLW 55h
MOVWF EECON2 ; write 55h
MOVLW AAh
MOVWF EECON2 ; write AAh
BSF EECON1,WR ; start erase (CPU stall)
BSF INTCON,GIE ; re-enable interrupts
TBLRD*- ; dummy read decrement
WRITE_BUFFER_BACK
MOVLW 8 ; number of write buffer groups of 8 bytes
MOVWF COUNTER_HI
MOVLW BUFFER_ADDR_HIGH ; point to buffer
MOVWF FSR0H
MOVLW BUFFER_ADDR_LOW
MOVWF FSR0L
PROGRAM_LOOP
MOVLW 8 ; number of bytes in holding register
MOVWF COUNTER
WRITE_WORD_TO_HREGS
MOVF POSTINC0, W ; get low byte of buffer data
MOVWF TABLAT ; present data to table latch
TBLWT+* ; write data, perform a short write
; to internal TBLWT holding register.
DECFSZ COUNTER ; loop until buffers are full
BRA WRITE_WORD_TO_HREGS© 2006 Microchip Technology Inc. DS39564C-page 63
PIC18FXX2
EXAMPLE 5-3: WRITING TO FLASH PROGRAM MEMORY (CONTINUED)
5.5.2 WRITE VERIFY
Depending on the application, good programming
practice may dictate that the value written to the memory
should be verified against the original value. This
should be used in applications where excessive writes
can stress bits near the specification limit.
5.5.3 UNEXPECTED TERMINATION OF
WRITE OPERATION
If a write is terminated by an unplanned event, such as
loss of power or an unexpected RESET, the memory
location just programmed should be verified and reprogrammed
if needed.The WRERR bit is set when a write
operation is interrupted by a MCLR Reset, or a WDT
Time-out Reset during normal operation. In these situations,
users can check the WRERR bit and rewrite the
location.
5.5.4 PROTECTION AGAINST SPURIOUS
WRITES
To protect against spurious writes to FLASH program
memory, the write initiate sequence must also be followed.
See “Special Features of the CPU”
(Section 19.0) for more detail.
5.6 FLASH Program Operation During
Code Protection
See “Special Features of the CPU” (Section 19.0) for
details on code protection of FLASH program memory.
TABLE 5-2: REGISTERS ASSOCIATED WITH PROGRAM FLASH MEMORY
PROGRAM_MEMORY
BSF EECON1,EEPGD ; point to FLASH program memory
BCF EECON1,CFGS ; access FLASH program memory
BSF EECON1,WREN ; enable write to memory
BCF INTCON,GIE ; disable interrupts
MOVLW 55h
Required MOVWF EECON2 ; write 55h
Sequence MOVLW AAh
MOVWF EECON2 ; write AAh
BSF EECON1,WR ; start program (CPU stall)
BSF INTCON,GIE ; re-enable interrupts
DECFSZ COUNTER_HI ; loop until done
BRA PROGRAM_LOOP
BCF EECON1,WREN ; disable write to memory
Address 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
FF8h TBLPTRU — — bit21 Program Memory Table Pointer Upper Byte
(TBLPTR<20:16>)
--00 0000 --00 0000
FF7h TBPLTRH Program Memory Table Pointer High Byte (TBLPTR<15:8>) 0000 0000 0000 0000
FF6h TBLPTRL Program Memory Table Pointer High Byte (TBLPTR<7:0>) 0000 0000 0000 0000
FF5h TABLAT Program Memory Table Latch 0000 0000 0000 0000
FF2h INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INTE RBIE TMR0IF INTF RBIF 0000 000x 0000 000u
FA7h EECON2 EEPROM Control Register2 (not a physical register) — —
FA6h EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 uu-0 u000
FA2h IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 ---1 1111
FA1h PIR2 — — — EEIF BCLIF LVDIF TMR3IF CCP2IF ---0 0000 ---0 0000
FA0h PIE2 — — — EEIE BCLIE LVDIE TMR3IE CCP2IE ---0 0000 ---0 0000
Legend: x = unknown, u = unchanged, r = reserved, - = unimplemented read as '0'.
Shaded cells are not used during FLASH/EEPROM access.PIC18FXX2
DS39564C-page 64 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 65
PIC18FXX2
6.0 DATA EEPROM MEMORY
The Data EEPROM is readable and writable during
normal operation over the entire VDD range. The data
memory is not directly mapped in the register file
space. Instead, it is indirectly addressed through the
Special Function Registers (SFR).
There are four SFRs used to read and write the
program and data EEPROM memory. These registers
are:
• EECON1
• EECON2
• EEDATA
• EEADR
The EEPROM data memory allows byte read and write.
When interfacing to the data memory block, EEDATA
holds the 8-bit data for read/write and EEADR holds the
address of the EEPROM location being accessed.
These devices have 256 bytes of data EEPROM with
an address range from 0h to FFh.
The EEPROM data memory is rated for high erase/
write cycles. A byte write automatically erases the location
and writes the new data (erase-before-write). The
write time is controlled by an on-chip timer. The write
time will vary with voltage and temperature, as well as
from chip to chip. Please refer to parameter D122
(Electrical Characteristics, Section 22.0) for exact
limits.
6.1 EEADR
The address register can address up to a maximum of
256 bytes of data EEPROM.
6.2 EECON1 and EECON2 Registers
EECON1 is the control register for EEPROM memory
accesses.
EECON2 is not a physical register. Reading EECON2
will read all '0's. The EECON2 register is used
exclusively in the EEPROM write sequence.
Control bits RD and WR initiate read and write operations,
respectively. These bits cannot be cleared, only
set, in software. They are cleared in hardware at the
completion of the read or write operation. The inability
to clear the WR bit in software prevents the accidental
or premature termination of a write operation.
The WREN bit, when set, will allow a write operation.
On power-up, the WREN bit is clear. The WRERR bit is
set when a write operation is interrupted by a MCLR
Reset, or a WDT Time-out Reset during normal operation.
In these situations, the user can check the
WRERR bit and rewrite the location. It is necessary to
reload the data and address registers (EEDATA and
EEADR), due to the RESET condition forcing the
contents of the registers to zero.
Note: Interrupt flag bit, EEIF in the PIR2 register,
is set when write is complete. It must be
cleared in software.PIC18FXX2
DS39564C-page 66 © 2006 Microchip Technology Inc.
REGISTER 6-1: EECON1 REGISTER (ADDRESS FA6h)
R/W-x R/W-x U-0 R/W-0 R/W-x R/W-0 R/S-0 R/S-0
EEPGD CFGS — FREE WRERR WREN WR RD
bit 7 bit 0
bit 7 EEPGD: FLASH Program or Data EEPROM Memory Select bit
1 = Access FLASH Program memory
0 = Access Data EEPROM memory
bit 6 CFGS: FLASH Program/Data EE or Configuration Select bit
1 = Access Configuration or Calibration registers
0 = Access FLASH Program or Data EEPROM memory
bit 5 Unimplemented: Read as '0'
bit 4 FREE: FLASH Row Erase Enable bit
1 = Erase the program memory row addressed by TBLPTR on the next WR command
(cleared by completion of erase operation)
0 = Perform write only
bit 3 WRERR: FLASH Program/Data EE Error Flag bit
1 = A write operation is prematurely terminated
(any MCLR or any WDT Reset during self-timed programming in normal operation)
0 = The write operation completed
Note: When a WRERR occurs, the EEPGD or FREE bits are not cleared. This allows tracing
of the error condition.
bit 2 WREN: FLASH Program/Data EE Write Enable bit
1 = Allows write cycles
0 = Inhibits write to the EEPROM
bit 1 WR: Write Control bit
1 = Initiates a data EEPROM erase/write cycle or a program memory erase cycle or write cycle.
(The operation is self-timed and the bit is cleared by hardware once write is complete. The
WR bit can only be set (not cleared) in software.)
0 = Write cycle to the EEPROM is complete
bit 0 RD: Read Control bit
1 = Initiates an EEPROM read
(Read takes one cycle. RD is cleared in hardware. The RD bit can only be set (not cleared)
in software. RD bit cannot be set when EEPGD = 1.)
0 = Does not initiate an EEPROM read
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 67
PIC18FXX2
6.3 Reading the Data EEPROM
Memory
To read a data memory location, the user must write the
address to the EEADR register, clear the EEPGD control
bit (EECON1<7>), clear the CFGS control bit
(EECON1<6>), and then set control bit RD
(EECON1<0>). The data is available for the very next
instruction cycle; therefore, the EEDATA register can
be read by the next instruction. EEDATA will hold this
value until another read operation, or until it is written to
by the user (during a write operation).
EXAMPLE 6-1: DATA EEPROM READ
6.4 Writing to the Data EEPROM
Memory
To write an EEPROM data location, the address must
first be written to the EEADR register and the data written
to the EEDATA register. Then the sequence in
Example 6-2 must be followed to initiate the write cycle.
The write will not initiate if the above sequence is not
exactly followed (write 55h to EECON2, write AAh to
EECON2, then set WR bit) for each byte. It is strongly
recommended that interrupts be disabled during this
code segment.
Additionally, the WREN bit in EECON1 must be set to
enable writes. This mechanism prevents accidental
writes to data EEPROM due to unexpected code execution
(i.e., runaway programs). The WREN bit should
be kept clear at all times, except when updating the
EEPROM. The WREN bit is not cleared by hardware.
After a write sequence has been initiated, EECON1,
EEADR and EDATA cannot be modified. The WR bit
will be inhibited from being set unless the WREN bit is
set. The WREN bit must be set on a previous instruction.
Both WR and WREN cannot be set with the same
instruction.
At the completion of the write cycle, the WR bit is
cleared in hardware and the EEPROM Write Complete
Interrupt Flag bit (EEIF) is set. The user may either
enable this interrupt, or poll this bit. EEIF must be
cleared by software.
EXAMPLE 6-2: DATA EEPROM WRITE
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to read
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access program FLASH or Data EEPROM memory
BSF EECON1, RD ; EEPROM Read
MOVF EEDATA, W ; W = EEDATA
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Data Memory Address to read
MOVLW DATA_EE_DATA ;
MOVWF EEDATA ; Data Memory Value to write
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access program FLASH or Data EEPROM memory
BSF EECON1, WREN ; Enable writes
BCF INTCON, GIE ; Disable interrupts
Required MOVLW 55h ;
Sequence MOVWF EECON2 ; Write 55h
MOVLW AAh ;
MOVWF EECON2 ; Write AAh
BSF EECON1, WR ; Set WR bit to begin write
BSF INTCON, GIE ; Enable interrupts
. ; user code execution
.
.
BCF EECON1, WREN ; Disable writes on write complete (EEIF set)PIC18FXX2
DS39564C-page 68 © 2006 Microchip Technology Inc.
6.5 Write Verify
Depending on the application, good programming
practice may dictate that the value written to the memory
should be verified against the original value. This
should be used in applications where excessive writes
can stress bits near the specification limit.
6.6 Protection Against Spurious Write
There are conditions when the device may not want to
write to the data EEPROM memory. To protect against
spurious EEPROM writes, various mechanisms have
been built-in. On power-up, the WREN bit is cleared.
Also, the Power-up Timer (72 ms duration) prevents
EEPROM write.
The write initiate sequence and the WREN bit together
help prevent an accidental write during brown-out,
power glitch, or software malfunction.
6.7 Operation During Code Protect
Data EEPROM memory has its own code protect
mechanism. External Read and Write operations are
disabled if either of these mechanisms are enabled.
The microcontroller itself can both read and write to the
internal Data EEPROM, regardless of the state of the
code protect configuration bit. Refer to “Special Features
of the CPU” (Section 19.0) for additional information.
6.8 Using the Data EEPROM
The data EEPROM is a high endurance, byte addressable
array that has been optimized for the storage of
frequently changing information (e.g., program variables
or other data that are updated often). Frequently
changing values will typically be updated more often
than specification D124. If this is not the case, an array
refresh must be performed. For this reason, variables
that change infrequently (such as constants, IDs, calibration,
etc.) should be stored in FLASH program
memory.
A simple data EEPROM refresh routine is shown in
Example 6-3.
EXAMPLE 6-3: DATA EEPROM REFRESH ROUTINE
Note: If data EEPROM is only used to store constants
and/or data that changes rarely, an
array refresh is likely not required. See
specification D124.
clrf EEADR ; Start at address 0
bcf EECON1,CFGS ; Set for memory
bcf EECON1,EEPGD ; Set for Data EEPROM
bcf INTCON,GIE ; Disable interrupts
bsf EECON1,WREN ; Enable writes
Loop ; Loop to refresh array
bsf EECON1,RD ; Read current address
movlw 55h ;
movwf EECON2 ; Write 55h
movlw AAh ;
movwf EECON2 ; Write AAh
bsf EECON1,WR ; Set WR bit to begin write
btfsc EECON1,WR ; Wait for write to complete
bra $-2
incfsz EEADR,F ; Increment address
bra Loop ; Not zero, do it again
bcf EECON1,WREN ; Disable writes
bsf INTCON,GIE ; Enable interrupts© 2006 Microchip Technology Inc. DS39564C-page 69
PIC18FXX2
TABLE 6-1: REGISTERS ASSOCIATED WITH DATA EEPROM MEMORY
Address 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
FF2h INTCON GIE/
GIEH
PEIE/
GIEL
T0IE INTE RBIE T0IF INTF RBIF 0000 000x 0000 000u
FA9h EEADR EEPROM Address Register 0000 0000 0000 0000
FA8h EEDATA EEPROM Data Register 0000 0000 0000 0000
FA7h EECON2 EEPROM Control Register2 (not a physical register) — —
FA6h EECON1 EEPGD CFGS — FREE WRERR WREN WR RD xx-0 x000 uu-0 u000
FA2h IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 ---1 1111
FA1h PIR2 — — — EEIF BCLIF LVDIF TMR3IF CCP2IF ---0 0000 ---0 0000
FA0h PIE2 — — — EEIE BCLIE LVDIE TMR3IE CCP2IE ---0 0000 ---0 0000
Legend: x = unknown, u = unchanged, r = reserved, - = unimplemented, read as '0'.
Shaded cells are not used during FLASH/EEPROM access.PIC18FXX2
DS39564C-page 70 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 71
PIC18FXX2
7.0 8 X 8 HARDWARE MULTIPLIER
7.1 Introduction
An 8 x 8 hardware multiplier is included in the ALU of
the PIC18FXX2 devices. By making the multiply a
hardware operation, it completes in a single instruction
cycle. This is an unsigned multiply that gives a 16-bit
result. The result is stored into the 16-bit product register
pair (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 multiply
algorithms
The performance increase allows the device to be used
in applications previously reserved for Digital Signal
Processors.
Table 7-1 shows a performance comparison between
enhanced devices using the single cycle hardware multiply,
and performing the same function without the
hardware multiply.
TABLE 7-1: PERFORMANCE COMPARISON
7.2 Operation
Example 7-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.
Example 7-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 7-1: 8 x 8 UNSIGNED
MULTIPLY ROUTINE
EXAMPLE 7-2: 8 x 8 SIGNED MULTIPLY
ROUTINE
Example 7-3 shows the sequence to do a 16 x 16
unsigned multiply. Equation 7-1 shows the algorithm
that is used. The 32-bit result is stored in four registers,
RES3:RES0.
EQUATION 7-1: 16 x 16 UNSIGNED
MULTIPLICATION
ALGORITHM
Routine Multiply Method
Program
Memory
(Words)
Cycles
(Max)
Time
@ 40 MHz @ 10 MHz @ 4 MHz
8 x 8 unsigned Without hardware multiply 13 69 6.9 μs 27.6 μs 69 μs
Hardware multiply 1 1 100 ns 400 ns 1 μs
8 x 8 signed Without hardware multiply 33 91 9.1 μs 36.4 μs 91 μs
Hardware multiply 6 6 600 ns 2.4 μs 6 μs
16 x 16 unsigned Without hardware multiply 21 242 24.2 μs 96.8 μs 242 μs
Hardware multiply 24 24 2.4 μs 9.6 μs 24 μs
16 x 16 signed Without hardware multiply 52 254 25.4 μs 102.6 μs 254 μs
Hardware multiply 36 36 3.6 μs 14.4 μs 36 μs
MOVF ARG1, W ;
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
MOVF ARG1, W
MULWF ARG2 ; ARG1 * ARG2 ->
; PRODH:PRODL
BTFSC ARG2, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG1
MOVF ARG2, W
BTFSC ARG1, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH
; - ARG2
RES3:RES0 = ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28
) +
(ARG1L • ARG2H • 28) +
(ARG1L • ARG2L)PIC18FXX2
DS39564C-page 72 © 2006 Microchip Technology Inc.
EXAMPLE 7-3: 16 x 16 UNSIGNED
MULTIPLY ROUTINE
Example 7-4 shows the sequence to do a 16 x 16
signed multiply. Equation 7-2 shows the algorithm
used. The 32-bit result is stored in four registers,
RES3: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 7-2: 16 x 16 SIGNED
MULTIPLICATION
ALGORITHM
EXAMPLE 7-4: 16 x 16 SIGNED
MULTIPLY ROUTINE
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
RES3:RES0
= ARG1H:ARG1L • ARG2H:ARG2L
= (ARG1H • ARG2H • 216) +
(ARG1H • ARG2L • 28) +
(ARG1L • ARG2H • 28) +
(ARG1L • ARG2L) +
(-1 • ARG2H<7> • ARG1H:ARG1L • 216) +
(-1 • ARG1H<7> • ARG2H:ARG2L • 216)
MOVF ARG1L, W
MULWF ARG2L ; ARG1L * ARG2L ->
; PRODH:PRODL
MOVFF PRODH, RES1 ;
MOVFF PRODL, RES0 ;
;
MOVF ARG1H, W
MULWF ARG2H ; ARG1H * ARG2H ->
; PRODH:PRODL
MOVFF PRODH, RES3 ;
MOVFF PRODL, RES2 ;
;
MOVF ARG1L, W
MULWF ARG2H ; ARG1L * ARG2H ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
MOVF ARG1H, W ;
MULWF ARG2L ; ARG1H * ARG2L ->
; PRODH:PRODL
MOVF PRODL, W ;
ADDWF RES1, F ; Add cross
MOVF PRODH, W ; products
ADDWFC RES2, F ;
CLRF WREG ;
ADDWFC RES3, F ;
;
BTFSS ARG2H, 7 ; ARG2H:ARG2L neg?
BRA SIGN_ARG1 ; no, check ARG1
MOVF ARG1L, W ;
SUBWF RES2 ;
MOVF ARG1H, W ;
SUBWFB RES3
;
SIGN_ARG1
BTFSS ARG1H, 7 ; ARG1H:ARG1L neg?
BRA CONT_CODE ; no, done
MOVF ARG2L, W ;
SUBWF RES2 ;
MOVF ARG2H, W ;
SUBWFB RES3
;
CONT_CODE
: © 2006 Microchip Technology Inc. DS39564C-page 73
PIC18FXX2
8.0 INTERRUPTS
The PIC18FXX2 devices have multiple interrupt
sources and an interrupt priority feature that allows
each interrupt source to be assigned a high priority
level or a low priority level. The high priority interrupt
vector is at 000008h and the low priority interrupt vector
is at 000018h. High priority interrupt events will override
any low priority interrupts that may be in progress.
There are ten registers which are used to control
interrupt operation. These registers are:
• RCON
• INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
It is recommended that the Microchip header files supplied
with MPLAB® IDE be used for the symbolic bit
names in these registers. This allows the assembler/
compiler to automatically take care of the placement of
these bits within the specified register.
Each interrupt source, except INT0, has three bits to
control its operation. The functions of these bits are:
• Flag bit to indicate that an interrupt event
occurred
• Enable bit that allows program execution to
branch to the interrupt vector address when the
flag bit is set
• Priority bit to select high priority or low priority
The interrupt priority feature is enabled by setting the
IPEN bit (RCON<7>). When interrupt priority is
enabled, there are two bits which enable interrupts globally.
Setting the GIEH bit (INTCON<7>) enables all
interrupts that have the priority bit set. Setting the GIEL
bit (INTCON<6>) enables all interrupts that have the
priority bit cleared. When the interrupt flag, enable bit
and appropriate global interrupt enable bit are set, the
interrupt will vector immediately to address 000008h or
000018h, depending on the priority level. Individual
interrupts can be disabled through their corresponding
enable bits.
When the IPEN bit is cleared (default state), the interrupt
priority feature is disabled and interrupts are compatible
with PICmicro® mid-range devices. In
Compatibility mode, the interrupt priority bits for each
source have no effect. INTCON<6> is the PEIE bit,
which enables/disables all peripheral interrupt sources.
INTCON<7> is the GIE bit, which enables/disables all
interrupt sources. All interrupts branch to address
000008h in Compatibility mode.
When an interrupt is responded to, the Global Interrupt
Enable bit is cleared to disable further interrupts. If the
IPEN bit is cleared, this is the GIE bit. If interrupt priority
levels are used, this will be either the GIEH or GIEL bit.
High priority interrupt sources can interrupt a low
priority interrupt.
The return address is pushed onto the stack and the
PC is loaded with the interrupt vector address
(000008h or 000018h). Once in the Interrupt Service
Routine, the source(s) of the interrupt can be determined
by polling the interrupt flag bits. The interrupt
flag bits must be cleared in software before re-enabling
interrupts to avoid recursive interrupts.
The “return from interrupt” instruction, RETFIE, exits
the interrupt routine and sets the GIE bit (GIEH or GIEL
if priority levels are used), which re-enables interrupts.
For external interrupt events, such as the INT pins or
the PORTB input change interrupt, the interrupt latency
will be three to four instruction cycles. The exact
latency is the same for one or two-cycle instructions.
Individual interrupt flag bits are set, regardless of the
status of their corresponding enable bit or the GIE bit.
Note: Do not use the MOVFF instruction to modify
any of the Interrupt control registers while
any interrupt is enabled. Doing so may
cause erratic microcontroller behavior.PIC18FXX2
DS39564C-page 74 © 2006 Microchip Technology Inc.
FIGURE 8-1: INTERRUPT LOGIC
TMR0IE
GIEH/GIE
GIEL/PEIE
Wake-up if in SLEEP mode
Interrupt to CPU
Vector to location
0008h
INT2IF
INT2IE
INT2IP
INT1IF
INT1IE
INT1IP
TMR0IF
TMR0IE
TMR0IP
RBIF
RBIE
RBIP
IPEN
TMR0IF
TMR0IP
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
RBIF
RBIE
RBIP
INT0IF
INT0IE
GIEL/PEIE
Interrupt to CPU
Vector to Location
IPEN
IPE
0018h
Peripheral Interrupt Flag bit
Peripheral Interrupt Enable bit
Peripheral Interrupt Priority bit
Peripheral Interrupt Flag bit
Peripheral Interrupt Enable bit
Peripheral Interrupt Priority bit
TMR1IF
TMR1IE
TMR1IP
XXXXIF
XXXXIE
XXXXIP
Additional Peripheral Interrupts
TMR1IF
TMR1IE
TMR1IP
High Priority Interrupt Generation
Low Priority Interrupt Generation
XXXXIF
XXXXIE
XXXXIP
Additional Peripheral Interrupts
GIE/GIEH© 2006 Microchip Technology Inc. DS39564C-page 75
PIC18FXX2
8.1 INTCON Registers
The INTCON Registers are readable and writable registers,
which contain various enable, priority and flag
bits.
REGISTER 8-1: INTCON REGISTER
Note: Interrupt flag bits are set when an interrupt
condition occurs, regardless of the state of
its corresponding enable bit or the global
enable bit. User software should ensure
the appropriate interrupt flag bits are clear
prior to enabling an interrupt. This feature
allows for software polling.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x
GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF
bit 7 bit 0
bit 7 GIE/GIEH: Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all high priority interrupts
0 = Disables all interrupts
bit 6 PEIE/GIEL: Peripheral Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low priority peripheral interrupts
0 = Disables all low 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
Note: A mismatch condition will continue to set this bit. Reading PORTB will end the
mismatch condition and allow the bit to be cleared.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 76 © 2006 Microchip Technology Inc.
REGISTER 8-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 '0'
bit 2 TMR0IP: TMR0 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 Unimplemented: Read as '0'
bit 0 RBIP: RB Port Change Interrupt Priority bit
1 = High priority
0 = Low priority
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.© 2006 Microchip Technology Inc. DS39564C-page 77
PIC18FXX2
REGISTER 8-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 = High priority
0 = Low priority
bit 6 INT1IP: INT1 External Interrupt Priority bit
1 = High priority
0 = Low priority
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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
Note: Interrupt flag bits are set when an interrupt condition occurs, regardless of the state
of its corresponding enable bit or the global enable bit. User software should ensure
the appropriate interrupt flag bits are clear prior to enabling an interrupt. This feature
allows for software polling.PIC18FXX2
DS39564C-page 78 © 2006 Microchip Technology Inc.
8.2 PIR Registers
The PIR registers contain the individual flag bits for the
peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Flag Registers (PIR1, PIR2).
REGISTER 8-4: PIR1: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 1
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>).
2: User software should ensure the appropriate
interrupt flag bits are cleared prior to enabling
an interrupt, and after servicing that interrupt.
R/W-0 R/W-0 R-0 R-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIF(1) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF
bit 7 bit 0
bit 7 PSPIF(1): 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 6 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 5 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 4 TXIF: USART Transmit Interrupt Flag bit (see Section 16.0 for details on TXIF functionality)
1 = The USART transmit buffer, TXREG, is empty (cleared when TXREG is written)
0 = The USART transmit buffer is full
bit 3 SSPIF: Master Synchronous Serial Port Interrupt Flag bit
1 = The transmission/reception is complete (must be cleared in software)
0 = Waiting to transmit/receive
bit 2 CCP1IF: CCP1 Interrupt Flag bit
Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
PWM mode:
Unused in this mode
bit 1 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 0 TMR1IF: TMR1 Overflow Interrupt Flag bit
1 = TMR1 register overflowed (must be cleared in software)
0 = MR1 register did not overflow
Note 1: This bit is reserved on PIC18F2X2 devices; always maintain this bit clear.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 79
PIC18FXX2
REGISTER 8-5: PIR2: PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 2
U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — — EEIF BCLIF LVDIF TMR3IF CCP2IF
bit 7 bit 0
bit 7-5 Unimplemented: Read as '0'
bit 4 EEIF: Data EEPROM/FLASH Write Operation Interrupt Flag bit
1 = The Write operation is complete (must be cleared in software)
0 = The Write operation is not complete, or has not been started
bit 3 BCLIF: Bus Collision Interrupt Flag bit
1 = A bus collision occurred (must be cleared in software)
0 = No bus collision occurred
bit 2 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
bit 1 TMR3IF: TMR3 Overflow Interrupt Flag bit
1 = TMR3 register overflowed (must be cleared in software)
0 = TMR3 register did not overflow
bit 0 CCP2IF: 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
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 80 © 2006 Microchip Technology Inc.
8.3 PIE Registers
The PIE registers contain the individual enable bits for
the peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Enable Registers (PIE1, PIE2). When IPEN = 0,
the PEIE bit must be set to enable any of these
peripheral interrupts.
REGISTER 8-6: PIE1: PERIPHERAL INTERRUPT ENABLE REGISTER 1
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
PSPIE(1) ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE
bit 7 bit 0
bit 7 PSPIE(1): Parallel Slave Port Read/Write Interrupt Enable bit
1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt
bit 6 ADIE: A/D Converter Interrupt Enable bit
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
bit 5 RCIE: USART Receive Interrupt Enable bit
1 = Enables the USART receive interrupt
0 = Disables the USART receive interrupt
bit 4 TXIE: USART Transmit Interrupt Enable bit
1 = Enables the USART transmit interrupt
0 = Disables the USART transmit interrupt
bit 3 SSPIE: Master Synchronous Serial Port Interrupt Enable bit
1 = Enables the MSSP interrupt
0 = Disables the MSSP interrupt
bit 2 CCP1IE: CCP1 Interrupt Enable bit
1 = Enables the CCP1 interrupt
0 = Disables the CCP1 interrupt
bit 1 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 0 TMR1IE: TMR1 Overflow Interrupt Enable bit
1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt
Note 1: This bit is reserved on PIC18F2X2 devices; always maintain this bit clear.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 81
PIC18FXX2
REGISTER 8-7: PIE2: PERIPHERAL INTERRUPT ENABLE REGISTER 2
U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — — EEIE BCLIE LVDIE TMR3IE CCP2IE
bit 7 bit 0
bit 7-5 Unimplemented: Read as '0'
bit 4 EEIE: Data EEPROM/FLASH Write Operation Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 3 BCLIE: Bus Collision Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 2 LVDIE: Low Voltage Detect Interrupt Enable bit
1 = Enabled
0 = Disabled
bit 1 TMR3IE: TMR3 Overflow Interrupt Enable bit
1 = Enables the TMR3 overflow interrupt
0 = Disables the TMR3 overflow interrupt
bit 0 CCP2IE: CCP2 Interrupt Enable bit
1 = Enables the CCP2 interrupt
0 = Disables the CCP2 interrupt
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 82 © 2006 Microchip Technology Inc.
8.4 IPR Registers
The IPR registers contain the individual priority bits for
the peripheral interrupts. Due to the number of peripheral
interrupt sources, there are two Peripheral Interrupt
Priority Registers (IPR1, IPR2). The operation of
the priority bits requires that the Interrupt Priority
Enable (IPEN) bit be set.
REGISTER 8-8: IPR1: PERIPHERAL INTERRUPT PRIORITY REGISTER 1
R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
PSPIP(1) ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP
bit 7 bit 0
bit 7 PSPIP(1): Parallel Slave Port Read/Write Interrupt Priority bit
1 = High priority
0 = Low priority
bit 6 ADIP: A/D Converter Interrupt Priority bit
1 = High priority
0 = Low priority
bit 5 RCIP: USART Receive Interrupt Priority bit
1 = High priority
0 = Low priority
bit 4 TXIP: USART Transmit Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 SSPIP: Master Synchronous Serial Port Interrupt Priority bit
1 = High priority
0 = Low priority
bit 2 CCP1IP: CCP1 Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR2IP: TMR2 to PR2 Match Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 TMR1IP: TMR1 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
Note 1: This bit is reserved on PIC18F2X2 devices; always maintain this bit set.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 83
PIC18FXX2
REGISTER 8-9: IPR2: PERIPHERAL INTERRUPT PRIORITY REGISTER 2
U-0 U-0 U-0 R/W-1 R/W-1 R/W-1 R/W-1 R/W-1
— — — EEIP BCLIP LVDIP TMR3IP CCP2IP
bit 7 bit 0
bit 7-5 Unimplemented: Read as '0'
bit 4 EEIP: Data EEPROM/FLASH Write Operation Interrupt Priority bit
1 = High priority
0 = Low priority
bit 3 BCLIP: Bus Collision Interrupt Priority bit
1 = High priority
0 = Low priority
bit 2 LVDIP: Low Voltage Detect Interrupt Priority bit
1 = High priority
0 = Low priority
bit 1 TMR3IP: TMR3 Overflow Interrupt Priority bit
1 = High priority
0 = Low priority
bit 0 CCP2IP: CCP2 Interrupt Priority bit
1 = High priority
0 = Low priority
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 84 © 2006 Microchip Technology Inc.
8.5 RCON Register
The RCON register contains the bit which is used to
enable prioritized interrupts (IPEN).
REGISTER 8-10: RCON REGISTER
R/W-0 U-0 U-0 R/W-1 R-1 R-1 R/W-0 R/W-0
IPEN — — RI TO PD POR BOR
bit 7 bit 0
bit 7 IPEN: Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts (16CXXX Compatibility mode)
bit 6-5 Unimplemented: Read as '0'
bit 4 RI: RESET Instruction Flag bit
For details of bit operation, see Register 4-3
bit 3 TO: Watchdog Time-out Flag bit
For details of bit operation, see Register 4-3
bit 2 PD: Power-down Detection Flag bit
For details of bit operation, see Register 4-3
bit 1 POR: Power-on Reset Status bit
For details of bit operation, see Register 4-3
bit 0 BOR: Brown-out Reset Status bit
For details of bit operation, see Register 4-3
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 85
PIC18FXX2
8.6 INT0 Interrupt
External interrupts on the RB0/INT0, RB1/INT1 and
RB2/INT2 pins are edge triggered: either rising, if the
corresponding INTEDGx bit is set in the INTCON2 register,
or falling, if the INTEDGx bit is clear. When a valid
edge appears on the RBx/INTx pin, the corresponding
flag bit INTxF is set. This interrupt can be disabled by
clearing the corresponding enable bit INTxE. Flag bit
INTxF must be cleared in software in the Interrupt Service
Routine before re-enabling the interrupt. All external
interrupts (INT0, INT1 and INT2) can wake-up the
processor from SLEEP, if bit INTxE was set prior to
going into SLEEP. If the global interrupt enable bit GIE
is set, the processor will branch to the interrupt vector
following wake-up.
Interrupt priority for INT1 and INT2 is determined by the
value contained in the interrupt priority bits, INT1IP
(INTCON3<6>) and INT2IP (INTCON3<7>). There is
no priority bit associated with INT0. It is always a high
priority interrupt source.
8.7 TMR0 Interrupt
In 8-bit mode (which is the default), an overflow
(FFh → 00h) in the TMR0 register will set flag bit
TMR0IF. In 16-bit mode, an overflow (FFFFh → 0000h)
in the TMR0H:TMR0L registers will set flag bit TMR0IF.
The interrupt can be enabled/disabled by setting/
clearing enable bit T0IE (INTCON<5>). Interrupt priority
for Timer0 is determined by the value contained in
the interrupt priority bit TMR0IP (INTCON2<2>). See
Section 10.0 for further details on the Timer0 module.
8.8 PORTB Interrupt-on-Change
An input change on PORTB<7:4> sets flag bit RBIF
(INTCON<0>). The interrupt can be enabled/disabled
by setting/clearing enable bit, RBIE (INTCON<3>).
Interrupt priority for PORTB interrupt-on-change is
determined by the value contained in the interrupt
priority bit, RBIP (INTCON2<0>).
8.9 Context Saving During Interrupts
During an interrupt, the return PC value is saved on the
stack. Additionally, the WREG, STATUS and BSR registers
are saved on the fast return stack. If a fast return
from interrupt is not used (See Section 4.3), the user
may need to save the WREG, STATUS and BSR registers
in software. Depending on the user’s application,
other registers may also need to be saved. Equation 8-1
saves and restores the WREG, STATUS and BSR
registers during an Interrupt Service Routine.
EXAMPLE 8-1: SAVING STATUS, WREG AND BSR REGISTERS IN RAM
MOVWF W_TEMP ; W_TEMP is in virtual bank
MOVFF STATUS, STATUS_TEMP ; STATUS_TEMP located anywhere
MOVFF BSR, BSR_TEMP ; BSR located anywhere
;
; USER ISR CODE
;
MOVFF BSR_TEMP, BSR ; Restore BSR
MOVF W_TEMP, W ; Restore WREG
MOVFF STATUS_TEMP,STATUS ; Restore STATUSPIC18FXX2
DS39564C-page 86 © 2006 Microchip Technology Inc.
NOTES: © 2006 Microchip Technology Inc. DS39564C-page 87
PIC18FXX2
9.0 I/O PORTS
Depending on the device selected, there are either five
ports or three ports available. Some pins of the I/O
ports are multiplexed with an alternate function from
the peripheral features on the device. In general, when
a peripheral is enabled, that pin may not be used as a
general purpose I/O pin.
Each port has three registers for its operation. These
registers are:
• TRIS register (data direction register)
• PORT register (reads the levels on the pins of the
device)
• LAT register (output latch)
The data latch (LAT register) is useful for read-modifywrite
operations on the value that the I/O pins are
driving.
9.1 PORTA, TRISA and LATA
Registers
PORTA is a 7-bit wide, bi-directional port. The corresponding
Data Direction register is TRISA. Setting a
TRISA bit (= 1) will make the corresponding PORTA pin
an input (i.e., put the corresponding output driver in a
Hi-Impedance mode). Clearing a TRISA bit (= 0) will
make the corresponding PORTA pin an output (i.e., put
the contents of the output latch on the selected pin).
Reading the PORTA register reads the status of the
pins, whereas writing to it will write to the port latch.
The Data Latch register (LATA) is also memory
mapped. Read-modify-write operations on the LATA
register reads and writes the latched output value for
PORTA.
The RA4 pin is multiplexed with the Timer0 module
clock input to become the RA4/T0CKI pin. The RA4/
T0CKI 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.
The other PORTA pins are multiplexed with analog
inputs and the analog VREF+ and VREF- inputs. The
operation of each pin is selected by clearing/setting the
control bits in the ADCON1 register (A/D Control
Register1).
The TRISA register controls the direction of the RA
pins, even when they are being used as analog inputs.
The user must ensure the bits in the TRISA register are
maintained set when using them as analog inputs.
EXAMPLE 9-1: INITIALIZING PORTA
FIGURE 9-1: BLOCK DIAGRAM OF
RA3:RA0 AND RA5 PINS
Note: On a Power-on Reset, RA5 and RA3:RA0
are configured as analog inputs and read
as ‘0’. RA6 and RA4 are configured as
digital inputs.
CLRF PORTA ; Initialize PORTA by
; clearing output
; data latches
CLRF LATA ; Alternate method
; to clear output
; data latches
MOVLW 0x07 ; Configure A/D
MOVWF ADCON1 ; for digital inputs
MOVLW 0xCF ; Value used to
; initialize data
; direction
MOVWF TRISA ; Set RA<3:0> as inputs
; RA<5:4> as outputs
Data
Bus
D Q
CK Q
D Q
CK Q
Q D
EN
P
N
WR LATA
WR TRISA
Data Latch
TRIS Latch
RD TRISA
RD PORTA
VSS
VDD
I/O pin(1)
Note 1: I/O pins have protection diodes to VDD and VSS.
Analog
Input
Mode
TTL
Input
Buffer
To A/D Converter and LVD Modules
RD LATA
or
PORTA
SS Input (RA5 only)PIC18FXX2
DS39564C-page 88 © 2006 Microchip Technology Inc.
FIGURE 9-2: BLOCK DIAGRAM OF
RA4/T0CKI PIN
FIGURE 9-3: BLOCK DIAGRAM OF
RA6 PIN
Data
Bus
WR TRISA
RD PORTA
Data Latch
TRIS Latch
RD TRISA
Schmitt
Trigger
Input
Buffer
N
VSS
I/O pin(1)
TMR0 Clock Input
D Q
CK Q
D Q
CK Q
EN
Q D
EN
RD LATA
WR LATA
or
PORTA
Note 1: I/O pin has protection diode to VSS only.
Data
Bus
D Q
CK Q
Q D
EN
P
N
WR LATA
WR
Data Latch
TRIS Latch
RD TRISA
RD PORTA
VSS
VDD
I/O pin(1)
Note 1: I/O pins have protection diodes to VDD and VSS.
or
PORTA
RD LATA
ECRA6 or
ECRA6 or
Enable
TTL
Input
Buffer
RCRA6
RCRA6 Enable
TRISA
D Q
CK Q© 2006 Microchip Technology Inc. DS39564C-page 89
PIC18FXX2
TABLE 9-1: PORTA FUNCTIONS
TABLE 9-2: SUMMARY OF REGISTERS ASSOCIATED WITH PORTA
Name Bit# Buffer Function
RA0/AN0 bit0 TTL Input/output or analog input.
RA1/AN1 bit1 TTL Input/output or analog input.
RA2/AN2/VREF- bit2 TTL Input/output or analog input or VREF-.
RA3/AN3/VREF+ bit3 TTL Input/output or analog input or VREF+.
RA4/T0CKI bit4 ST Input/output or external clock input for Timer0.
Output is open drain type.
RA5/SS/AN4/LVDIN bit5 TTL Input/output or slave select input for synchronous serial port or analog
input, or low voltage detect input.
OSC2/CLKO/RA6 bit6 TTL OSC2 or clock output or I/O pin.
Legend: TTL = TTL input, ST = Schmitt Trigger input
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
PORTA — RA6 RA5 RA4 RA3 RA2 RA1 RA0 -x0x 0000 -u0u 0000
LATA — LATA Data Output Register -xxx xxxx -uuu uuuu
TRISA — PORTA Data Direction Register -111 1111 -111 1111
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 00-- 0000 00-- 0000
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTA.PIC18FXX2
DS39564C-page 90 © 2006 Microchip Technology Inc.
9.2 PORTB, TRISB and LATB
Registers
PORTB is an 8-bit wide, bi-directional port. The corresponding
Data Direction register is TRISB. Setting a
TRISB bit (= 1) will make the corresponding PORTB pin
an input (i.e., put the corresponding output driver in a
Hi-Impedance mode). Clearing a TRISB bit (= 0) will
make the corresponding PORTB pin an output (i.e., put
the contents of the output latch on the selected pin).
The Data Latch register (LATB) is also memory
mapped. Read-modify-write operations on the LATB
register reads and writes the latched output value for
PORTB.
EXAMPLE 9-2: INITIALIZING PORTB
Each of the PORTB pins has a weak internal pull-up. A
single control bit can turn on all the pull-ups. This is performed
by clearing bit RBPU (INTCON2<7>). The
weak pull-up is automatically turned off when the port
pin is configured as an output. The pull-ups are
disabled on a Power-on Reset.
Four of the PORTB pins, RB7:RB4, have an interrupton-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 interrupton-change
comparison). The input pins (of RB7:RB4)
are compared with the old value latched on the last
read of PORTB. The “mismatch” outputs of RB7:RB4
are OR’ed together to generate the RB Port Change
Interrupt with flag bit, RBIF (INTCON<0>).
This interrupt can wake the device from SLEEP. The
user, in the Interrupt Service Routine, can clear the
interrupt in the following manner:
a) Any read or write of PORTB (except with the
MOVFF instruction). This will end the mismatch
condition.
b) Clear flag bit RBIF.
A mismatch condition will continue to set flag bit RBIF.
Reading PORTB will end the mismatch condition and
allow flag bit RBIF to be cleared.
The interrupt-on-change feature is recommended for
wake-up on key depression operation and operations
where PORTB is only used for the interrupt-on-change
feature. Polling of PORTB is not recommended while
using the interrupt-on-change feature.
RB3 can be configured by the configuration bit
CCP2MX as the alternate peripheral pin for the CCP2
module (CCP2MX=’0’).
FIGURE 9-4: BLOCK DIAGRAM OF
RB7:RB4 PINS
Note: On a Power-on Reset, these pins are
configured as digital inputs.
CLRF PORTB ; Initialize PORTB by
; clearing output
; data latches
CLRF LATB ; Alternate method
; to clear output
; data latches
MOVLW 0xCF ; Value used to
; initialize data
; direction
MOVWF TRISB ; Set RB<3:0> as inputs
; RB<5:4> as outputs
; RB<7:6> as inputs
Note 1: While in Low Voltage ICSP mode, the
RB5 pin can no longer be used as a general
purpose I/O pin, and should be held
low during normal operation to protect
against inadvertent ICSP mode entry.
2: When using Low Voltage ICSP programming
(LVP), the pull-up on RB5 becomes
disabled. If TRISB bit 5 is cleared,
thereby setting RB5 as an output, LATB
bit 5 must also be cleared for proper
operation.
Data Latch
From other
RBPU(2)
P
VDD
I/O pin(1)
D Q
CK
D Q
CK
Q D
EN
Q D
EN
Data Bus
WR LATB
WR TRISB
Set RBIF
TRIS Latch
RD TRISB
RD PORTB
RB7:RB4 pins
Weak
Pull-up
RD PORTB
Latch
TTL
Input
Buffer ST
Buffer
RB7:RB5 in Serial Programming mode
Q3
Q1
RD LATB
or
PORTB
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s)
and clear the RBPU bit (INTCON2<7>).© 2006 Microchip Technology Inc. DS39564C-page 91
PIC18FXX2
FIGURE 9-5: BLOCK DIAGRAM OF RB2:RB0 PINS
FIGURE 9-6: BLOCK DIAGRAM OF RB3 PIN
Data Latch
RBPU(2)
P
VDD
D Q
CK
D Q
CK
Q D
EN
Data Bus
WR Port
WR TRIS
RD TRIS
RD Port
Weak
Pull-up
RD Port
RB0/INT
I/O pin(1)
TTL
Input
Buffer
Schmitt Trigger
Buffer
TRIS Latch
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>).
Data Latch
P
VDD
D Q
CK
Q D
EN
Data Bus
WR LATB or
WR TRISB
RD TRISB
RD PORTB
Weak
Pull-up
CCP2 Input(3)
TTL
Input
Buffer
Schmitt Trigger
Buffer
TRIS Latch
RD LATB
WR PORTB
RBPU(2)
CK
D
Enable(3)
CCP Output
RD PORTB
CCP Output(3) 1
0
P
N
VDD
VSS
I/O pin(1)
Q
CCP2MX
CCP2MX = 0
Note 1: I/O pin has diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate DDR bit(s) and clear the RBPU bit (INTCON2<7>).
3: The CCP2 input/output is multiplexed with RB3 if the CCP2MX bit is enabled (=’0’) in the configuration register. PIC18FXX2
DS39564C-page 92 © 2006 Microchip Technology Inc.
TABLE 9-3: PORTB FUNCTIONS
TABLE 9-4: SUMMARY OF REGISTERS ASSOCIATED WITH PORTB
Name Bit# Buffer Function
RB0/INT0 bit0 TTL/ST(1) Input/output pin or external interrupt input0.
Internal software programmable weak pull-up.
RB1/INT1 bit1 TTL/ST(1) Input/output pin or external interrupt input1.
Internal software programmable weak pull-up.
RB2/INT2 bit2 TTL/ST(1) Input/output pin or external interrupt input2.
Internal software programmable weak pull-up.
RB3/CCP2(3) bit3 TTL/ST(4) Input/output pin or Capture2 input/Compare2 output/PWM output when
CCP2MX configuration bit is enabled.
Internal software programmable weak pull-up.
RB4 bit4 TTL Input/output pin (with interrupt-on-change).
Internal software programmable weak pull-up.
RB5/PGM(5) bit5 TTL/ST(2) Input/output pin (with interrupt-on-change).
Internal software programmable weak pull-up.
Low voltage ICSP enable pin.
RB6/PGC bit6 TTL/ST(2) Input/output pin (with interrupt-on-change).
Internal software programmable weak pull-up.
Serial programming clock.
RB7/PGD bit7 TTL/ST(2) Input/output pin (with interrupt-on-change).
Internal software programmable weak pull-up.
Serial programming data.
Legend: TTL = TTL input, ST = Schmitt Trigger input
Note 1: This buffer is a Schmitt Trigger input when configured as the external interrupt.
2: This buffer is a Schmitt Trigger input when used in Serial Programming mode.
3: A device configuration bit selects which I/O pin the CCP2 pin is multiplexed on.
4: This buffer is a Schmitt Trigger input when configured as the CCP2 input.
5: Low Voltage ICSP Programming (LVP) is enabled by default, which disables the RB5 I/O function. LVP
must be disabled to enable RB5 as an I/O pin and allow maximum compatibility to the other 28-pin and
40-pin mid-range devices.
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
PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 xxxx xxxx uuuu uuuu
LATB LATB Data Output Register xxxx xxxx uuuu uuuu
TRISB PORTB Data Direction Register 1111 1111 1111 1111
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
INTCON2 RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP 1111 -1-1 1111 -1-1
INTCON3 INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF 11-0 0-00 11-0 0-00
Legend: x = unknown, u = unchanged. Shaded cells are not used by PORTB.© 2006 Microchip Technology Inc. DS39564C-page 93
PIC18FXX2
9.3 PORTC, TRISC and LATC
Registers
PORTC is an 8-bit wide, bi-directional port. The corresponding
Data Direction register is TRISC. Setting a
TRISC bit (= 1) will make the corresponding PORTC
pin an input (i.e., put the corresponding output driver in
a Hi-Impedance mode). Clearing a TRISC bit (= 0) will
make the corresponding PORTC pin an output (i.e., put
the contents of the output latch on the selected pin).
The Data Latch register (LATC) is also memory
mapped. Read-modify-write operations on the LATC
register reads and writes the latched output value for
PORTC.
PORTC is multiplexed with several peripheral functions
(Table 9-5). 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. The user should refer to the corresponding
peripheral section for the correct TRIS bit
settings.
The pin override value is not loaded into the TRIS register.
This allows read-modify-write of the TRIS register,
without concern due to peripheral overrides.
RC1 is normally configured by configuration bit,
CCP2MX, as the default peripheral pin of the CCP2
module (default/erased state, CCP2MX = ’1’).
EXAMPLE 9-3: INITIALIZING PORTC
FIGURE 9-7: PORTC BLOCK DIAGRAM (PERIPHERAL OUTPUT OVERRIDE)
Note: On a Power-on Reset, these pins are
configured as digital inputs.
CLRF PORTC ; Initialize PORTC by
; clearing output
; data latches
CLRF LATC ; Alternate method
; to clear output
; data latches
MOVLW 0xCF ; Value used to
; initialize data
; direction
MOVWF TRISC ; Set RC<3:0> as inputs
; RC<5:4> as outputs
; RC<7:6> as inputs
Data Bus
WR LATC or
WR TRISC
RD TRISC
D Q
CK Q
Q D
EN
Peripheral Data Out
0
1
D Q
CK Q
RD PORTC
Peripheral Data In
WR PORTC
RD LATC
Peripheral Output
Schmitt
Port/Peripheral Select(2)
Enable(3)
P
N
VSS
VDD
I/O pin(1)
Note 1: I/O pins have diode protection to VDD and VSS.
2: Port/Peripheral Select signal selects between port data (input) and peripheral output.
3: Peripheral Output Enable is only active if peripheral select is active.
Data Latch
TRIS Latch
TriggerPIC18FXX2
DS39564C-page 94 © 2006 Microchip Technology Inc.
TABLE 9-5: PORTC FUNCTIONS
TABLE 9-6: SUMMARY OF REGISTERS ASSOCIATED WITH PORTC
Name Bit# Buffer Type Function
RC0/T1OSO/T1CKI bit0 ST Input/output port pin or Timer1 oscillator output/Timer1 clock input.
RC1/T1OSI/CCP2 bit1 ST Input/output port pin, Timer1 oscillator input, or Capture2 input/
Compare2 output/PWM output when CCP2MX configuration bit is
set.
RC2/CCP1 bit2 ST Input/output port pin or Capture1 input/Compare1 output/PWM1
output.
RC3/SCK/SCL bit3 ST RC3 can also be the synchronous serial clock for both SPI and I2C
modes.
RC4/SDI/SDA bit4 ST RC4 can also be the SPI Data In (SPI mode) or Data I/O (I2C mode).
RC5/SDO bit5 ST Input/output port pin or Synchronous Serial Port data output.
RC6/TX/CK bit6 ST Input/output port pin, Addressable USART Asynchronous Transmit, or
Addressable USART Synchronous Clock.
RC7/RX/DT bit7 ST Input/output port pin, Addressable USART Asynchronous Receive, or
Addressable USART Synchronous Data.
Legend: ST = Schmitt Trigger input
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
PORTC RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0 xxxx xxxx uuuu uuuu
LATC LATC Data Output Register xxxx xxxx uuuu uuuu
TRISC PORTC Data Direction Register 1111 1111 1111 1111
Legend: x = unknown, u = unchanged© 2006 Microchip Technology Inc. DS39564C-page 95
PIC18FXX2
9.4 PORTD, TRISD and LATD
Registers
This section is applicable only to the PIC18F4X2
devices.
PORTD is an 8-bit wide, bi-directional port. The corresponding
Data Direction register is TRISD. Setting a
TRISD bit (= 1) will make the corresponding PORTD
pin an input (i.e., put the corresponding output driver in
a Hi-Impedance mode). Clearing a TRISD bit (= 0) will
make the corresponding PORTD pin an output (i.e., put
the contents of the output latch on the selected pin).
The Data Latch register (LATD) is also memory
mapped. Read-modify-write operations on the LATD
register reads and writes the latched output value for
PORTD.
PORTD is an 8-bit port with Schmitt Trigger input buffers.
Each pin is individually configurable as an input or
output.
PORTD can be configured as an 8-bit wide microprocessor
port (parallel slave port) by setting control bit
PSPMODE (TRISE<4>). In this mode, the input buffers
are TTL. See Section 9.6 for additional information on
the Parallel Slave Port (PSP).
EXAMPLE 9-4: INITIALIZING PORTD
FIGURE 9-8: PORTD BLOCK DIAGRAM
IN I/O PORT MODE
Note: On a Power-on Reset, these pins are
configured as digital inputs.
CLRF PORTD ; Initialize PORTD by
; clearing output
; data latches
CLRF LATD ; Alternate method
; to clear output
; data latches
MOVLW 0xCF ; Value used to
; initialize data
; direction
MOVWF TRISD ; Set RD<3:0> as inputs
; RD<5:4> as outputs
; RD<7:6> as inputs
Data
Bus
WR LATD
WR TRISD
RD PORTD
Data Latch
TRIS Latch
RD TRISD
Schmitt
Trigger
Input
Buffer
I/O pin(1)
D Q
CK
D Q
CK
EN
Q D
EN
RD LATD
or
PORTD
Note 1: I/O pins have diode protection to VDD and VSS.PIC18FXX2
DS39564C-page 96 © 2006 Microchip Technology Inc.
TABLE 9-7: PORTD FUNCTIONS
TABLE 9-8: SUMMARY OF REGISTERS ASSOCIATED WITH PORTD
Name Bit# Buffer Type Function
RD0/PSP0 bit0 ST/TTL(1) Input/output port pin or parallel slave port bit0.
RD1/PSP1 bit1 ST/TTL(1) Input/output port pin or parallel slave port bit1.
RD2/PSP2 bit2 ST/TTL(1) Input/output port pin or parallel slave port bit2.
RD3/PSP3 bit3 ST/TTL(1) Input/output port pin or parallel slave port bit3.
RD4/PSP4 bit4 ST/TTL(1) Input/output port pin or parallel slave port bit4.
RD5/PSP5 bit5 ST/TTL(1) Input/output port pin or parallel slave port bit5.
RD6/PSP6 bit6 ST/TTL(1) Input/output port pin or parallel slave port bit6.
RD7/PSP7 bit7 ST/TTL(1) Input/output port pin or parallel slave port bit7.
Legend: ST = Schmitt Trigger input, TTL = TTL input
Note 1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffer when in Parallel Slave Port mode.
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 RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0 xxxx xxxx uuuu uuuu
LATD LATD Data Output Register xxxx xxxx uuuu uuuu
TRISD PORTD Data Direction Register 1111 1111 1111 1111
TRISE IBF OBF IBOV PSPMODE — PORTE Data Direction bits 0000 -111 0000 -111
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by PORTD.© 2006 Microchip Technology Inc. DS39564C-page 97
PIC18FXX2
9.5 PORTE, TRISE and LATE
Registers
This section is only applicable to the PIC18F4X2
devices.
PORTE is a 3-bit wide, bi-directional port. The corresponding
Data Direction register is TRISE. Setting a
TRISE bit (= 1) will make the corresponding PORTE pin
an input (i.e., put the corresponding output driver in a
Hi-Impedance mode). Clearing a TRISE bit (= 0) will
make the corresponding PORTE pin an output (i.e., put
the contents of the output latch on the selected pin).
The Data Latch register (LATE) is also memory
mapped. Read-modify-write operations on the LATE
register reads and writes the latched output value for
PORTE.
PORTE has three pins (RE0/RD/AN5, RE1/WR/AN6
and RE2/CS/AN7) which are individually configurable
as inputs or outputs. These pins have Schmitt Trigger
input buffers.
Register 9-1 shows the TRISE register, which also
controls the parallel slave port operation.
PORTE pins are multiplexed with analog inputs. When
selected as an analog input, these pins will read as '0's.
TRISE controls the direction of the RE pins, even when
they are being used as analog inputs. The user must
make sure to keep the pins configured as inputs when
using them as analog inputs.
EXAMPLE 9-5: INITIALIZING PORTE
FIGURE 9-9: PORTE BLOCK DIAGRAM
IN I/O PORT MODE
Note: On a Power-on Reset, these pins are
configured as analog inputs.
CLRF PORTE ; Initialize PORTE by
; clearing output
; data latches
CLRF LATE ; Alternate method
; to clear output
; data latches
MOVLW 0x07 ; Configure A/D
MOVWF ADCON1 ; for digital inputs
MOVLW 0x05 ; Value used to
; initialize data
; direction
MOVWF TRISE ; Set RE<0> as inputs
; RE<1> as outputs
; RE<2> as inputs
Data
Bus
WR LATE
WR TRISE
RD PORTE
Data Latch
TRIS Latch
RD TRISE
Schmitt
Trigger
Input
Buffer
D Q
CK
D Q
CK
EN
Q D
EN
I/O pin(1)
RD LATE
or
PORTE
To Analog Converter
Note 1: I/O pins have diode protection to VDD and VSS.PIC18FXX2
DS39564C-page 98 © 2006 Microchip Technology Inc.
REGISTER 9-1: 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 0
bit 7 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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 99
PIC18FXX2
TABLE 9-9: PORTE FUNCTIONS
TABLE 9-10: SUMMARY OF REGISTERS ASSOCIATED WITH PORTE
Name Bit# Buffer Type Function
RE0/RD/AN5 bit0 ST/TTL(1)
Input/output port pin or read control input in Parallel Slave Port mode
or analog input:
RD
1 = Not a read operation
0 = Read operation. Reads PORTD register (if chip selected).
RE1/WR/AN6 bit1 ST/TTL(1)
Input/output port pin or write control input in Parallel Slave Port mode
or analog input:
WR
1 = Not a write operation
0 = Write operation. Writes PORTD register (if chip selected).
RE2/CS/AN7 bit2 ST/TTL(1)
Input/output port pin or chip select control input in Parallel Slave Port
mode or analog input:
CS
1 = Device is not selected
0 = Device is selected
Legend: ST = Schmitt Trigger input, TTL = TTL input
Note 1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode.
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
PORTE — — — — — RE2 RE1 RE0 ---- -000 ---- -000
LATE — — — — — LATE Data Output Register ---- -xxx ---- -uuu
TRISE IBF OBF IBOV PSPMODE — PORTE Data Direction bits 0000 -111 0000 -111
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 00-- 0000 00-- 0000
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by PORTE.PIC18FXX2
DS39564C-page 100 © 2006 Microchip Technology Inc.
9.6 Parallel Slave Port
The Parallel Slave Port is implemented on the 40-pin
devices only (PIC18F4X2).
PORTD operates as an 8-bit wide Parallel Slave Port,
or microprocessor port when control bit, PSPMODE
(TRISE<4>) is set. It is asynchronously readable and
writable by the external world through RD control input
pin, RE0/RD and WR control input pin, RE1/WR.
It can directly interface to an 8-bit microprocessor data
bus. The external microprocessor can read or write the
PORTD latch as an 8-bit latch. Setting bit PSPMODE
enables port pin RE0/RD to be the RD input, RE1/WR
to be the WR input and RE2/CS to be the CS (chip
select) input. For this functionality, the corresponding
data direction bits of the TRISE register (TRISE<2:0>)
must be configured as inputs (set). The A/D port configuration
bits PCFG2:PCFG0 (ADCON1<2:0>) must be
set, which will configure pins RE2:RE0 as digital I/O.
A write to the PSP occurs when both the CS and WR
lines are first detected low. A read from the PSP occurs
when both the CS and RD lines are first detected low.
The PORTE I/O pins become control inputs for the
microprocessor port when bit PSPMODE (TRISE<4>)
is set. In this mode, the user must make sure that the
TRISE<2:0> bits are set (pins are configured as digital
inputs), and the ADCON1 is configured for digital I/O.
In this mode, the input buffers are TTL.
FIGURE 9-10: PORTD AND PORTE
BLOCK DIAGRAM
(PARALLEL SLAVE
PORT)
FIGURE 9-11: PARALLEL SLAVE PORT WRITE WAVEFORMS
Data Bus
WR LATD
RDx
D Q
CK
EN
Q D
RD PORTD EN
Pin
One bit of PORTD
Set Interrupt Flag
PSPIF (PIR1<7>)
Read
Chip Select
Write
RD
CS
WR
Note: I/O pin has protection diodes to VDD and VSS.
TTL
TTL
TTL
TTL
or
PORTD
RD LATD
Data Latch
TRIS Latch
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
RD
IBF
OBF
PSPIF
PORTD<7:0>© 2006 Microchip Technology Inc. DS39564C-page 101
PIC18FXX2
FIGURE 9-12: PARALLEL SLAVE PORT READ WAVEFORMS
TABLE 9-11: REGISTERS ASSOCIATED WITH PARALLEL SLAVE PORT
Q1 Q2 Q3 Q4
CS
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
WR
IBF
PSPIF
RD
OBF
PORTD<7:0>
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
PORTE — — — — — RE2 RE1 RE0 ---- -000 ---- -000
LATE — — — — — LATE Data Output bits ---- -xxx ---- -uuu
TRISE IBF OBF IBOV PSPMODE — PORTE Data Direction bits 0000 -111 0000 -111
INTCON GIE/
GIEH
PEIE/
GIEL
TMR0IF INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
PIR1 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 00-- 0000 00-- 0000
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Parallel Slave Port.PIC18FXX2
DS39564C-page 102 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 103
PIC18FXX2
10.0 TIMER0 MODULE
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 in 8-bit
mode and FFFFh to 0000h in 16-bit mode
• Edge select for external clock
Figure 10-1 shows a simplified block diagram of the
Timer0 module in 8-bit mode and Figure 10-2 shows a
simplified block diagram of the Timer0 module in 16-bit
mode.
The T0CON register (Register 10-1) is a readable and
writable register that controls all the aspects of Timer0,
including the prescale selection.
REGISTER 10-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
bit 7 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
0 = Internal instruction cycle clock (CLKO)
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
111 = 1:256 prescale value
110 = 1:128 prescale value
101 = 1:64 prescale value
100 = 1:32 prescale value
011 = 1:16 prescale value
010 = 1:8 prescale value
001 = 1:4 prescale value
000 = 1:2 prescale value
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 104 © 2006 Microchip Technology Inc.
FIGURE 10-1: TIMER0 BLOCK DIAGRAM IN 8-BIT MODE
FIGURE 10-2: TIMER0 BLOCK DIAGRAM IN 16-BIT MODE
Note: Upon RESET, Timer0 is enabled in 8-bit mode with clock input from T0CKI max. prescale.
RA4/T0CKI pin
T0SE
0
1
1
0
T0CS
FOSC/4
Programmable
Prescaler
Sync with
Internal
Clocks
TMR0L
(2 TCY delay)
Data Bus
8
PSA
T0PS2, T0PS1, T0PS0
Set Interrupt
Flag bit TMR0IF
on Overflow
3
Note: Upon RESET, Timer0 is enabled in 8-bit mode with clock input from T0CKI max. prescale.
T0CKI pin
T0SE
0
1
1
0
T0CS
FOSC/4
Programmable Prescaler
Sync with
Internal
Clocks TMR0L
(2 TCY delay)
Data Bus<7:0>
8
PSA
T0PS2, T0PS1, T0PS0
Set Interrupt
Flag bit TMR0IF
on Overflow
3
TMR0
TMR0H
High Byte
8
8
8
Read TMR0L
Write TMR0L© 2006 Microchip Technology Inc. DS39564C-page 105
PIC18FXX2
10.1 Timer0 Operation
Timer0 can operate as a timer or as a counter.
Timer mode is selected by clearing the T0CS bit. In
Timer mode, the Timer0 module will increment every
instruction cycle (without prescaler). If the TMR0L 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 TMR0L register.
Counter mode is selected by setting the T0CS bit. In
Counter mode, Timer0 will increment, either on every
rising or falling edge of pin RA4/T0CKI. The incrementing
edge is determined by the Timer0 Source Edge
Select bit (T0SE). Clearing the T0SE bit selects the rising
edge. Restrictions on the external clock input are
discussed below.
When an external clock input is used for Timer0, it must
meet certain requirements. The requirements ensure
the external clock can be synchronized with the internal
phase clock (TOSC). Also, there is a delay in the actual
incrementing of Timer0 after synchronization.
10.2 Prescaler
An 8-bit counter is available as a prescaler for the Timer0
module. The prescaler is not readable or writable.
The PSA and T0PS2:T0PS0 bits determine the
prescaler assignment and prescale ratio.
Clearing bit PSA will assign the prescaler to the Timer0
module. When the prescaler is assigned to the Timer0
module, prescale values of 1:2, 1:4,..., 1:256 are
selectable.
When assigned to the Timer0 module, all instructions
writing to the TMR0L register (e.g., CLRF TMR0,
MOVWF TMR0, BSF TMR0, x....etc.) will clear the
prescaler count.
10.2.1 SWITCHING PRESCALER ASSIGNMENT
The prescaler assignment is fully under software control,
(i.e., it can be changed “on-the-fly” during program
execution).
10.3 Timer0 Interrupt
The TMR0 interrupt is generated when the TMR0 register
overflows from FFh to 00h in 8-bit mode, or FFFFh
to 0000h in 16-bit mode. This overflow sets the TMR0IF
bit. The interrupt can be masked by clearing the
TMR0IE bit. The TMR0IE bit must be cleared in software
by the Timer0 module Interrupt Service Routine
before re-enabling this interrupt. The TMR0 interrupt
cannot awaken the processor from SLEEP, since the
timer is shut-off during SLEEP.
10.4 16-Bit Mode Timer Reads and
Writes
TMR0H is not the high byte of the timer/counter in
16-bit mode, but is actually a buffered version of the
high byte of Timer0 (refer to Figure 10-2). The high byte
of the Timer0 counter/timer is not directly readable nor
writable. TMR0H is updated with the contents of the
high byte of Timer0 during a read of TMR0L. This provides
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.
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 all 16-bits of Timer0 to be
updated at once.
TABLE 10-1: REGISTERS ASSOCIATED WITH TIMER0
Note: Writing to TMR0L when the prescaler is
assigned to Timer0 will clear the prescaler
count, but will not change the prescaler
assignment.
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
TMR0L Timer0 Module Low Byte Register xxxx xxxx uuuu uuuu
TMR0H Timer0 Module High Byte Register 0000 0000 0000 0000
INTCON GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF 0000 000x 0000 000u
T0CON TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0 1111 1111 1111 1111
TRISA — PORTA Data Direction Register -111 1111 -111 1111
Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by Timer0.PIC18FXX2
DS39564C-page 106 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 107
PIC18FXX2
11.0 TIMER1 MODULE
The Timer1 module timer/counter has the following
features:
• 16-bit timer/counter
(two 8-bit registers; TMR1H and TMR1L)
• Readable and writable (both registers)
• Internal or external clock select
• Interrupt-on-overflow from FFFFh to 0000h
• RESET from CCP module special event trigger
Figure 11-1 is a simplified block diagram of the Timer1
module.
Register 11-1 details the Timer1 control register. This
register controls the Operating mode of the Timer1
module, and contains the Timer1 oscillator enable bit
(T1OSCEN). Timer1 can be enabled or disabled by
setting or clearing control bit TMR1ON (T1CON<0>).
REGISTER 11-1: T1CON: TIMER1 CONTROL REGISTER
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON
bit 7 bit 0
bit 7 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 = 1:8 Prescale value
10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value
bit 3 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 RC0/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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 108 © 2006 Microchip Technology Inc.
11.1 Timer1 Operation
Timer1 can operate in one of these modes:
• As a timer
• As a synchronous counter
• As an asynchronous counter
The Operating mode is determined by the clock select
bit, TMR1CS (T1CON<1>).
When TMR1CS = 0, Timer1 increments every instruction
cycle. When TMR1CS = 1, Timer1 increments on
every rising edge of the external clock input or the
Timer1 oscillator, if enabled.
When the Timer1 oscillator is enabled (T1OSCEN is
set), the RC1/T1OSI and RC0/T1OSO/T1CKI pins
become inputs. That is, the TRISC<1:0> value is
ignored, and the pins are read as ‘0’.
Timer1 also has an internal “RESET input”. This
RESET can be generated by the CCP module
(Section 14.0).
FIGURE 11-1: TIMER1 BLOCK DIAGRAM
FIGURE 11-2: TIMER1 BLOCK DIAGRAM: 16-BIT READ/WRITE MODE
TMR1H TMR1L
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0 SLEEP Input
FOSC/4
Internal
Clock
TMR1ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
TMR1IF
Overflow
TMR1
CLR
CCP Special Event Trigger
T1OSCEN
Enable
Oscillator(1)
T1OSC
Interrupt
Flag Bit
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
T1OSI
T1CKI/T1OSO
Timer 1
TMR1L
T1OSC
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
SLEEP Input
T1OSCEN
Enable
Oscillator(1)
TMR1IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR1ON
on/off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T13CKI/T1OSO
T1OSI
TMR1
Flag bit
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
High Byte
Data Bus<7:0>
8
TMR1H
8 8
8
Read TMR1L
Write TMR1L
CLR
CCP Special Event Trigger© 2006 Microchip Technology Inc. DS39564C-page 109
PIC18FXX2
11.2 Timer1 Oscillator
A crystal oscillator circuit is built-in between pins T1OSI
(input) and T1OSO (amplifier output). It is enabled by
setting control bit T1OSCEN (T1CON<3>). The oscillator
is a low power oscillator rated up to 200 kHz. It will
continue to run during SLEEP. It is primarily intended
for a 32 kHz crystal. Table 11-1 shows the capacitor
selection for the Timer1 oscillator.
The user must provide a software time delay to ensure
proper start-up of the Timer1 oscillator.
TABLE 11-1: CAPACITOR SELECTION FOR
THE ALTERNATE
OSCILLATOR
11.3 Timer1 Interrupt
The TMR1 Register pair (TMR1H:TMR1L) increments
from 0000h to FFFFh and rolls over to 0000h. The
TMR1 Interrupt, if enabled, is generated on overflow,
which is latched in interrupt flag bit TMR1IF (PIR1<0>).
This interrupt can be enabled/disabled by setting/
clearing TMR1 interrupt enable bit, TMR1IE (PIE1<0>).
11.4 Resetting Timer1 using a CCP
Trigger Output
If the CCP module is configured in Compare mode to
generate a “special event trigger” (CCP1M3:CCP1M0
= 1011), this signal will reset Timer1 and start an A/D
conversion (if the A/D module is enabled).
Timer1 must be configured for either Timer or Synchronized
Counter mode to take advantage of this feature.
If Timer1 is running in Asynchronous Counter mode,
this RESET operation may not work.
In the event that a write to Timer1 coincides with a
special event trigger from CCP1, the write will take
precedence.
In this mode of operation, the CCPR1H:CCPR1L registers
pair effectively becomes the period register for
Timer1.
11.5 Timer1 16-Bit Read/Write Mode
Timer1 can be configured for 16-bit reads and writes
(see Figure 11-2). When the RD16 control bit
(T1CON<7>) 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.
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.
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.
Osc Type Freq C1 C2
LP 32 kHz TBD(1) TBD(1)
Crystal to be Tested:
32.768 kHz Epson C-001R32.768K-A ± 20 PPM
Note 1: Microchip suggests 33 pF as a starting
point in validating the oscillator circuit.
2: Higher capacitance increases the stability
of the oscillator, but also increases the
start-up time.
3: Since each resonator/crystal has its own
characteristics, the user should consult
the resonator/crystal manufacturer
for appropriate values of external
components.
4: Capacitor values are for design guidance
only.
Note: The special event triggers from the CCP1
module will not set interrupt flag bit
TMR1IF (PIR1<0>). PIC18FXX2
DS39564C-page 110 © 2006 Microchip Technology Inc.
TABLE 11-2: REGISTERS ASSOCIATED WITH TIMER1 AS A TIMER/COUNTER
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
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
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 TMR1 Register xxxx xxxx uuuu uuuu
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0-00 0000 u-uu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Timer1 module.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits clear.© 2006 Microchip Technology Inc. DS39564C-page 111
PIC18FXX2
12.0 TIMER2 MODULE
The Timer2 module timer has the following features:
• 8-bit timer (TMR2 register)
• 8-bit period register (PR2)
• Readable and writable (both registers)
• Software programmable prescaler (1:1, 1:4, 1:16)
• Software programmable postscaler (1:1 to 1:16)
• Interrupt on TMR2 match of PR2
• SSP module optional use of TMR2 output to
generate clock shift
Timer2 has a control register shown in Register 12-1.
Timer2 can be shut-off by clearing control bit TMR2ON
(T2CON<2>) to minimize power consumption.
Figure 12-1 is a simplified block diagram of the Timer2
module. Register 12-1 shows the Timer2 control register.
The prescaler and postscaler selection of Timer2
are controlled by this register.
12.1 Timer2 Operation
Timer2 can be used as the PWM time-base for the
PWM mode of the CCP module. The TMR2 register is
readable and writable, and is cleared on any device
RESET. The input clock (FOSC/4) has a prescale option
of 1:1, 1:4 or 1:16, selected by control bits
T2CKPS1:T2CKPS0 (T2CON<1:0>). The match output
of TMR2 goes through a 4-bit postscaler (which
gives a 1:1 to 1:16 scaling inclusive) to generate a
TMR2 interrupt (latched in flag bit TMR2IF, (PIR1<1>)).
The prescaler and postscaler counters are cleared
when any of the following occurs:
• a write to the TMR2 register
• a write to the T2CON register
• any device RESET (Power-on Reset, MCLR
Reset, Watchdog Timer Reset, or Brown-out
Reset)
TMR2 is not cleared when T2CON is written.
REGISTER 12-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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 112 © 2006 Microchip Technology Inc.
12.2 Timer2 Interrupt
The Timer2 module has an 8-bit period register, PR2.
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 PR2 register is
initialized to FFh upon RESET.
12.3 Output of TMR2
The output of TMR2 (before the postscaler) is fed to the
Synchronous Serial Port module, which optionally uses
it to generate the shift clock.
FIGURE 12-1: TIMER2 BLOCK DIAGRAM
TABLE 12-1: REGISTERS ASSOCIATED WITH TIMER2 AS A TIMER/COUNTER
Comparator
TMR2 Sets Flag
TMR2
Output(1)
RESET
Postscaler
Prescaler
PR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
EQ
4
bit TMR2IF
Note 1: TMR2 register output can be software selected by the SSP Module as a baud clock.
TOUTPS3:TOUTPS0
T2CKPS1:T2CKPS0
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
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
TMR2 Timer2 Module Register 0000 0000 0000 0000
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
PR2 Timer2 Period Register 1111 1111 1111 1111
Legend: x = unknown, u = unchanged, - = unimplemented read as '0'. Shaded cells are not used by the Timer2 module.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits clear.© 2006 Microchip Technology Inc. DS39564C-page 113
PIC18FXX2
13.0 TIMER3 MODULE
The Timer3 module timer/counter has the following
features:
• 16-bit timer/counter
(two 8-bit registers; TMR3H and TMR3L)
• Readable and writable (both registers)
• Internal or external clock select
• Interrupt-on-overflow from FFFFh to 0000h
• RESET from CCP module trigger
Figure 13-1 is a simplified block diagram of the Timer3
module.
Register 13-1 shows the Timer3 control register. This
register controls the Operating mode of the Timer3
module and sets the CCP clock source.
Register 11-1 shows the Timer1 control register. This
register controls the Operating mode of the Timer1
module, as well as contains the Timer1 oscillator
enable bit (T1OSCEN), which can be a clock source for
Timer3.
REGISTER 13-1: T3CON: TIMER3 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
RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
bit 7 bit 0
bit 7 RD16: 16-bit Read/Write Mode Enable bit
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 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 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 Timer1 oscillator 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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 114 © 2006 Microchip Technology Inc.
13.1 Timer3 Operation
Timer3 can operate in one of these modes:
• As a timer
• As a synchronous counter
• As an asynchronous counter
The Operating mode is determined by the clock select
bit, TMR3CS (T3CON<1>).
When TMR3CS = 0, Timer3 increments every instruction
cycle. When TMR3CS = 1, Timer3 increments on
every rising edge of the Timer1 external clock input or
the Timer1 oscillator, if enabled.
When the Timer1 oscillator is enabled (T1OSCEN is
set), the RC1/T1OSI and RC0/T1OSO/T1CKI pins
become inputs. That is, the TRISC<1:0> value is
ignored, and the pins are read as ‘0’.
Timer3 also has an internal “RESET input”. This RESET
can be generated by the CCP module (Section 14.0).
FIGURE 13-1: TIMER3 BLOCK DIAGRAM
FIGURE 13-2: TIMER3 BLOCK DIAGRAM CONFIGURED IN 16-BIT READ/WRITE MODE
TMR3H TMR3L
T1OSC
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0
SLEEP Input
T1OSCEN
Enable
Oscillator(1)
TMR3IF
Overflow
Interrupt
FOSC/4
Internal
Clock
TMR3ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T1OSO/
T1OSI
Flag bit
(3)
Note 1: When enable bit T1OSCEN is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
T13CKI
CLR
CCP Special Trigger
T3CCPx
Timer3
TMR3L
T1OSC
T3SYNC
TMR3CS
T3CKPS1:T3CKPS0 SLEEP Input
T1OSCEN
Enable
Oscillator(1)
FOSC/4
Internal
Clock
TMR3ON
On/Off
Prescaler
1, 2, 4, 8
Synchronize
det
1
0
0
1
Synchronized
Clock Input
2
T1OSO/
T1OSI
TMR3
T13CKI
CLR
CCP Special Trigger
T3CCPx
To Timer1 Clock Input
Note 1: When the T1OSCEN bit is cleared, the inverter and feedback resistor are turned off. This eliminates power drain.
High Byte
Data Bus<7:0>
8
TMR3H
8 8
8
Read TMR3L
Write TMR3L
Set TMR3IF Flag bit
on Overflow© 2006 Microchip Technology Inc. DS39564C-page 115
PIC18FXX2
13.2 Timer1 Oscillator
The Timer1 oscillator may be used as the clock source
for Timer3. The Timer1 oscillator is enabled by setting
the T1OSCEN (T1CON<3>) bit. The oscillator is a low
power oscillator rated up to 200 KHz. See Section 11.0
for further details.
13.3 Timer3 Interrupt
The TMR3 Register pair (TMR3H:TMR3L) increments
from 0000h to FFFFh and rolls over to 0000h. The
TMR3 Interrupt, if enabled, is generated on overflow,
which is latched in interrupt flag bit, TMR3IF
(PIR2<1>). This interrupt can be enabled/disabled by
setting/clearing TMR3 interrupt enable bit, TMR3IE
(PIE2<1>).
13.4 Resetting Timer3 Using a CCP
Trigger Output
If the CCP module is configured in Compare mode to
generate a “special event trigger” (CCP1M3:CCP1M0
= 1011), this signal will reset Timer3.
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 CCP1, the write will take precedence. In this mode
of operation, the CCPR1H:CCPR1L registers pair
effectively becomes the period register for Timer3.
TABLE 13-1: REGISTERS ASSOCIATED WITH TIMER3 AS A TIMER/COUNTER
Note: The special event triggers from the CCP
module will not set interrupt flag bit,
TMR3IF (PIR1<0>).
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
PIR2 — — — EEIF BCLIF LVDIF TMR3IF CCP2IF ---0 0000 ---0 0000
PIE2 — — — EEIE BCLIE LVDIE TMR3IE CCP2IE ---0 0000 ---0 0000
IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 ---1 1111
TMR3L Holding Register for the Least Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
TMR3H Holding Register for the Most Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0-00 0000 u-uu uuuu
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0000 0000 uuuu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Timer1 module.PIC18FXX2
DS39564C-page 116 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 117
PIC18FXX2
14.0 CAPTURE/COMPARE/PWM
(CCP) MODULES
Each CCP (Capture/Compare/PWM) module contains
a 16-bit register which can operate as a 16-bit Capture
register, as a 16-bit Compare register or as a PWM
Master/Slave Duty Cycle register. Table 14-1 shows
the timer resources of the CCP Module modes.
The operation of CCP1 is identical to that of CCP2, with
the exception of the special event trigger. Therefore,
operation of a CCP module in the following sections is
described with respect to CCP1.
Table 14-2 shows the interaction of the CCP modules.
REGISTER 14-1: CCP1CON REGISTER/CCP2CON REGISTER
U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— — DCxB1 DCxB0 CCPxM3 CCPxM2 CCPxM1 CCPxM0
bit 7 bit 0
bit 7-6 Unimplemented: Read as '0'
bit 5-4 DCxB1:DCxB0: PWM Duty Cycle bit1 and bit0
Capture mode:
Unused
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
(DCx9:DCx2) of the duty cycle are found in CCPRxL.
bit 3-0 CCPxM3:CCPxM0: CCPx Mode Select bits
0000 = Capture/Compare/PWM disabled (resets CCPx module)
0001 = Reserved
0010 = Compare mode, toggle output on match (CCPxIF bit is set)
0011 = Reserved
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode,
Initialize CCP pin Low, on compare match force CCP pin High (CCPIF bit is set)
1001 = Compare mode,
Initialize CCP pin High, on compare match force CCP pin Low (CCPIF bit is set)
1010 = Compare mode,
Generate software interrupt on compare match (CCPIF bit is set, CCP pin is unaffected)
1011 = Compare mode,
Trigger special event (CCPIF bit is set)
11xx = PWM mode
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 118 © 2006 Microchip Technology Inc.
14.1 CCP1 Module
Capture/Compare/PWM Register 1 (CCPR1) is comprised
of two 8-bit registers: CCPR1L (low byte) and
CCPR1H (high byte). The CCP1CON register controls
the operation of CCP1. All are readable and writable.
TABLE 14-1: CCP MODE - TIMER
RESOURCE
14.2 CCP2 Module
Capture/Compare/PWM Register2 (CCPR2) is comprised
of two 8-bit registers: CCPR2L (low byte) and
CCPR2H (high byte). The CCP2CON register controls
the operation of CCP2. All are readable and writable.
TABLE 14-2: INTERACTION OF TWO CCP MODULES
CCP Mode Timer Resource
Capture
Compare
PWM
Timer1 or Timer3
Timer1 or Timer3
Timer2
CCPx Mode CCPy Mode Interaction
Capture Capture TMR1 or TMR3 time-base. Time-base can be different for each CCP.
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© 2006 Microchip Technology Inc. DS39564C-page 119
PIC18FXX2
14.3 Capture Mode
In Capture mode, CCPR1H:CCPR1L captures the
16-bit value of the TMR1 or TMR3 registers when an
event occurs on pin RC2/CCP1. An event is defined as
one of the following:
• every falling edge
• every rising edge
• every 4th rising edge
• every 16th rising edge
The event is selected by control bits CCP1M3:CCP1M0
(CCP1CON<3:0>). When a capture is made, the interrupt
request flag bit CCP1IF (PIR1<2>) is set; it must be
cleared in software. If another capture occurs before the
value in register CCPR1 is read, the old captured value
is overwritten by the new captured value.
14.3.1 CCP PIN CONFIGURATION
In Capture mode, the RC2/CCP1 pin should be
configured as an input by setting the TRISC<2> bit.
14.3.2 TIMER1/TIMER3 MODE SELECTION
The timers that are to be used with the capture feature
(either Timer1 and/or Timer3) must be running in Timer
mode or Synchronized Counter mode. In Asynchronous
Counter mode, the capture operation may not
work. The timer to be used with each CCP module is
selected in the T3CON register.
14.3.3 SOFTWARE INTERRUPT
When the Capture mode is changed, a false capture
interrupt may be generated. The user should keep bit
CCP1IE (PIE1<2>) clear to avoid false interrupts and
should clear the flag bit, CCP1IF, following any such
change in Operating mode.
14.3.4 CCP PRESCALER
There are four prescaler settings, specified by bits
CCP1M3:CCP1M0. Whenever the CCP module is
turned off or the CCP module is not in Capture mode,
the prescaler counter is cleared. This means that any
RESET will clear the prescaler counter.
Switching from one capture prescaler to another may
generate an interrupt. Also, the prescaler counter will
not be cleared, therefore, the first capture may be from
a non-zero prescaler. Example 14-1 shows the recommended
method for switching between capture prescalers.
This example also clears the prescaler counter
and will not generate the “false” interrupt.
EXAMPLE 14-1: CHANGING BETWEEN
CAPTURE PRESCALERS
FIGURE 14-1: CAPTURE MODE OPERATION BLOCK DIAGRAM
Note: If the RC2/CCP1 is configured as an output,
a write to the port can cause a capture
condition.
CLRF CCP1CON, F ; Turn CCP module off
MOVLW NEW_CAPT_PS ; Load WREG with the
; new prescaler mode
; value and CCP ON
MOVWF CCP1CON ; Load CCP1CON with
; this value
CCPR1H CCPR1L
TMR1H TMR1L
Set Flag bit CCP1IF
TMR3
Enable
Q’s
CCP1CON<3:0>
CCP1 pin
Prescaler
÷ 1, 4, 16
and
Edge Detect
TMR3H TMR3L
TMR1
Enable
T3CCP2
T3CCP2
CCPR2H CCPR2L
TMR1H TMR1L
Set Flag bit CCP2IF
TMR3
Enable
Q’s
CCP2CON<3:0>
CCP2 pin
Prescaler
÷ 1, 4, 16
and
Edge Detect
TMR3H TMR3L
TMR1
Enable
T3CCP2
T3CCP1
T3CCP2
T3CCP1PIC18FXX2
DS39564C-page 120 © 2006 Microchip Technology Inc.
14.4 Compare Mode
In Compare mode, the 16-bit CCPR1 (CCPR2) register
value is constantly compared against either the TMR1
register pair value, or the TMR3 register pair value.
When a match occurs, the RC2/CCP1 (RC1/CCP2) pin
is:
• driven High
• driven Low
• toggle output (High to Low or Low to High)
• remains unchanged
The action on the pin is based on the value of control
bits CCP1M3:CCP1M0 (CCP2M3:CCP2M0). At the
same time, interrupt flag bit CCP1IF (CCP2IF) is set.
14.4.1 CCP PIN CONFIGURATION
The user must configure the CCPx pin as an output by
clearing the appropriate TRISC bit.
14.4.2 TIMER1/TIMER3 MODE SELECTION
Timer1 and/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.
14.4.3 SOFTWARE INTERRUPT MODE
When generate software interrupt is chosen, the CCP1
pin is not affected. Only a CCP interrupt is generated (if
enabled).
14.4.4 SPECIAL EVENT TRIGGER
In this mode, an internal hardware trigger is generated,
which may be used to initiate an action.
The special event trigger output of CCP1 resets the
TMR1 register pair. This allows the CCPR1 register to
effectively be a 16-bit programmable period register for
Timer1.
The special trigger output of CCPx resets either the
TMR1 or TMR3 register pair. Additionally, the CCP2
Special Event Trigger will start an A/D conversion if the
A/D module is enabled.
FIGURE 14-2: COMPARE MODE OPERATION BLOCK DIAGRAM
Note: Clearing the CCP1CON register will force
the RC2/CCP1 compare output latch to the
default low level. This is not the PORTC
I/O data latch.
Note: The special event trigger from the CCP2
module will not set the Timer1 or Timer3
interrupt flag bits.
CCPR1H CCPR1L
TMR1H TMR1L
Comparator
Q S
R
Output
Logic
Special Event Trigger
Set Flag bit CCP1IF
RC2/CCP1 pin Match
TRISC<2>
CCP1CON<3:0>
Mode Select
Output Enable
Special Event Trigger will:
Reset Timer1 or Timer3, but not set Timer1 or Timer3 interrupt flag bit,
and set bit GO/DONE (ADCON0<2>)
which starts an A/D conversion (CCP2 only)
TMR3H TMR3L
T3CCP2
CCPR2H CCPR2L
Comparator
0 1
T3CCP2
T3CCP1
Q S
R
Output
Logic
Special Event Trigger
Set Flag bit CCP2IF
RC1/CCP2 pin Match
TRISC<1>
CCP2CON<3:0>
Mode Select
Output Enable
0 1© 2006 Microchip Technology Inc. DS39564C-page 121
PIC18FXX2
TABLE 14-3: REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, TIMER1 AND TIMER3
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
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 TMR1 Register xxxx xxxx uuuu uuuu
T1CON RD16 — T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON 0-00 0000 u-uu uuuu
CCPR1L Capture/Compare/PWM Register1 (LSB) xxxx xxxx uuuu uuuu
CCPR1H Capture/Compare/PWM Register1 (MSB) xxxx xxxx uuuu uuuu
CCP1CON — — DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000
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 --00 0000
PIR2 — — — EEIE BCLIF LVDIF TMR3IF CCP2IF ---0 0000 ---0 0000
PIE2 — — — EEIF BCLIE LVDIE TMR3IE CCP2IE ---0 0000 ---0 0000
IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 ---1 1111
TMR3L Holding Register for the Least Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
TMR3H Holding Register for the Most Significant Byte of the 16-bit TMR3 Register xxxx xxxx uuuu uuuu
T3CON RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON 0000 0000 uuuu uuuu
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by Capture and Timer1.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2x2 devices; always maintain these bits clear.PIC18FXX2
DS39564C-page 122 © 2006 Microchip Technology Inc.
14.5 PWM Mode
In Pulse Width Modulation (PWM) mode, the CCP1 pin
produces up to a 10-bit resolution PWM output. Since
the CCP1 pin is multiplexed with the PORTC data latch,
the TRISC<2> bit must be cleared to make the CCP1
pin an output.
Figure 14-3 shows a simplified block diagram of the
CCP module in PWM mode.
For a step-by-step procedure on how to set up the CCP
module for PWM operation, see Section 14.5.3.
FIGURE 14-3: SIMPLIFIED PWM BLOCK
DIAGRAM
A PWM output (Figure 14-4) has a time-base (period)
and a time that the output stays high (duty cycle). The
frequency of the PWM is the inverse of the period
(1/period).
FIGURE 14-4: PWM OUTPUT
14.5.1 PWM PERIOD
The PWM period is specified by writing to the PR2
register. The PWM period can be calculated using the
following formula:
PWM period = (PR2) + 1] • 4 • TOSC •
(TMR2 prescale value)
PWM frequency is defined as 1 / [PWM period].
When TMR2 is equal to PR2, the following three events
occur on the next increment cycle:
• TMR2 is cleared
• The CCP1 pin is set (exception: if PWM duty
cycle = 0%, the CCP1 pin will not be set)
• The PWM duty cycle is latched from CCPR1L into
CCPR1H
14.5.2 PWM DUTY CYCLE
The PWM duty cycle is specified by writing to the
CCPR1L register and to the CCP1CON<5:4> bits. Up
to 10-bit resolution is available. The CCPR1L contains
the eight MSbs and the CCP1CON<5:4> contains the
two LSbs. This 10-bit value is represented by
CCPR1L:CCP1CON<5:4>. The following equation is
used to calculate the PWM duty cycle in time:
PWM duty cycle = (CCPR1L:CCP1CON<5:4>) •
TOSC • (TMR2 prescale value)
CCPR1L and CCP1CON<5:4> can be written to at any
time, but the duty cycle value is not latched into
CCPR1H until after a match between PR2 and TMR2
occurs (i.e., the period is complete). In PWM mode,
CCPR1H is a read only register.
The CCPR1H register and a 2-bit internal latch are
used to double buffer the PWM duty cycle. This double
buffering is essential for glitchless PWM operation.
When the CCPR1H and 2-bit latch match TMR2 concatenated
with an internal 2-bit Q clock or 2 bits of the
TMR2 prescaler, the CCP1 pin is cleared.
The maximum PWM resolution (bits) for a given PWM
frequency is given by the equation:
Note: Clearing the CCP1CON register will force
the CCP1 PWM output latch to the default
low level. This is not the PORTC I/O data
latch.
CCPR1L
CCPR1H (Slave)
Comparator
TMR2
Comparator
PR2
(Note 1)
R Q
S
Duty Cycle Registers CCP1CON<5:4>
Clear Timer,
CCP1 pin and
latch D.C.
TRISC<2>
RC2/CCP1
Note: 8-bit timer is concatenated with 2-bit internal Q clock or 2
bits of the prescaler to create 10-bit time-base.
Period
Duty Cycle
TMR2 = PR2
TMR2 = Duty Cycle
TMR2 = PR2
Note: The Timer2 postscaler (see Section 12.0)
is not used in the determination of the
PWM frequency. The postscaler could be
used to have a servo update rate at a
different frequency than the PWM output.
Note: If the PWM duty cycle value is longer than
the PWM period, the CCP1 pin will not be
cleared.
FOSC
FPWM
--------------- ⎝ ⎠ ⎛ ⎞ log
log( ) 2 PWM Resolution (max) = -----------------------------bits© 2006 Microchip Technology Inc. DS39564C-page 123
PIC18FXX2
14.5.3 SETUP FOR PWM OPERATION
The following steps should be taken when configuring
the CCP module for PWM operation:
1. Set the PWM period by writing to the PR2 register.
2. Set the PWM duty cycle by writing to the
CCPR1L register and CCP1CON<5:4> bits.
3. Make the CCP1 pin an output by clearing the
TRISC<2> bit.
4. Set the TMR2 prescale value and enable Timer2
by writing to T2CON.
5. Configure the CCP1 module for PWM operation.
TABLE 14-4: EXAMPLE PWM FREQUENCIES AND RESOLUTIONS AT 40 MHz
TABLE 14-5: REGISTERS ASSOCIATED WITH PWM AND TIMER2
PWM Frequency 2.44 kHz 9.77 kHz 39.06 kHz 156.25 kHz 312.50 kHz 416.67 kHz
Timer Prescaler (1, 4, 16) 16 4 1 1 1 1
PR2 Value 0xFF 0xFF 0xFF 0x3F 0x1F 0x17
Maximum Resolution (bits) 14 12 10 8 7 6.58
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
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
TMR2 Timer2 Module Register 0000 0000 0000 0000
PR2 Timer2 Module Period Register 1111 1111 1111 1111
T2CON — TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 -000 0000 -000 0000
CCPR1L Capture/Compare/PWM Register1 (LSB) xxxx xxxx uuuu uuuu
CCPR1H Capture/Compare/PWM Register1 (MSB) xxxx xxxx uuuu uuuu
CCP1CON — — DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0 --00 0000 --00 0000
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 --00 0000
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 PIC18F2X2 devices; always maintain these bits clear.PIC18FXX2
DS39564C-page 124 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 125
PIC18FXX2
15.0 MASTER SYNCHRONOUS
SERIAL PORT (MSSP)
MODULE
15.1 Master SSP (MSSP) Module
Overview
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 (I2C)
- Full Master mode
- Slave mode (with general address call)
The I2C interface supports the following modes in
hardware:
• Master mode
• Multi-Master mode
• Slave mode
15.2 Control Registers
The MSSP module has three associated registers.
These include a status register (SSPSTAT) and two
control registers (SSPCON1 and SSPCON2). The use
of these registers and their individual configuration bits
differ significantly, depending on whether the MSSP
module is operated in SPI or I2C mode.
Additional details are provided under the individual
sections.
15.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) - RC5/SDO
• Serial Data In (SDI) - RC4/SDI/SDA
• Serial Clock (SCK) - RC3/SCK/SCL/LVDIN
Additionally, a fourth pin may be used when in a Slave
mode of operation:
• Slave Select (SS) - RA5/SS/AN4
Figure 15-1 shows the block diagram of the MSSP
module when operating in SPI mode.
FIGURE 15-1: MSSP BLOCK DIAGRAM
(SPI MODE)
Read Write
Internal
Data Bus
SSPSR reg
SSPM3:SSPM0
bit0 shift
clock
SS Control
Enable
Edge
Select
Clock Select
TMR2 output
Prescaler TOSC
4, 16, 64
2
Edge
Select
2
4
Data to TX/RX in SSPSR
TRIS bit
2
SMP:CKE
RC5/SDO
( )
SSPBUF reg
RC4/SDI/SDA
RA5/SS/AN4
RC3/SCK/
SCL/LVDINPIC18FXX2
DS39564C-page 126 © 2006 Microchip Technology Inc.
15.3.1 REGISTERS
The MSSP module has four registers for SPI mode
operation. These are:
• MSSP Control Register1 (SSPCON1)
• MSSP Status Register (SSPSTAT)
• Serial Receive/Transmit Buffer (SSPBUF)
• MSSP Shift Register (SSPSR) - Not directly
accessible
SSPCON1 and SSPSTAT are the control and status
registers in SPI mode operation. The SSPCON1 register
is readable and writable. The lower 6 bits of the
SSPSTAT are read only. The upper two bits of the
SSPSTAT are read/write.
SSPSR is the shift register used for shifting data in or
out. SSPBUF is the buffer register to which data bytes
are written to or read from.
In receive operations, SSPSR and SSPBUF together
create a double buffered receiver. When SSPSR
receives a complete byte, it is transferred to SSPBUF
and the SSPIF interrupt is set.
During transmission, the SSPBUF is not double buffered.
A write to SSPBUF will write to both SSPBUF and
SSPSR.
REGISTER 15-1: SSPSTAT: MSSP STATUS REGISTER (SPI MODE)
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE D/A P S R/W UA BF
bit 7 bit 0
bit 7 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
bit 6 CKE: SPI Clock Edge Select
When CKP = 0:
1 = Data transmitted on rising edge of SCK
0 = Data transmitted on falling edge of SCK
When 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
Used in I2C mode only
bit 4 P: STOP bit
Used in I2C mode only. This bit is cleared when the MSSP module is disabled, SSPEN is
cleared.
bit 3 S: START bit
Used in I2C mode only
bit 2 R/W: Read/Write bit information
Used in I2C mode only
bit 1 UA: Update Address
Used in I2C mode only
bit 0 BF: Buffer Full Status bit (Receive mode only)
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 127
PIC18FXX2
REGISTER 15-2: SSPCON1: MSSP CONTROL REGISTER1 (SPI MODE)
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 0
bit 7 WCOL: Write Collision Detect bit (Transmit mode only)
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
SPI Slave 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.The user
must read the SSPBUF, even if only transmitting data, to avoid setting overflow
(must be cleared in software).
0 = No overflow
Note: In Master mode, the overflow bit is not set since each new reception (and
transmission) is initiated by writing to the SSPBUF register.
bit 5 SSPEN: Synchronous Serial Port Enable bit
1 = Enables serial port and configures SCK, SDO, SDI, and SS as serial port pins
0 = Disables serial port and configures these pins as I/O port pins
Note: When enabled, these pins must be properly configured as input or output.
bit 4 CKP: Clock Polarity Select bit
1 = IDLE state for clock is a high level
0 = IDLE state for clock is a low level
bit 3-0 SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
0101 = SPI Slave mode, clock = SCK pin, SS pin control disabled, SS can be used as I/O pin
0100 = SPI Slave mode, clock = SCK pin, SS pin control enabled
0011 = SPI Master mode, clock = TMR2 output/2
0010 = SPI Master mode, clock = FOSC/64
0001 = SPI Master mode, clock = FOSC/16
0000 = SPI Master mode, clock = FOSC/4
Note: Bit combinations not specifically listed here are either reserved, or implemented in
I
2C mode only.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 128 © 2006 Microchip Technology Inc.
15.3.2 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)
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<0>), 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<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 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 15-1 shows the loading of the
SSPBUF (SSPSR) for data transmission.
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.
EXAMPLE 15-1: LOADING THE SSPBUF (SSPSR) REGISTER
LOOP BTFSS SSPSTAT, BF ;Has data been received(transmit complete)?
BRA LOOP ;No
MOVF SSPBUF, W ;WREG reg = contents of SSPBUF
MOVWF RXDATA ;Save in user RAM, if data is meaningful
MOVF TXDATA, W ;W reg = contents of TXDATA
MOVWF SSPBUF ;New data to xmit © 2006 Microchip Technology Inc. DS39564C-page 129
PIC18FXX2
15.3.3 ENABLING SPI I/O
To enable the serial port, SSP Enable bit, SSPEN
(SSPCON1<5>), 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 TRISC<5> bit cleared
• SCK (Master mode) must have TRISC<3> bit
cleared
• SCK (Slave mode) must have TRISC<3> bit set
• SS must have TRISC<4> 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.
15.3.4 TYPICAL CONNECTION
Figure 15-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 opposite
edge of the clock. Both processors should be programmed
to the 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 15-2: SPI MASTER/SLAVE CONNECTION
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDO
SDI
PROCESSOR 1
SCK
SPI Master SSPM3:SSPM0 = 00xxb
Serial Input Buffer
(SSPBUF)
Shift Register
(SSPSR)
MSb LSb
SDI
SDO
PROCESSOR 2
SCK
SPI Slave SSPM3:SSPM0 = 010xb
Serial ClockPIC18FXX2
DS39564C-page 130 © 2006 Microchip Technology Inc.
15.3.5 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 15-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
the CKP bit (SSPCON1<4>). This then, would
give waveforms for SPI communication as shown in
Figure 15-3, Figure 15-5, and Figure 15-6, 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 TCY)
• FOSC/16 (or 4 • TCY)
• FOSC/64 (or 16 • TCY)
• Timer2 output/2
This allows a maximum data rate (at 40 MHz) of
10.00 Mbps.
Figure 15-3 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 15-3: SPI MODE WAVEFORM (MASTER MODE)
SCK
(CKP = 0
SCK
(CKP = 1
SCK
(CKP = 0
SCK
(CKP = 1
4 Clock
Modes
Input
Sample
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
bit7 bit0
SDI
SSPIF
(SMP = 1)
(SMP = 0)
(SMP = 1)
CKE = 1)
CKE = 0)
CKE = 1)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
(CKE = 0)
(CKE = 1)
Next Q4 cycle
after Q2↓© 2006 Microchip Technology Inc. DS39564C-page 131
PIC18FXX2
15.3.6 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.
15.3.7 SLAVE SELECT
SYNCHRONIZATION
The SS pin allows a Synchronous Slave mode. The
SPI must be in Slave mode with SS pin control enabled
(SSPCON1<3:0> = 04h). The pin must not be driven
low for the SS pin to function as an input. The Data
Latch must be high. 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 module resets, the bit counter is forced
to 0. This can be done by either 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.
FIGURE 15-4: SLAVE SYNCHRONIZATION WAVEFORM
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.
2: If the SPI is used in Slave mode with CKE
set, then the SS pin control must be
enabled.
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit7
SDO bit7 bit6 bit7
SSPIF
Interrupt
(SMP = 0)
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
bit0
bit7
bit0
Next Q4 cycle
after Q2↓PIC18FXX2
DS39564C-page 132 © 2006 Microchip Technology Inc.
FIGURE 15-5: SPI MODE WAVEFORM (SLAVE MODE WITH CKE = 0)
FIGURE 15-6: SPI MODE WAVEFORM (SLAVE MODE WITH CKE = 1)
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
SSPIF
Interrupt
(SMP = 0)
CKE = 0)
CKE = 0)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
Optional
Next Q4 cycle
after Q2↓
SCK
(CKP = 1
SCK
(CKP = 0
Input
Sample
SDI
bit7 bit0
SDO bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
SSPIF
Interrupt
(SMP = 0)
CKE = 1)
CKE = 1)
(SMP = 0)
Write to
SSPBUF
SSPSR to
SSPBUF
SS
Flag
Not Optional
Next Q4 cycle
after Q2↓© 2006 Microchip Technology Inc. DS39564C-page 133
PIC18FXX2
15.3.8 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 MSSP interrupt
flag bit will be set and if enabled, will wake the device
from SLEEP.
15.3.9 EFFECTS OF A RESET
A RESET disables the MSSP module and terminates
the current transfer.
15.3.10 BUS MODE COMPATIBILITY
Table 15-1 shows the compatibility between the
standard SPI modes and the states the CKP and CKE
control bits.
TABLE 15-1: SPI BUS MODES
There is also a SMP bit which controls when the data is
sampled.
TABLE 15-2: REGISTERS ASSOCIATED WITH SPI OPERATION
Standard SPI Mode
Terminology
Control Bits State
CKP CKE
0, 0 0 1
0, 1 0 0
1, 0 1 1
1, 1 1 0
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
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
SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx uuuu uuuu
SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 0000 0000 0000 0000
TRISA — PORTA Data Direction Register -111 1111 -111 1111
SSPSTAT SMP CKE D/A 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 SPI mode.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18C2X2 devices; always maintain these bits clear.PIC18FXX2
DS39564C-page 134 © 2006 Microchip Technology Inc.
15.4 I2C Mode
The MSSP module in I2C 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.
Two pins are used for data transfer:
• Serial clock (SCL) - RC3/SCK/SCL
• Serial data (SDA) - RC4/SDI/SDA
The user must configure these pins as inputs or outputs
through the TRISC<4:3> bits.
FIGURE 15-7: MSSP BLOCK DIAGRAM
(I2C MODE)
15.4.1 REGISTERS
The MSSP module has six registers for I2C operation.
These are:
• 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)
SSPCON, SSPCON2 and SSPSTAT are the control
and status registers in I2C mode operation. The
SSPCON and SSPCON2 registers are readable and
writable. The lower 6 bits of the SSPSTAT are read
only. The upper two bits of the SSPSTAT are read/
write.
SSPSR is the shift register used for shifting data in or
out. SSPBUF is the buffer register to which data bytes
are written to or read from.
SSPADD register holds the slave device address
when the SSP is configured in I2C Slave mode. When
the SSP is configured in Master mode, the lower
seven bits of SSPADD act as the baud rate generator
reload value.
In receive operations, SSPSR and SSPBUF together,
create a double buffered receiver. When SSPSR
receives a complete byte, it is transferred to SSPBUF
and the SSPIF interrupt is set.
During transmission, the SSPBUF is not double buffered.
A write to SSPBUF will write to both SSPBUF and
SSPSR.
Read Write
SSPSR reg
Match Detect
SSPADD reg
START and
STOP bit Detect
SSPBUF reg
Internal
Data Bus
Addr Match
Set, Reset
S, P bits
(SSPSTAT reg)
RC3/SCK/SCL
RC4/
Shift
Clock
MSb
SDI/
LSb
SDA© 2006 Microchip Technology Inc. DS39564C-page 135
PIC18FXX2
REGISTER 15-3: SSPSTAT: MSSP STATUS REGISTER (I2C MODE)
R/W-0 R/W-0 R-0 R-0 R-0 R-0 R-0 R-0
SMP CKE D/A P S R/W UA BF
bit 7 bit 0
bit 7 SMP: Slew Rate Control bit
In 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: SMBus Select bit
In Master or Slave mode:
1 = Enable SMBus specific inputs
0 = Disable SMBus specific inputs
bit 5 D/A: Data/Address bit
In Master mode:
Reserved
In Slave mode:
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
1 = Indicates that a STOP bit has been detected last
0 = STOP bit was not detected last
Note: This bit is cleared on RESET and when SSPEN is cleared.
bit 3 S: START bit
1 = Indicates that a start bit has been detected last
0 = START bit was not detected last
Note: This bit is cleared on RESET and when SSPEN is cleared.
bit 2 R/W: Read/Write bit Information (I2C mode only)
In Slave mode:
1 = Read
0 = Write
Note: 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 Master mode:
1 = Transmit is in progress
0 = Transmit is not in progress
Note: ORing 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 Slave mode only)
1 = Indicates that the user needs to update the address in the SSPADD register
0 = Address does not need to be updated
bit 0 BF: Buffer Full Status bit
In Transmit mode:
1 = Receive complete, SSPBUF is full
0 = Receive not complete, SSPBUF is empty
In Receive mode:
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 W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 136 © 2006 Microchip Technology Inc.
REGISTER 15-4: SSPCON1: MSSP CONTROL REGISTER1 (I2C MODE)
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 0
bit 7 WCOL: Write Collision Detect bit
In Master Transmit mode:
1 = A write to the SSPBUF register was attempted while the I2C conditions were not valid for
a transmission to be started (must be cleared in software)
0 = No collision
In Slave Transmit mode:
1 = The SSPBUF register is written while it is still transmitting the previous word (must be
cleared in software)
0 = No collision
In Receive mode (Master or Slave modes):
This is a “don’t care” bit
bit 6 SSPOV: Receive Overflow Indicator bit
In Receive mode:
1 = A byte is received while the SSPBUF register is still holding the previous byte (must
be cleared in software)
0 = No overflow
In Transmit mode:
This is a “don’t care” bit in Transmit mode
bit 5 SSPEN: Synchronous Serial Port Enable bit
1 = Enables the serial port and configures the SDA and SCL pins as the serial port pins
0 = Disables serial port and configures these pins as I/O port pins
Note: When enabled, the SDA and SCL pins must be properly configured as input or output.
bit 4 CKP: SCK Release Control bit
In Slave mode:
1 = Release clock
0 = Holds clock low (clock stretch), used to ensure data setup time
In Master mode:
Unused in this mode
bit 3-0 SSPM3:SSPM0: Synchronous Serial Port Mode Select bits
1111 = I2C Slave mode, 10-bit address with START and STOP bit interrupts enabled
1110 = I2C Slave mode, 7-bit address with START and STOP bit interrupts enabled
1011 = I2C Firmware Controlled Master mode (Slave IDLE)
1000 = I2C Master mode, clock = FOSC / (4 * (SSPADD+1))
0111 = I2C Slave mode, 10-bit address
0110 = I2C Slave mode, 7-bit address
Note: Bit combinations not specifically listed here are either reserved, or implemented in
SPI mode only.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 137
PIC18FXX2
REGISTER 15-5: SSPCON2: MSSP CONTROL REGISTER 2 (I2C MODE)
R/W-0 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 SEN
bit 7 bit 0
bit 7 GCEN: General Call Enable bit (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 (Master Transmit mode only)
1 = Acknowledge was not received from slave
0 = Acknowledge was received from slave
bit 5 ACKDT: Acknowledge Data bit (Master Receive mode only)
1 = Not Acknowledge
0 = Acknowledge
Note: Value that will be transmitted when the user initiates an Acknowledge sequence at
the end of a receive.
bit 4 ACKEN: Acknowledge Sequence Enable bit (Master Receive mode only)
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 (Master mode only)
1 = Enables Receive mode for I2C
0 = Receive IDLE
bit 2 PEN: STOP Condition Enable bit (Master mode only)
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 (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/Stretch Enabled bit
In Master mode:
1 = Initiate START condition on SDA and SCL pins. Automatically cleared by hardware.
0 = START condition IDLE
In Slave mode:
1 = Clock stretching is enabled for both Slave Transmit and Slave Receive (stretch enabled)
0 = Clock stretching is enabled for slave transmit only (Legacy mode)
Note: For bits ACKEN, RCEN, PEN, RSEN, SEN: If the I2C module is not in the IDLE
mode, this bit may not be set (no spooling) and the SSPBUF may not be written (or
writes to the SSPBUF are disabled).
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 138 © 2006 Microchip Technology Inc.
15.4.2 OPERATION
The MSSP module functions are enabled by setting
MSSP Enable bit, SSPEN (SSPCON<5>).
The SSPCON1 register allows control of the I2C operation.
Four mode selection bits (SSPCON<3:0>) allow
one of the following I2C modes to be selected:
• I2C Master mode, clock = OSC/4 (SSPADD +1)
• I2C Slave mode (7-bit address)
• I2C Slave mode (10-bit address)
• 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
• I2C Firmware controlled master operation, slave
is IDLE
Selection of any I2C mode, with the SSPEN bit set,
forces the SCL and SDA pins to be open drain, provided
these pins are programmed to inputs by setting
the appropriate TRISC bits. To guarantee proper operation
of the module, pull-up resistors must be provided
externally to the SCL and SDA pins.
15.4.3 SLAVE MODE
In Slave mode, the SCL and SDA pins must be configured
as inputs (TRISC<4:3> set). The MSSP module
will override the input state with the output data when
required (slave-transmitter).
The I2C Slave mode hardware will always generate an
interrupt on an address match. Through the mode
select bits, the user can also choose to interrupt on
START and STOP bits
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
load the SSPBUF register with the received value
currently in the SSPSR register.
Any combination of the following conditions will cause
the MSSP module not to give this ACK pulse:
• The buffer full bit BF (SSPSTAT<0>) was set
before the transfer was received.
• The overflow bit SSPOV (SSPCON<6>) was set
before the transfer was received.
In this case, the SSPSR register value is not loaded
into the SSPBUF, but bit SSPIF (PIR1<3>) is set. 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 for proper operation. The high and low times of the
I
2C specification, as well as the requirement of the
MSSP module, are shown in timing parameter 100 and
parameter 101.
15.4.3.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. 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:
1. The SSPSR register value is loaded into the
SSPBUF register.
2. The buffer full bit BF is set.
3. An ACK pulse is generated.
4. MSSP interrupt flag bit, SSPIF (PIR1<3>) 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. Bit R/W (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
‘11110 A9 A8 0’, where ‘A9’ and ‘A8’ are the two
MSbs of the address. The sequence of events for 10-bit
address is as follows, with steps 7 through 9 for the
slave-transmitter:
1. Receive first (high) byte of Address (bits SSPIF,
BF and bit UA (SSPSTAT<1>) are set).
2. Update the SSPADD register with second (low)
byte of Address (clears bit UA and releases the
SCL line).
3. Read the SSPBUF register (clears bit BF) and
clear flag bit SSPIF.
4. Receive second (low) byte of Address (bits
SSPIF, BF, and UA are set).
5. Update the SSPADD register with the first (high)
byte of Address. If match releases SCL line, this
will clear bit UA.
6. Read the SSPBUF register (clears bit BF) and
clear flag bit SSPIF.
7. Receive Repeated START condition.
8. Receive first (high) byte of Address (bits SSPIF
and BF are set).
9. Read the SSPBUF register (clears bit BF) and
clear flag bit SSPIF.© 2006 Microchip Technology Inc. DS39564C-page 139
PIC18FXX2
15.4.3.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 and the SDA line is held low
(ACK).
When the address byte overflow condition exists, then
the no Acknowledge (ACK) pulse is given. An overflow
condition is defined as either bit BF (SSPSTAT<0>) is
set, or bit SSPOV (SSPCON1<6>) is set.
An MSSP interrupt is generated for each data transfer
byte. Flag bit SSPIF (PIR1<3>) must be cleared in software.
The SSPSTAT register is used to determine the
status of the byte.
If SEN is enabled (SSPCON1<0>=1), RC3/SCK/SCL
will be held low (clock stretch) following each data transfer.
The clock must be released by setting bit CKP
(SSPCON<4>). See Section 15.4.4 (“Clock Stretching”),
for more detail.
15.4.3.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 pin RC3/SCK/SCL is held
low, regardless of SEN (see “Clock Stretching”,
Section 15.4.4, for more detail). By stretching the clock,
the master will be unable to assert another clock pulse
until the slave is done preparing the transmit data.The
transmit data must be loaded into the SSPBUF register,
which also loads the SSPSR register. Then pin RC3/
SCK/SCL should be enabled by setting bit CKP
(SSPCON1<4>). 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 15-9).
The ACK pulse from the master-receiver is latched on
the rising edge of the ninth SCL input pulse. If the SDA
line is high (not ACK), then the data transfer is complete.
In this case, when the ACK is latched by the
slave, the slave logic is reset (resets SSPSTAT register)
and the slave monitors for another occurrence of
the START bit. If the SDA line was low (ACK), the next
transmit data must be loaded into the SSPBUF register.
Again, pin RC3/SCK/SCL must be enabled by setting
bit CKP.
An MSSP interrupt is generated for each data transfer
byte. The SSPIF bit must be cleared in software and
the SSPSTAT register is used to determine the status
of the byte. The SSPIF bit is set on the falling edge of
the ninth clock pulse.PIC18FXX2
DS39564C-page 140 © 2006 Microchip Technology Inc.
FIGURE 15-8: I2C SLAVE MODE TIMING WITH SEN = 0 (RECEPTION, 7-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>) SSPOV (SSPCON<6>)
S 1 2 34 56 7 8 91 234 5 67 89 1 23 45 7 89 P
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D1 D0
ACK Receiving Data ACK Receiving Data R/W = 0
ACK
Receiving Address
Cleared in software
SSPBUF is read
Bus Master
terminates
transfer
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
D2
6
(PIR1<3>)
CKP (CKP does not reset to ‘0’ when SEN = 0)© 2006 Microchip Technology Inc. DS39564C-page 141
PIC18FXX2
FIGURE 15-9: I2C SLAVE MODE TIMING (TRANSMISSION, 7-BIT ADDRESS) SDA SCL SSPIF (PIR1<3>) BF (SSPSTAT<0>) A6 A5 A4 A3 A2 A1 D6 D5 D4 D3 D2 D1 D0
1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9
SSPBUF is written in software
Cleared in software
SCL held low
while CPU
responds to SSPIF
From SSPIF ISR
Data in
sampled
S
ACK Transmitting Data R/W = 1
ACK
Receiving Address
A7 D7
9 1
D6 D5 D4 D3 D2 D1 D0
2 3 4 5 6 7 8 9
SSPBUF is written in software
Cleared in software
From SSPIF ISR
Transmitting Data
D7
1
CKP
P
ACK
CKP is set in software CKP is set in softwarePIC18FXX2
DS39564C-page 142 © 2006 Microchip Technology Inc.
FIGURE 15-10: I2C SLAVE MODE TIMING WITH SEN = 0 (RECEPTION, 10-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1 234 56 7 89 1 2345 67 89 1 2345 7 89 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0
Receive Data Byte
ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
D2
6
(PIR1<3>)
Cleared in software
Receive Second Byte of Address
Cleared by hardware
when SSPADD is updated
with low byte of address
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
ACK
CKP
D7 D6 D5 D4 D3 D1 D0
12345 789
Receive Data Byte
Bus Master
terminates
transfer
D2
6
ACK
Cleared in software Cleared in software
SSPOV (SSPCON<6>)
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
(CKP does not reset to ‘0’ when SEN = 0)
Clock is held low until
update of SSPADD has
taken place© 2006 Microchip Technology Inc. DS39564C-page 143
PIC18FXX2
FIGURE 15-11: I2C SLAVE MODE TIMING (TRANSMISSION, 10-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1 234 56 789 1 2345 67 89 1 2345 789 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 1 1 1 1 0 A8
R/W=1
ACK ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
Bus Master
terminates
transfer
A9
6
(PIR1<3>)
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated with low
byte of address
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address.
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
Receive First Byte of Address
D7 D6 D5 D4 D3 D1
12345 789
ACK
D2
6
Transmitting Data Byte
D0
Dummy read of SSPBUF
to clear BF flag
Sr
Cleared in software
Write of SSPBUF
initiates transmit
Cleared in software
Completion of
clears BF flag
CKP (SSPCON<4>)
CKP is set in software
CKP is automatically cleared in hardware holding SCL low
Clock is held low until
update of SSPADD has
taken place
data transmission
Clock is held low until
CKP is set to ‘1’
BF flag is clear
at the end of the
third address sequencePIC18FXX2
DS39564C-page 144 © 2006 Microchip Technology Inc.
15.4.4 CLOCK STRETCHING
Both 7- and 10-bit Slave modes implement automatic
clock stretching during a transmit sequence.
The SEN bit (SSPCON2<0>) allows clock stretching to
be enabled during receives. Setting SEN will cause
the SCL pin to be held low at the end of each data
receive sequence.
15.4.4.1 Clock Stretching for 7-bit Slave
Receive Mode (SEN = 1)
In 7-bit Slave Receive mode, on the falling edge of the
ninth clock at the end of the ACK sequence, if the BF
bit is set, the CKP bit in the SSPCON1 register is automatically
cleared, forcing the SCL output to be held
low. The CKP being cleared to ‘0’ will assert the SCL
line low. The CKP bit must be set in the user’s ISR
before reception is allowed to continue. By holding the
SCL line low, the user has time to service the ISR and
read the contents of the SSPBUF before the master
device can initiate another receive sequence. This will
prevent buffer overruns from occurring (see
Figure 15-13).
15.4.4.2 Clock Stretching for 10-bit Slave
Receive Mode (SEN = 1)
In 10-bit Slave Receive mode, during the address
sequence, clock stretching automatically takes place
but CKP is not cleared. During this time, if the UA bit is
set after the ninth clock, clock stretching is initiated.
The UA bit is set after receiving the upper byte of the
10-bit address, and following the receive of the second
byte of the 10-bit address with the R/W bit cleared to
‘0’. The release of the clock line occurs upon updating
SSPADD. Clock stretching will occur on each data
receive sequence as described in 7-bit mode.
15.4.4.3 Clock Stretching for 7-bit Slave
Transmit Mode
7-bit Slave Transmit mode implements clock stretching
by clearing the CKP bit after the falling edge of the
ninth clock, if the BF bit is clear. This occurs,
regardless of the state of the SEN bit.
The user’s ISR must set the CKP bit before transmission
is allowed to continue. By holding the SCL line
low, the user has time to service the ISR and load the
contents of the SSPBUF before the master device can
initiate another transmit sequence (see Figure 15-9).
15.4.4.4 Clock Stretching for 10-bit Slave
Transmit Mode
In 10-bit Slave Transmit mode, clock stretching is controlled
during the first two address sequences by the
state of the UA bit, just as it is in 10-bit Slave Receive
mode. The first two addresses are followed by a third
address sequence, which contains the high order bits
of the 10-bit address and the R/W bit set to ‘1’. After
the third address sequence is performed, the UA bit is
not set, the module is now configured in Transmit
mode, and clock stretching is controlled by the BF flag,
as in 7-bit Slave Transmit mode (see Figure 15-11).
Note 1: If the user reads the contents of the
SSPBUF before the falling edge of the
ninth clock, thus clearing the BF bit, the
CKP bit will not be cleared and clock
stretching will not occur.
2: The CKP bit can be set in software,
regardless of the state of the BF bit. The
user should be careful to clear the BF bit
in the ISR before the next receive
sequence, in order to prevent an overflow
condition.
Note: If the user polls the UA bit and clears it by
updating the SSPADD register before the
falling edge of the ninth clock occurs, and if
the user hasn’t cleared the BF bit by reading
the SSPBUF register before that time,
then the CKP bit will still NOT be asserted
low. Clock stretching on the basis of the
state of the BF bit only occurs during a data
sequence, not an address sequence.
Note 1: If the user loads the contents of SSPBUF,
setting the BF bit before the falling edge of
the ninth clock, the CKP bit will not be
cleared and clock stretching will not occur.
2: The CKP bit can be set in software,
regardless of the state of the BF bit.© 2006 Microchip Technology Inc. DS39564C-page 145
PIC18FXX2
15.4.4.5 Clock Synchronization and
the CKP bit
If a user clears the CKP bit, the SCL output is forced to
‘0’. Setting the CKP bit will not assert the SCL output
low until the SCL output is already sampled low. If the
user attempts to drive SCL low, the CKP bit will not
assert the SCL line until an external I2C master device
has already asserted the SCL line. The SCL output will
remain low until the CKP bit is set, and all other
devices on the I2C bus have de-asserted SCL. This
ensures that a write to the CKP bit will not violate the
minimum high time requirement for SCL (see
Figure 15-12).
FIGURE 15-12: CLOCK SYNCHRONIZATION TIMING
SDA
SCL
DX DX-1
WR
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
SSPCON
CKP
Master device
de-asserts clock
Master device
asserts clockPIC18FXX2
DS39564C-page 146 © 2006 Microchip Technology Inc.
FIGURE 15-13: I2C SLAVE MODE TIMING WITH SEN = 1 (RECEPTION, 7-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>) SSPOV (SSPCON<6>)
S 1 2 34 56 7 8 9 1 234 5 67 89 1 23 45 7 89 P
A7 A6 A5 A4 A3 A2 A1 D7 D6 D5 D4 D3 D2 D1 D0 D7 D6 D5 D4 D3 D1 D0
ACK Receiving Data ACK Receiving Data R/W = 0
ACK
Receiving Address
Cleared in software
SSPBUF is read
Bus Master
terminates
transfer
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
D2
6
(PIR1<3>)
CKP
CKP
written
to ‘1’ in
If BF is cleared
prior to the falling
edge of the 9th clock,
CKP will not be reset
to ‘0’ and no clock
stretching will occur
software
Clock is held low until
CKP is set to ‘1’
Clock is not held low
because buffer full bit is
clear prior to falling edge
of 9th clock
Clock is not held low
because ACK = 1
BF is set after falling
edge of the 9th clock,
CKP is reset to ‘0’ and
clock stretching occurs© 2006 Microchip Technology Inc. DS39564C-page 147
PIC18FXX2
FIGURE 15-14: I2C SLAVE MODE TIMING SEN = 1 (RECEPTION, 10-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>)
S 1 234 56 7 8 9 1 234 5 67 89 1 2345 7 89 P
1 1 1 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D1 D0
Receive Data Byte
ACK
R/W = 0
ACK
Receive First Byte of Address
Cleared in software
D2
6
(PIR1<3>)
Cleared in software
Receive Second Byte of Address
Cleared by hardware when
SSPADD is updated with low
byte of address after falling edge
UA (SSPSTAT<1>)
Clock is held low until
update of SSPADD has
taken place
UA is set indicating that
the SSPADD needs to be
updated
UA is set indicating that
SSPADD needs to be
updated
Cleared by hardware when
SSPADD is updated with high
byte of address after falling edge
SSPBUF is written with
contents of SSPSR
Dummy read of SSPBUF
to clear BF flag
ACK
CKP
D7 D6 D5 D4 D3 D1 D0
12345 789
Receive Data Byte
Bus Master
terminates
transfer
D2
6
ACK
Cleared in software Cleared in software
SSPOV (SSPCON<6>)
CKP written to ‘1’
Note: An update of the SSPADD
register before the falling
edge of the ninth clock will
have no effect on UA, and
UA will remain set.
Note: An update of the SSPADD
register before the falling
edge of the ninth clock will
have no effect on UA, and
UA will remain set.
in software
Clock is held low until
update of SSPADD has
taken place
of ninth clock. of ninth clock.
SSPOV is set
because SSPBUF is
still full. ACK is not sent.
Dummy read of SSPBUF
to clear BF flag
Clock is held low until
CKP is set to ‘1’
Clock is not held low
because ACK = 1PIC18FXX2
DS39564C-page 148 © 2006 Microchip Technology Inc.
15.4.5 GENERAL CALL ADDRESS
SUPPORT
The addressing procedure for the I2C 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, in theory, respond with an
Acknowledge.
The general call address is one of eight addresses
reserved for specific purposes by the I2C 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 enabled (SSPCON2<7>
set). Following a START bit detect, 8-bits are shifted
into the SSPSR and the address is compared against
the SSPADD. It is also compared to the general call
address and fixed in hardware.
If the general call address matches, the SSPSR is
transferred to the SSPBUF, the BF flag bit is set (eighth
bit), and on the falling edge of the ninth bit (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. The value can be used to determine if the
address was device specific or a general call address.
In 10-bit mode, the SSPADD is required to be updated
for the second half of the address to match, and the UA
bit is set (SSPSTAT<1>). If the general call address is
sampled when the GCEN bit is set, while the slave is
configured in 10-bit Address mode, then the second
half of the address is not necessary, the UA bit will not
be set, and the slave will begin receiving data after the
Acknowledge (Figure 15-15).
FIGURE 15-15: SLAVE MODE GENERAL CALL ADDRESS SEQUENCE
(7 OR 10-BIT ADDRESS MODE)
SDA
SCL
S
SSPIF
BF (SSPSTAT<0>)
SSPOV (SSPCON1<6>)
Cleared in software
SSPBUF is read
R/W = 0
ACK General Call Address
Address is compared to General Call Address
GCEN (SSPCON2<7>)
Receiving data ACK
1 2 34 56 7891 2 34 56 789
D7 D6 D5 D4 D3 D2 D1 D0
after ACK, set interrupt
'0'
'1'© 2006 Microchip Technology Inc. DS39564C-page 149
PIC18FXX2
15.4.6 MASTER MODE
Master mode is enabled by setting and clearing the
appropriate SSPM bits in SSPCON1 and by setting the
SSPEN bit. In Master mode, the SCL and SDA lines
are manipulated by the MSSP hardware.
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 MSSP module is
disabled. Control of the I2C bus may be taken when the
P bit is set or the bus is IDLE, with both the S and P bits
clear.
In Firmware Controlled Master mode, user code conducts
all I2C bus operations based on START and
STOP bit conditions.
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. Configure the I2C port to receive data.
5. Generate an Acknowledge condition at the end
of a received byte of data.
6. Generate a STOP condition on SDA and SCL.
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
FIGURE 15-16: MSSP BLOCK DIAGRAM (I2C MASTER MODE)
Note: 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
initiate 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 a write
to the SSPBUF did not occur.
Read Write
SSPSR
START bit, STOP bit,
START bit Detect
SSPBUF
Internal
Data Bus
Set/Reset, S, P, WCOL (SSPSTAT)
Shift
Clock
MSb LSb
SDA
Acknowledge
Generate
STOP bit Detect
Write Collision Detect
Clock Arbitration
State Counter for
end of XMIT/RCV
SCL
SCL in
Bus Collision
SDA in Receive Enable
Clock Cntl
Clock Arbitrate/WCOL Detect
(hold off clock source)
SSPADD<6:0>
Baud
Set SSPIF, BCLIF
Reset ACKSTAT, PEN (SSPCON2)
Rate
Generator
SSPM3:SSPM0PIC18FXX2
DS39564C-page 150 © 2006 Microchip Technology Inc.
15.4.6.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
I
2C 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 SDA, while SCL 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 the SPI mode operation
is used to set the SCL clock frequency for either
100 kHz, 400 kHz or 1 MHz I2C operation. See
Section 15.4.7 (“Baud Rate Generator”), for more
detail.
A typical transmit sequence would go as follows:
1. The user generates a START condition by setting
the START enable bit, SEN
(SSPCON2<0>).
2. SSPIF is set. The MSSP module will wait the
required start time before any other operation
takes place.
3. The user loads the SSPBUF with the slave
address to transmit.
4. Address is shifted out the SDA pin until all 8 bits
are transmitted.
5. The MSSP Module shifts in the ACK bit from the
slave device and writes its value into the
SSPCON2 register (SSPCON2<6>).
6. The MSSP module generates an interrupt at the
end of the ninth clock cycle by setting the SSPIF
bit.
7. The user loads the SSPBUF with eight bits of
data.
8. Data is shifted out the SDA pin until all 8 bits are
transmitted.
9. The MSSP Module shifts in the ACK bit from the
slave device and writes its value into the
SSPCON2 register (SSPCON2<6>).
10. The MSSP module generates an interrupt at the
end of the ninth clock cycle by setting the SSPIF
bit.
11. The user generates a STOP condition by setting
the STOP enable bit PEN (SSPCON2<2>).
12. Interrupt is generated once the STOP condition
is complete.© 2006 Microchip Technology Inc. DS39564C-page 151
PIC18FXX2
15.4.7 BAUD RATE GENERATOR
In I2C Master mode, the baud rate generator (BRG)
reload value is placed in the lower 7 bits of the
SSPADD register (Figure 15-17). When a write occurs
to SSPBUF, the baud rate generator will automatically
begin counting. The BRG counts down to 0 and stops
until another reload has taken place. The BRG count is
decremented twice per instruction cycle (TCY) on the
Q2 and Q4 clocks. In I2C Master mode, the BRG is
reloaded automatically.
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.
Table 15-3 demonstrates clock rates based on
instruction cycles and the BRG value loaded into
SSPADD.
FIGURE 15-17: BAUD RATE GENERATOR BLOCK DIAGRAM
TABLE 15-3: I2C CLOCK RATE W/BRG
SSPM3:SSPM0
CLKO BRG Down Counter Fosc/4
SSPADD<6:0>
SSPM3:SSPM0
SCL
Reload
Control
Reload
FCY FCY*2 BRG Value FSCL(2)
(2 Rollovers of BRG)
10 MHz 20 MHz 19h 400 kHz(1)
10 MHz 20 MHz 20h 312.5 kHz
10 MHz 20 MHz 3Fh 100 kHz
4 MHz 8 MHz 0Ah 400 kHz(1)
4 MHz 8 MHz 0Dh 308 kHz
4 MHz 8 MHz 28h 100 kHz
1 MHz 2 MHz 03h 333 kHz(1)
1 MHz 2 MHz 0Ah 100kHz
1 MHz 2 MHz 00h 1 MHz(1)
Note 1: The I2C interface does not conform to the 400 kHz I2C specification (which applies to rates greater than
100 kHz) in all details, but may be used with care where higher rates are required by the application.
2: Actual frequency will depend on bus conditions. Theoretically, bus conditions will add rise time and extend
low time of clock period, producing the effective frequency.PIC18FXX2
DS39564C-page 152 © 2006 Microchip Technology Inc.
15.4.7.1 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 15-18).
FIGURE 15-18: BAUD RATE GENERATOR TIMING WITH CLOCK ARBITRATION
SDA
SCL
SCL de-asserted but slave holds
DX DX-1
BRG
SCL is sampled high, reload takes
place and BRG starts its count.
03h 02h 01h 00h (hold off) 03h 02h
Reload
BRG
Value
SCL low (clock arbitration)
SCL allowed to transition high
BRG decrements on
Q2 and Q4 cycles© 2006 Microchip Technology Inc. DS39564C-page 153
PIC18FXX2
15.4.8 I2C MASTER MODE START
CONDITION TIMING
To initiate a START condition, the user sets the START
condition enable bit, SEN (SSPCON2<0>). If the SDA
and SCL pins are sampled high, the baud rate generator
is reloaded with the contents of SSPADD<6:0> and
starts its count. If SCL and SDA are both sampled high
when the baud rate generator times out (TBRG), the
SDA pin is driven low. The action of the SDA being
driven low, while SCL is high, is the START condition
and causes the S bit (SSPSTAT<3>) 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 (TBRG), the
SEN bit (SSPCON2<0>) will be automatically cleared
by hardware, the baud rate generator is suspended,
leaving the SDA line held low and the START condition
is complete.
15.4.8.1 WCOL Status Flag
If the user writes the SSPBUF when a START
sequence is in progress, the WCOL is set and the contents
of the buffer are unchanged (the write doesn’t
occur).
FIGURE 15-19: FIRST START BIT TIMING
Note: If at the beginning of the START condition,
the SDA and SCL pins are already sampled
low, or if during the START condition
the SCL line is sampled low before the
SDA line is driven low, a bus collision
occurs, the Bus Collision Interrupt Flag,
BCLIF is set, the START condition is
aborted, and the I2C module is reset into its
IDLE state.
Note: Because queueing of events is not
allowed, writing to the lower 5 bits of
SSPCON2 is disabled until the START
condition is complete.
SDA
SCL
S
TBRG
1st bit 2nd bit
TBRG
SDA = 1,
At completion of START bit, SCL = 1
TBRG Write to SSPBUF occurs here
Hardware clears SEN bit
TBRG
Write to SEN bit occurs here Set S bit (SSPSTAT<3>)
and sets SSPIF bitPIC18FXX2
DS39564C-page 154 © 2006 Microchip Technology Inc.
15.4.9 I2C MASTER MODE REPEATED
START CONDITION TIMING
A Repeated START condition occurs when the RSEN
bit (SSPCON2<1>) 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 SCL is sampled
high, the baud rate generator is reloaded with the contents
of SSPADD<6:0> and begins counting. SDA and
SCL must be sampled high for one TBRG. This action is
then followed by assertion of the SDA pin (SDA = 0) for
one TBRG,
while SCL is high. Following this, the RSEN
bit (SSPCON2<1>) will be automatically cleared and
the baud rate generator will not be 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<3>) will be set. The SSPIF bit will not be set
until the baud rate generator has timed out.
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).
15.4.9.1 WCOL Status Flag
If the user writes the SSPBUF when a Repeated
START sequence is in progress, the WCOL is set and
the contents of the buffer are unchanged (the write
doesn’t occur).
FIGURE 15-20: REPEAT START CONDITION WAVEFORM
Note 1: If RSEN is programmed while any other
event is in progress, it will not take effect.
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".
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.
SDA
SCL
Sr = Repeated START
Write to SSPCON2
Falling edge of ninth clock Write to SSPBUF occurs here
End of Xmit
At completion of START bit,
hardware clear RSEN bit
1st bit
Set S (SSPSTAT<3>)
TBRG
TBRG
SDA = 1,
SDA = 1,
SCL (no change)
SCL = 1
occurs here.
TBRG TBRG TBRG
and set SSPIF© 2006 Microchip Technology Inc. DS39564C-page 155
PIC18FXX2
15.4.10 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 the 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). SCL
is held low for one baud rate generator rollover count
(TBRG). Data should be valid before SCL is released
high (see data setup time specification parameter 107).
When the SCL pin is released high, it is held that way
for TBRG. 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 flag is cleared
and the master releases SDA. This allows the slave
device being addressed to respond with an ACK bit
during the ninth bit time if an address match occurred
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 SCL low and SDA unchanged
(Figure 15-21).
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<6>).
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.
15.4.10.1 BF Status Flag
In Transmit mode, the BF bit (SSPSTAT<0>) is set
when the CPU writes to SSPBUF and is cleared when
all 8 bits are shifted out.
15.4.10.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), the WCOL is set and the contents of the
buffer are unchanged (the write doesn’t occur).
WCOL must be cleared in software.
15.4.10.3 ACKSTAT Status Flag
In Transmit mode, the ACKSTAT bit (SSPCON2<6>) 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.
15.4.11 I2C MASTER MODE RECEPTION
Master mode reception is enabled by programming the
receive enable bit, RCEN (SSPCON2<3>).
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<4>).
15.4.11.1 BF Status Flag
In receive operation, 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.
15.4.11.2 SSPOV Status Flag
In receive operation, 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.
15.4.11.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), the WCOL bit is set and the contents of the buffer
are unchanged (the write doesn’t occur).
Note: In the MSSP module, the RCEN bit must
be set after the ACK sequence or the
RCEN bit will be disregarded. PIC18FXX2
DS39564C-page 156 © 2006 Microchip Technology Inc.
FIGURE 15-21: I2C MASTER MODE WAVEFORM (TRANSMISSION, 7 OR 10-BIT ADDRESS) SDA SCL SSPIF BF (SSPSTAT<0>) SEN A7 A6 A5 A4 A3 A2 A1 ACK = 0 D7 D6 D5 D4 D3 D2 D1 D0 ACK Transmitting Data or Second Half R/W = 0 Transmit Address to Slave 123456789 123456789 P Cleared in software service routine From SSP interrupt SSPBUF is written in software After START condition, SEN cleared by hardware
S
SSPBUF written with 7-bit address and R/W
start transmit
SCL held low
while CPU
responds to SSPIF
SEN = 0
of 10-bit Address
Write SSPCON2<0> SEN = 1
START condition begins From slave clear ACKSTAT bit SSPCON2<6>
ACKSTAT in
SSPCON2 = 1
Cleared in software
SSPBUF written
PEN
Cleared in software
R/W© 2006 Microchip Technology Inc. DS39564C-page 157
PIC18FXX2
FIGURE 15-22: I2C MASTER MODE WAVEFORM (RECEPTION, 7-BIT ADDRESS)
P 9 8 7 6 5
D0 D1 D2 D3 D4 D5 D6 D7
S
A7 A6 A5 A4 A3 A2 A1 SDA
SCL 1 2 3 4 5 6 7 8 9 1 2 3 4 5 678 9 1234
Bus Master
terminates
transfer
ACK
Receiving Data from Slave Receiving Data from Slave
D0 D1 D2 D3 D4 D5 D6 D7 ACK
R/W = 1 Transmit Address to Slave
SSPIF
BF
ACK is not sent
Write to SSPCON2<0> (SEN = 1)
Write to SSPBUF occurs here
ACK from Slave
Master configured as a receiver
by programming SSPCON2<3>, (RCEN = 1)
PEN bit = 1
written here
Data shifted in on falling edge of CLK
Cleared in software
Start XMIT
SEN = 0
SDA = 0, SCL = 1
SSPOV
while CPU
(SSPSTAT<0>)
ACK
Last bit is shifted into SSPSR and
contents are unloaded into SSPBUF
Cleared in software Cleared in software
Set SSPIF interrupt
at end of receive
Set P bit
(SSPSTAT<4>)
and SSPIF
Cleared in
software
ACK from Master
Set SSPIF at end
Set SSPIF interrupt
at end of Acknowledge
sequence
Set SSPIF interrupt
at end of Acknowledge
sequence
of receive
Set ACKEN, start Acknowledge sequence
SSPOV is set because
SSPBUF is still full
SDA = ACKDT = 1
RCEN cleared
automatically
RCEN = 1 start
next receive
Write to SSPCON2<4>
to start Acknowledge sequence
SDA = ACKDT (SSPCON2<5>) = 0
RCEN cleared
automatically
responds to SSPIF
ACKEN
Begin START Condition
Cleared in software
SDA = ACKDT = 0 PIC18FXX2
DS39564C-page 158 © 2006 Microchip Technology Inc.
15.4.12 ACKNOWLEDGE SEQUENCE
TIMING
An Acknowledge sequence is enabled by setting the
Acknowledge sequence enable bit, ACKEN
(SSPCON2<4>). When this bit is set, the SCL pin is
pulled low and the contents of the Acknowledge data bit
are 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 (TBRG) and the
SCL pin is de-asserted (pulled high). When the SCL pin
is sampled high (clock arbitration), the baud rate generator
counts for TBRG. 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 15-23).
15.4.12.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).
15.4.13 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<2>). At the end of a receive/transmit
the SCL line 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 TBRG (baud rate
generator rollover count) later, the SDA pin will be
de-asserted. When the SDA pin is sampled high while
SCL is high, the P bit (SSPSTAT<4>) is set. A TBRG
later, the PEN bit is cleared and the SSPIF bit is set
(Figure 15-24).
15.4.13.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 15-23: ACKNOWLEDGE SEQUENCE WAVEFORM
FIGURE 15-24: STOP CONDITION RECEIVE OR TRANSMIT MODE
Note: TBRG = one baud rate generator period.
SDA
SCL
Set SSPIF at the end
Acknowledge sequence starts here,
Write to SSPCON2 ACKEN automatically cleared
Cleared in
TBRG TBRG
of receive
ACK
8
ACKEN = 1, ACKDT = 0
D0
9
SSPIF
software Set SSPIF at the end
of Acknowledge sequence
Cleared in
software
SCL
SDA
SDA asserted low before rising edge of clock
Write to SSPCON2
Set PEN
Falling edge of
SCL = 1 for TBRG, followed by SDA = 1 for TBRG
9th clock
SCL brought high after TBRG
Note: TBRG = one baud rate generator period.
TBRG TBRG
after SDA sampled high. P bit (SSPSTAT<4>) is set.
TBRG
to setup STOP condition.
ACK
P
TBRG
PEN bit (SSPCON2<2>) is cleared by
hardware and the SSPIF bit is set© 2006 Microchip Technology Inc. DS39564C-page 159
PIC18FXX2
15.4.14 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 MSSP interrupt is enabled).
15.4.15 EFFECT OF A RESET
A RESET disables the MSSP module and terminates
the current transfer.
15.4.16 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 I2C 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
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:
• Address Transfer
• Data Transfer
• A START Condition
• A Repeated START Condition
• An Acknowledge Condition
15.4.17 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 I2C
port to its IDLE state (Figure 15-25).
If a transmit was in progress when the bus collision
occurred, the transmission is halted, the BF flag is
cleared, the SDA and SCL lines are de-asserted, and
the SSPBUF can be written to. When the user services
the bus collision Interrupt Service Routine, and if the
I
2C 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 I2C bus is free, the user can resume communication
by asserting a START condition.
The master will continue to monitor the SDA and SCL
pins. 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 the 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 I2C
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 15-25: BUS COLLISION TIMING FOR TRANSMIT AND ACKNOWLEDGE
SDA
SCL
BCLIF
SDA released
SDA line pulled low
by another source
Sample SDA. While SCL is high,
data doesn’t match what is driven
Bus collision has occurred.
Set bus collision
interrupt (BCLIF)
by the master.
by master
Data changes
while SCL = 0PIC18FXX2
DS39564C-page 160 © 2006 Microchip Technology Inc.
15.4.17.1 Bus Collision During a START
Condition
During a START condition, a bus collision occurs if:
a) SDA or SCL are sampled low at the beginning of
the START condition (Figure 15-26).
b) SCL is sampled low before SDA is asserted low
(Figure 15-27).
During a START condition, both the SDA and the SCL
pins are monitored.
If the SDA pin is already low, or the SCL pin is already
low, then all of the following occur:
• the START condition is aborted,
• the BCLIF flag is set, and
• the MSSP module is reset to its IDLE state
(Figure 15-26).
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 0. 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 15-28). 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 0, and during this time, if the SCL pins
are sampled as '0', a bus collision does not occur. At
the end of the BRG count, the SCL pin is asserted low.
FIGURE 15-26: BUS COLLISION DURING START CONDITION (SDA ONLY)
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. If the address is
the same, arbitration must be allowed to
continue into the data portion, Repeated
START or STOP conditions.
SDA
SCL
SEN
SDA sampled low before
SDA goes low before the SEN bit is set.
S bit and SSPIF set because
SSP module reset into IDLE state.
SEN cleared automatically because of bus collision.
S bit and SSPIF set because
Set SEN, enable START
condition if SDA = 1, SCL=1
SDA = 0, SCL = 1.
BCLIF
S
SSPIF
SDA = 0, SCL = 1.
SSPIF and BCLIF are
cleared in software.
SSPIF and BCLIF are
cleared in software.
Set BCLIF,
START condition. Set BCLIF.© 2006 Microchip Technology Inc. DS39564C-page 161
PIC18FXX2
FIGURE 15-27: BUS COLLISION DURING START CONDITION (SCL = 0)
FIGURE 15-28: BRG RESET DUE TO SDA ARBITRATION DURING START CONDITION
SDA
SCL
SEN bus collision occurs. set BCLIF
SCL = 0 before SDA = 0,
Set SEN, enable START
sequence if SDA = 1, SCL = 1
TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
Interrupt cleared
in software
bus collision occurs. Set BCLIF.
SCL = 0 before BRG time-out,
'0' '0'
'0' '0'
SDA
SCL
SEN
Set S
Set SEN, enable START
sequence if SDA = 1, SCL = 1
Less than TBRG TBRG
SDA = 0, SCL = 1
BCLIF
S
SSPIF
S
Interrupts cleared
Set SSPIF in software
SDA = 0, SCL = 1
SDA pulled low by other master.
Reset BRG and assert SDA.
SCL pulled low after BRG
Time-out
Set SSPIF
'0'PIC18FXX2
DS39564C-page 162 © 2006 Microchip Technology Inc.
15.4.17.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’,
Figure 15-29). If SDA is sampled high, the BRG is
reloaded and begins counting. If SDA 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.
If SCL goes from high to low before the BRG times out
and SDA has not already been asserted, a bus collision
occurs. In this case, another master is attempting to
transmit a data ’1’ during the Repeated START
condition, Figure 15-30.
If, at the end of the BRG time-out both SCL and SDA
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 15-29: BUS COLLISION DURING A REPEATED START CONDITION (CASE 1)
FIGURE 15-30: BUS COLLISION DURING REPEATED START CONDITION (CASE 2)
SDA
SCL
RSEN
BCLIF
S
SSPIF
Sample SDA when SCL goes high.
If SDA = 0, set BCLIF and release SDA and SCL.
Cleared in software
'0'
'0'
SDA
SCL
BCLIF
RSEN
S
SSPIF
Interrupt cleared
in software
SCL goes low before SDA,
Set BCLIF. Release SDA and SCL.
TBRG TBRG
'0'© 2006 Microchip Technology Inc. DS39564C-page 163
PIC18FXX2
15.4.17.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 allowed 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 15-31). 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 15-32).
FIGURE 15-31: BUS COLLISION DURING A STOP CONDITION (CASE 1)
FIGURE 15-32: BUS COLLISION DURING A STOP CONDITION (CASE 2)
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
SDA asserted low
SDA sampled
low after TBRG,
Set BCLIF
'0'
'0'
SDA
SCL
BCLIF
PEN
P
SSPIF
TBRG TBRG TBRG
Assert SDA SCL goes low before SDA goes high
Set BCLIF
'0'
'0'PIC18FXX2
DS39564C-page 164 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 165
PIC18FXX2
16.0 ADDRESSABLE UNIVERSAL
SYNCHRONOUS
ASYNCHRONOUS RECEIVER
TRANSMITTER (USART)
The Universal Synchronous Asynchronous Receiver
Transmitter (USART) module is one of the two serial
I/O modules. (USART is also known as a Serial Communications
Interface or SCI.) The 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 USART can be configured in the following modes:
• Asynchronous (full-duplex)
• Synchronous - Master (half-duplex)
• Synchronous - Slave (half-duplex)
In order to configure pins RC6/TX/CK and RC7/RX/DT
as the Universal Synchronous Asynchronous Receiver
Transmitter:
• bit SPEN (RCSTA<7>) must be set (= 1),
• bit TRISC<6> must be cleared (= 0), and
• bit TRISC<7> must be set (=1).
Register 16-1 shows the Transmit Status and Control
Register (TXSTA) and Register 16-2 shows the
Receive Status and Control Register (RCSTA).PIC18FXX2
DS39564C-page 166 © 2006 Microchip Technology Inc.
REGISTER 16-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 R/W-0
CSRC TX9 TXEN SYNC — BRGH TRMT TX9D
bit 7 bit 0
bit 7 CSRC: Clock Source Select bit
Asynchronous mode:
Don’t care
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: SREN/CREN overrides TXEN in SYNC mode.
bit 4 SYNC: USART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
bit 3 Unimplemented: Read as '0'
bit 2 BRGH: High Baud Rate Select bit
Asynchronous mode:
1 = High speed
0 = Low speed
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
Can be Address/Data bit or a parity bit.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown© 2006 Microchip Technology Inc. DS39564C-page 167
PIC18FXX2
REGISTER 16-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
Asynchronous mode:
Don’t care
Synchronous mode - Master:
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception is complete.
Synchronous mode - Slave:
Don’t care
bit 4 CREN: Continuous Receive Enable bit
Asynchronous mode:
1 = Enables receiver
0 = Disables receiver
Synchronous mode:
1 = Enables continuous receive until enable bit CREN is cleared (CREN overrides SREN)
0 = Disables continuous receive
bit 3 ADDEN: Address Detect Enable bit
Asynchronous mode 9-bit (RX9 = 1):
1 = Enables address detection, enable interrupt and load 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
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
This can be Address/Data bit or a parity bit, and must be calculated by user firmware.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 168 © 2006 Microchip Technology Inc.
16.1 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, bit BRGH (TXSTA<2>) also controls the baud
rate. In Synchronous mode, bit BRGH is ignored.
Table 16-1 shows the formula for computation of the
baud rate for different USART modes, which only apply
in Master mode (internal clock).
Given the desired baud rate and Fosc, the nearest integer
value for the SPBRG register can be calculated
using the formula in Table 16-1. From this, the error in
baud rate can be determined.
Example 16-1 shows the calculation of the baud rate
error for the following conditions:
• FOSC = 16 MHz
• Desired Baud Rate = 9600
• BRGH = 0
• SYNC = 0
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.
16.1.1 SAMPLING
The data on the RC7/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.
EXAMPLE 16-1: CALCULATING BAUD RATE ERROR
TABLE 16-1: BAUD RATE FORMULA
TABLE 16-2: REGISTERS ASSOCIATED WITH BAUD RATE GENERATOR
Desired Baud Rate = FOSC / (64 (X + 1))
Solving for X:
X = ( (FOSC / Desired Baud Rate) / 64 ) – 1
X = ((16000000 / 9600) / 64) – 1
X = [25.042] = 25
Calculated Baud Rate = 16000000 / (64 (25 + 1))
= 9615
Error = (Calculated Baud Rate – Desired Baud Rate)
Desired Baud Rate
= (9615 – 9600) / 9600
= 0.16%
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))
N/A
Legend: X = value in SPBRG (0 to 255)
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
TXSTA CSRC TX9 TXEN SYNC — BRGH TRMT TX9D 0000 -010 0000 -010
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
SPBRG Baud Rate Generator Register 0000 0000 0000 0000
Legend: x = unknown, - = unimplemented, read as '0'. Shaded cells are not used by the BRG.© 2006 Microchip Technology Inc. DS39564C-page 169
PIC18FXX2
TABLE 16-3: BAUD RATES FOR SYNCHRONOUS MODE
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 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 SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 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)
FOSC = 4 MHz SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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 - 255PIC18FXX2
DS39564C-page 170 © 2006 Microchip Technology Inc.
TABLE 16-4: BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = 0)
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
0.3 NA - - NA - - NA - - NA - -
1.2 NA - - NA - - NA - - NA - -
2.4 NA - - 2.40 -0.07 214 2.40 -0.15 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)
FOSC = 16 MHz SPBRG
value
(decimal)
10 MHz SPBRG
value
(decimal)
7.15909 MHz SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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
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 SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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© 2006 Microchip Technology Inc. DS39564C-page 171
PIC18FXX2
TABLE 16-5: BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = 1)
BAUD
RATE
(Kbps)
FOSC = 40 MHz SPBRG
value
(decimal)
33 MHz SPBRG
value
(decimal)
25 MHz SPBRG
value
(decimal)
20 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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 SPBRG
value
(decimal)
7.15909 MHz SPBRG
value
(decimal)
5.0688 MHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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
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)
FOSC = 4 MHz SPBRG
value
(decimal)
3.579545 MHz SPBRG
value
(decimal)
1 MHz SPBRG
value
(decimal)
32.768 kHz SPBRG
value
(decimal) KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR KBAUD
%
ERROR
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 - 255PIC18FXX2
DS39564C-page 172 © 2006 Microchip Technology Inc.
16.2 USART Asynchronous Mode
In this mode, the USART uses standard non-return-tozero
(NRZ) format (one START bit, eight or nine data
bits and one STOP bit). The most common data format
is 8-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 bit BRGH (TXSTA<2>). Parity is not
supported by the hardware, but can be implemented in
software (and stored as the ninth data bit).
Asynchronous mode is stopped during SLEEP.
Asynchronous mode is selected by clearing bit SYNC
(TXSTA<4>).
The USART Asynchronous module consists of the
following important elements:
• Baud Rate Generator
• Sampling Circuit
• Asynchronous Transmitter
• Asynchronous Receiver
16.2.1 USART ASYNCHRONOUS
TRANSMITTER
The USART transmitter block diagram is shown in
Figure 16-1. The heart of the transmitter is the Transmit
(serial) Shift Register (TSR). The shift register obtains
its data from the read/write transmit buffer, TXREG. The
TXREG register is loaded with data in software. The
TSR register is not loaded until the STOP bit has been
transmitted from the 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
flag bit TXIF (PIR1<4>) is set. This interrupt can be
enabled/disabled by setting/clearing enable bit TXIE
( PIE1<4>). Flag bit TXIF will be set, regardless of the
state of enable bit TXIE and cannot be cleared in software.
It will reset only when new data is loaded into the
TXREG register. While flag bit TXIF indicated the status
of the TXREG register, another bit, TRMT
(TXSTA<1>), shows the status of the TSR register. Status
bit TRMT 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.
To set up an asynchronous transmission:
1. Initialize the SPBRG register for the appropriate
baud rate. If a high speed baud rate is desired,
set bit BRGH (Section 16.1).
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set transmit bit
TX9. Can be used as address/data bit.
5. Enable the transmission by setting bit TXEN,
which will also set bit TXIF.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Load data to the TXREG register (starts
transmission).
FIGURE 16-1: USART TRANSMIT BLOCK DIAGRAM
Note 1: The TSR register is not mapped in data
memory, so it is not available to the user.
2: Flag bit TXIF is set when enable bit TXEN
is set.
Note: TXIF is not cleared immediately upon loading
data into the transmit buffer TXREG.
The flag bit becomes valid in the second
instruction cycle following the load
instruction.
TXIF
TXIE
Interrupt
TXEN Baud Rate CLK
SPBRG
Baud Rate Generator
TX9D
MSb LSb
Data Bus
TXREG Register
TSR Register
(8) 0
TX9
TRMT SPEN
RC6/TX/CK pin
Pin Buffer
and Control
8
• • •© 2006 Microchip Technology Inc. DS39564C-page 173
PIC18FXX2
FIGURE 16-2: ASYNCHRONOUS TRANSMISSION
FIGURE 16-3: ASYNCHRONOUS TRANSMISSION (BACK TO BACK)
TABLE 16-6: REGISTERS ASSOCIATED WITH ASYNCHRONOUS TRANSMISSION
Word 1
STOP bit
Word 1
Transmit Shift Reg
START bit bit 0 bit 1 bit 7/8
Write to TXREG
Word 1
BRG Output
(Shift Clock)
RC6/TX/CK (pin)
TXIF bit
(Transmit Buffer
Reg. Empty Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
Transmit Shift Reg.
Write to TXREG
BRG Output
(Shift Clock)
RC6/TX/CK (pin)
TXIF bit
(Interrupt Reg. Flag)
TRMT bit
(Transmit Shift
Reg. Empty Flag)
Word 1 Word 2
Word 1 Word 2
START bit STOP bit START bit
Transmit Shift Reg.
Word 1 Word 2
bit 0 bit 1 bit 7/8 bit 0
Note: This timing diagram shows two consecutive transmissions.
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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG USART Transmit Register 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 Transmission.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits clear.PIC18FXX2
DS39564C-page 174 © 2006 Microchip Technology Inc.
16.2.2 USART ASYNCHRONOUS
RECEIVER
The receiver block diagram is shown in Figure 16-4.
The data is received on the RC7/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.
To set 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 (Section 16.1).
2. Enable the asynchronous serial port by clearing
bit SYNC and setting bit SPEN.
3. If interrupts are desired, set enable bit RCIE.
4. If 9-bit reception is desired, set bit RX9.
5. Enable the reception by setting bit CREN.
6. Flag bit RCIF will be set when reception is complete
and an interrupt will be generated if enable
bit RCIE was set.
7. Read the RCSTA register to get the ninth bit (if
enabled) and determine if any error occurred
during reception.
8. Read the 8-bit received data by reading the
RCREG register.
9. If any error occurred, clear the error by clearing
enable bit CREN.
10. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
16.2.3 SETTING UP 9-BIT MODE WITH
ADDRESS DETECT
This mode would typically be used in RS-485 systems.
To set up an Asynchronous Reception with Address
Detect Enable:
1. Initialize the SPBRG register for the appropriate
baud rate. If a high speed baud rate is required,
set the BRGH bit.
2. Enable the asynchronous serial port by clearing
the SYNC bit and setting the SPEN bit.
3. If interrupts are required, set the RCEN bit and
select the desired priority level with the RCIP bit.
4. Set the RX9 bit to enable 9-bit reception.
5. Set the ADDEN bit to enable address detect.
6. Enable reception by setting the CREN bit.
7. The RCIF bit will be set when reception is complete.
The interrupt will be acknowledged if the
RCIE and GIE bits are set.
8. Read the RCSTA register to determine if any
error occurred during reception, as well as read
bit 9 of data (if applicable).
9. Read RCREG to determine if the device is being
addressed.
10. If any error occurred, clear the CREN bit.
11. If the device has been addressed, clear the
ADDEN bit to allow all received data into the
receive buffer and interrupt the CPU.
FIGURE 16-4: USART RECEIVE BLOCK DIAGRAM
x64 Baud Rate CLK
SPBRG
Baud Rate Generator
RC7/RX/DT
Pin Buffer
and Control
SPEN
Data
Recovery
CREN OERR FERR
MSb RSR Register LSb
RX9D RCREG Register FIFO
Interrupt RCIF
RCIE
Data Bus
8
÷ 64
÷ 16
or
STOP (8) 7 1 0 START
RX9
• • •© 2006 Microchip Technology Inc. DS39564C-page 175
PIC18FXX2
FIGURE 16-5: ASYNCHRONOUS RECEPTION
TABLE 16-7: REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION
START
bit bit0 bit1 bit7/8 bit0 STOP bit7/8
bit
START
bit
START
bit7/8 STOP bit
bit
RX (pin)
Reg
Rcv Buffer Reg
Rcv Shift
Read Rcv
Buffer Reg
RCREG
RCIF
(Interrupt Flag)
OERR bit
CREN
Word 1
RCREG
Word 2
RCREG
STOP
bit
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.
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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
RCREG USART Receive Register 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 PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits
clear.PIC18FXX2
DS39564C-page 176 © 2006 Microchip Technology Inc.
16.3 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 bit SYNC (TXSTA<4>). In
addition, enable bit SPEN (RCSTA<7>) is set in order
to configure the RC6/TX/CK and RC7/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 bit CSRC (TXSTA<7>).
16.3.1 USART SYNCHRONOUS MASTER
TRANSMISSION
The USART transmitter block diagram is shown in
Figure 16-1. The heart of the transmitter is the Transmit
(serial) Shift Register (TSR). The shift register obtains
its data from the read/write transmit buffer register
TXREG. The TXREG register is loaded with data in
software. The TSR register is not loaded until the last
bit has been transmitted from the previous load. As
soon as the last bit is transmitted, the TSR is loaded
with new data from the TXREG (if available). Once the
TXREG register transfers the data to the TSR register
(occurs in one TCYCLE), the TXREG is empty and interrupt
bit TXIF (PIR1<4>) is set. The interrupt can be
enabled/disabled by setting/clearing enable bit TXIE
(PIE1<4>). Flag bit TXIF will be set, regardless of the
state of enable bit TXIE, and cannot be cleared in software.
It will reset only when new data is loaded into the
TXREG register. While flag bit TXIF indicates the status
of the TXREG register, another bit TRMT (TXSTA<1>)
shows the status of the TSR register. TRMT is a read
only bit, which is set when the TSR is empty. No interrupt
logic is tied to this bit, so the user has to poll this
bit in order to determine if the TSR register is empty.
The TSR is not mapped in data memory, so it is not
available to the user.
To set up a Synchronous Master Transmission:
1. Initialize the SPBRG register for the appropriate
baud rate (Section 16.1).
2. Enable the synchronous master serial port by
setting bits SYNC, SPEN, and CSRC.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set bit TX9.
5. Enable the transmission by setting bit TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Start transmission by loading data to the TXREG
register.
TABLE 16-8: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER TRANSMISSION
Note: TXIF is not cleared immediately upon loading
data into the transmit buffer TXREG.
The flag bit becomes valid in the second
instruction cycle following the load
instruction.
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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG USART Transmit Register 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, read as '0'.
Shaded cells are not used for Synchronous Master Transmission.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits
clear.© 2006 Microchip Technology Inc. DS39564C-page 177
PIC18FXX2
FIGURE 16-6: SYNCHRONOUS TRANSMISSION
FIGURE 16-7: SYNCHRONOUS TRANSMISSION (THROUGH TXEN)
bit 0 bit 1 bit 7
Word 1
Q1 Q2 Q3Q4 Q1 Q2Q3 Q4Q1 Q2Q3 Q4Q1 Q2 Q3 Q4Q1 Q2 Q3Q4 Q3Q4 Q1 Q2 Q3Q4 Q1Q2 Q3 Q4 Q1Q2 Q3 Q4Q1 Q2 Q3 Q4Q1 Q2Q3 Q4Q1 Q2Q3 Q4
RC7/RX/DT bit 2 bit 0 bit 1 bit 7
RC6/TX/CK
Write to
TXREG Reg
TXIF bit
(Interrupt Flag)
TRMT
TXEN bit
'1' '1'
Word 2
TRMT bit
Write Word1 Write Word2
Note: Sync Master mode; SPBRG = '0'. Continuous transmission of two 8-bit words.
pin
pin
RC7/RX/DT pin
RC6/TX/CK pin
Write to
TXREG reg
TXIF bit
TRMT bit
bit0 bit1 bit2 bit6 bit7
TXEN bitPIC18FXX2
DS39564C-page 178 © 2006 Microchip Technology Inc.
16.3.2 USART SYNCHRONOUS MASTER
RECEPTION
Once Synchronous mode is selected, reception is
enabled by setting either enable bit SREN
(RCSTA<5>), or enable bit CREN (RCSTA<4>). Data is
sampled on the RC7/RX/DT pin on the falling edge of
the clock. If enable bit SREN is set, only a single word
is received. If enable bit CREN is set, the reception is
continuous until CREN is cleared. If both bits are set,
then CREN takes precedence.
To set up a Synchronous Master Reception:
1. Initialize the SPBRG register for the appropriate
baud rate (Section 16.1).
2. Enable the synchronous master serial port by
setting bits SYNC, SPEN and CSRC.
3. Ensure bits CREN and SREN are clear.
4. If interrupts are desired, set enable bit RCIE.
5. If 9-bit reception is desired, set bit RX9.
6. If a single reception is required, set bit SREN.
For continuous reception, set bit CREN.
7. Interrupt flag bit RCIF will be set when reception
is complete and an interrupt will be generated if
the enable bit RCIE was 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
bit CREN.
11. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 16-9: REGISTERS ASSOCIATED WITH SYNCHRONOUS MASTER RECEPTION
FIGURE 16-8: SYNCHRONOUS RECEPTION (MASTER MODE, SREN)
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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
RCREG USART Receive Register 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, read as '0'. Shaded cells are not used for Synchronous Master Reception.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits clear.
CREN bit
RC7/RX/DT pin
RC6/TX/CK pin
Write to
bit SREN
SREN bit
RCIF bit
(Interrupt)
Read
RXREG
Q2 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
'0'
bit0 bit1 bit2 bit3 bit4 bit5 bit6 bit7
'0'
Q1 Q2 Q3 Q4
Note: Timing diagram demonstrates Sync Master mode with bit SREN = '1' and bit BRGH = '0'.© 2006 Microchip Technology Inc. DS39564C-page 179
PIC18FXX2
16.4 USART Synchronous Slave Mode
Synchronous Slave mode differs from the Master mode
in the fact that the shift clock is supplied externally at
the RC6/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 bit CSRC (TXSTA<7>).
16.4.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) Flag bit TXIF will not be set.
d) When the first word has been shifted out of TSR,
the TXREG register will transfer the second
word to the TSR and flag bit TXIF will now be
set.
e) If enable bit TXIE is set, the interrupt will wake
the chip from SLEEP. If the global interrupt is
enabled, the program will branch to the interrupt
vector.
To set up a Synchronous Slave Transmission:
1. Enable the synchronous slave serial port by setting
bits SYNC and SPEN and clearing bit
CSRC.
2. Clear bits CREN and SREN.
3. If interrupts are desired, set enable bit TXIE.
4. If 9-bit transmission is desired, set bit TX9.
5. Enable the transmission by setting enable bit
TXEN.
6. If 9-bit transmission is selected, the ninth bit
should be loaded in bit TX9D.
7. Start transmission by loading data to the TXREG
register.
8. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 16-10: REGISTERS ASSOCIATED WITH SYNCHRONOUS SLAVE TRANSMISSION
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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
TXREG USART Transmit Register 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, read as '0'.
Shaded cells are not used for Synchronous Slave Transmission.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits
clear.PIC18FXX2
DS39564C-page 180 © 2006 Microchip Technology Inc.
16.4.2 USART SYNCHRONOUS SLAVE
RECEPTION
The operation of the Synchronous Master and Slave
modes is identical, except in the case of the SLEEP
mode and bit SREN, which is a “don't care” in Slave
mode.
If receive is enabled by setting bit CREN 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 enable bit RCIE bit is set, the interrupt generated
will wake the chip from SLEEP. If the global interrupt is
enabled, the program will branch to the interrupt vector.
To set up a Synchronous Slave Reception:
1. Enable the synchronous master serial port by
setting bits SYNC and SPEN and clearing bit
CSRC.
2. If interrupts are desired, set enable bit RCIE.
3. If 9-bit reception is desired, set bit RX9.
4. To enable reception, set enable bit CREN.
5. Flag bit RCIF will be set when reception is complete.
An interrupt will be generated if enable bit
RCIE was 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
bit CREN.
9. If using interrupts, ensure that the GIE and PEIE
bits in the INTCON register (INTCON<7:6>) are
set.
TABLE 16-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
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
RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D 0000 -00x 0000 -00x
RCREG USART Receive Register 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, read as '0'.
Shaded cells are not used for Synchronous Slave Reception.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits
clear.© 2006 Microchip Technology Inc. DS39564C-page 181
PIC18FXX2
17.0 COMPATIBLE 10-BIT
ANALOG-TO-DIGITAL
CONVERTER (A/D) MODULE
The Analog-to-Digital (A/D) converter module has five
inputs for the PIC18F2X2 devices and eight for the
PIC18F4X2 devices. This module has the ADCON0
and ADCON1 register definitions that are compatible
with the mid-range A/D module.
The A/D allows conversion of an analog input signal to
a corresponding 10-bit digital number.
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 Register 0 (ADCON0)
• A/D Control Register 1 (ADCON1)
The ADCON0 register, shown in Register 17-1, controls
the operation of the A/D module. The ADCON1
register, shown in Register 17-2, configures the
functions of the port pins.
REGISTER 17-1: ADCON0 REGISTER
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0
ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE — ADON
bit 7 bit 0
bit 7-6 ADCS1:ADCS0: A/D Conversion Clock Select bits (ADCON0 bits in bold)
bit 5-3 CHS2:CHS0: Analog Channel Select bits
000 = channel 0, (AN0)
001 = channel 1, (AN1)
010 = channel 2, (AN2)
011 = channel 3, (AN3)
100 = channel 4, (AN4)
101 = channel 5, (AN5)
110 = channel 6, (AN6)
111 = channel 7, (AN7)
Note: The PIC18F2X2 devices do not implement the full 8 A/D channels; the unimplemented
selections are reserved. Do not select any unimplemented channel.
bit 2 GO/DONE: A/D Conversion Status bit
When ADON = 1:
1 = A/D conversion in progress (setting this bit starts the A/D conversion which is automatically
cleared by hardware when the A/D conversion is complete)
0 = A/D conversion not in progress
bit 1 Unimplemented: Read as '0'
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 ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
ADCON1
ADCON0
Clock Conversion
0 00 FOSC/2
0 01 FOSC/8
0 10 FOSC/32
0 11 FRC (clock derived from the internal A/D RC oscillator)
1 00 FOSC/4
1 01 FOSC/16
1 10 FOSC/64
1 11 FRC (clock derived from the internal A/D RC oscillator)PIC18FXX2
DS39564C-page 182 © 2006 Microchip Technology Inc.
REGISTER 17-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 0
bit 7 ADFM: A/D Result Format Select bit
1 = Right justified. Six (6) Most Significant bits of ADRESH are read as ’0’.
0 = Left justified. Six (6) Least Significant bits of ADRESL are read as ’0’.
bit 6 ADCS2: A/D Conversion Clock Select bit (ADCON1 bits in bold)
bit 5-4 Unimplemented: Read as '0'
bit 3-0 PCFG3:PCFG0: A/D Port Configuration Control bits
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknown
Note: On any device RESET, the port pins that are multiplexed with analog functions (ANx) are
forced to be an analog input.
ADCON1
ADCON0
Clock Conversion
0 00 FOSC/2
0 01 FOSC/8
0 10 FOSC/32
0 11 FRC (clock derived from the internal A/D RC oscillator)
1 00 FOSC/4
1 01 FOSC/16
1 10 FOSC/64
1 11 FRC (clock derived from the internal A/D RC oscillator)
A = Analog input D = Digital I/O
C/R = # of analog input channels / # of A/D voltage references
PCFG
<3:0> AN7 AN6 AN5 AN4 AN3 AN2 AN1 AN0 VREF+ VREF- C / R
0000 A AAA A A AAVDD VSS 8 / 0
0001 A A A AVREF+ A A A AN3 VSS 7 / 1
0010 DDDA A A AAVDD VSS 5 / 0
0011 D D D AVREF+ A A A AN3 VSS 4 / 1
0100 DDDD A D AAVDD VSS 3 / 0
0101 D D D DVREF+ D A A AN3 VSS 2 / 1
011x D D D D D D D D — — 0 / 0
1000 A A A AVREF+ VREF- A A AN3 AN2 6 / 2
1001 DDAA A A AAVDD VSS 6 / 0
1010 D D A AVREF+ A A A AN3 VSS 5 / 1
1011 D D A AVREF+ VREF- A A AN3 AN2 4 / 2
1100 D D D AVREF+ VREF- A A AN3 AN2 3 / 2
1101 D D D DVREF+ VREF- A A AN3 AN2 2 / 2
1110 DDDD D D DAVDD VSS 1 / 0
1111 D D D DVREF+ VREF- D A AN3 AN2 1 / 2© 2006 Microchip Technology Inc. DS39564C-page 183
PIC18FXX2
The analog reference voltage is software selectable to
either the device’s positive and negative supply voltage
(VDD and VSS), or the voltage level on the RA3/AN3/
VREF+ pin and RA2/AN2/VREF- pin.
The A/D converter has a unique feature of being able
to operate while the device is in SLEEP mode. To operate
in SLEEP, the A/D conversion clock must be
derived from the A/D’s internal RC oscillator.
The output of the sample and hold is the input into the
converter, which generates the result via successive
approximation.
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.
Each port pin associated with the A/D converter can be
configured as an analog input (RA3 can also be a
voltage reference) or as a digital I/O.
The ADRESH and ADRESL registers contain the result
of the A/D conversion. When the A/D conversion is
complete, the result is loaded into the ADRESH/
ADRESL registers, the GO/DONE bit (ADCON0<2>) is
cleared, and A/D interrupt flag bit, ADIF is set. The block
diagram of the A/D module is shown in Figure 17-1.
FIGURE 17-1: A/D BLOCK DIAGRAM
(Input Voltage)
VAIN
VREF+
Reference
Voltage
VDD
PCFG<3:0>
CHS<2:0>
AN7*
AN6*
AN5*
AN4
AN3
AN2
AN1
AN0
111
110
101
100
011
010
001
000
10-bit
Converter
VREFVSS
A/D
* These channels are implemented only on the PIC18F4X2 devices.PIC18FXX2
DS39564C-page 184 © 2006 Microchip Technology Inc.
The value that is in the ADRESH/ADRESL registers is
not modified for a Power-on Reset. The ADRESH/
ADRESL registers will contain unknown data after a
Power-on Reset.
After the A/D module has been configured as desired,
the selected channel must be acquired before the conversion
is started. The analog input channels must
have their corresponding TRIS bits selected as an
input. To determine acquisition time, see Section 17.1.
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 ADIF bit
• Set ADIE bit
• Set GIE bit
• Set PEIE bit
3. Wait the required acquisition time.
4. Start conversion:
• Set GO/DONE bit (ADCON0)
5. Wait for A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared
(interrupts disabled)
OR
• Waiting for the A/D interrupt
6. Read A/D Result registers (ADRESH/ADRESL);
clear bit ADIF if required.
7. For next conversion, go to step 1 or step 2 as
required. The A/D conversion time per bit is
defined as TAD. A minimum wait of 2 TAD is
required before the next acquisition starts.
17.1 A/D Acquisition Requirements
For the A/D converter to meet its specified accuracy,
the charge holding capacitor (CHOLD) must be allowed
to fully charge to the input channel voltage level. The
analog input model is shown in Figure 17-2. The
source impedance (RS) and the internal sampling
switch (RSS) impedance directly affect the time
required to charge the capacitor CHOLD. The sampling
switch (RSS) impedance varies over the device voltage
(VDD). 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Ω. After the analog input channel is
selected (changed), this acquisition must be done
before the conversion can be started.
FIGURE 17-2: ANALOG INPUT MODEL
Note: When the conversion is started, the holding
capacitor is disconnected from the
input pin.
VAIN CPIN
Rs ANx
5 pF
VDD
VT = 0.6V
VT = 0.6V I LEAKAGE
RIC ≤ 1k
Sampling
Switch
SS RSS
CHOLD = 120 pF
VSS
6V
Sampling Switch
5V
4V
3V
2V
5 6 7 8 9 10 11
(kΩ)
VDD
± 500 nA
Legend: CPIN
VT
I LEAKAGE
RIC
SS
CHOLD
= input capacitance
= threshold voltage
= leakage current at the pin due to
= interconnect resistance
= sampling switch
= sample/hold capacitance (from DAC)
various junctions© 2006 Microchip Technology Inc. DS39564C-page 185
PIC18FXX2
To calculate the minimum acquisition time,
Equation 17-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.
EQUATION 17-1: ACQUISITION TIME
EQUATION 17-2: A/D MINIMUM CHARGING TIME
Example 17-1 shows the calculation of the minimum
required acquisition time, TACQ. This calculation is
based on the following application system assumptions:
• CHOLD = 120 pF
• Rs = 2.5 kΩ
• Conversion Error ≤ 1/2 LSb
• VDD = 5V → Rss = 7 kΩ
• Temperature = 50°C (system max.)
• VHOLD = 0V @ time = 0
EXAMPLE 17-1: CALCULATING THE MINIMUM REQUIRED ACQUISITION TIME
TACQ = Amplifier Settling Time + Holding Capacitor Charging Time + Temperature Coefficient
= TAMP + TC + TCOFF
VHOLD = (VREF – (VREF/2048)) • (1 – e(-Tc/CHOLD(RIC + RSS + RS)))
or
TC = -(120 pF)(1 kΩ + RSS + RS) ln(1/2048)
TACQ = TAMP + TC + 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/2048)
-120 pF (1 kΩ + 7 kΩ + 2.5 kΩ) ln(0.0004883)
-120 pF (10.5 kΩ) ln(0.0004883)
-1.26 μs (-7.6246)
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 μsPIC18FXX2
DS39564C-page 186 © 2006 Microchip Technology Inc.
17.2 Selecting the A/D Conversion Clock
The A/D conversion time per bit is defined as TAD. The
A/D conversion requires 12 TAD per 10-bit conversion.
The source of the A/D conversion clock is software
selectable. The seven possible options for TAD are:
• 2 TOSC
• 4 TOSC
• 8 TOSC
• 16 TOSC
• 32 TOSC
• 64 TOSC
• Internal A/D module RC oscillator (2-6 μs)
For correct A/D conversions, the A/D conversion clock
(TAD) must be selected to ensure a minimum TAD time
of 1.6 μs.
Table 17-1 shows the resultant TAD times derived from
the device operating frequencies and the A/D clock
source selected.
17.3 Configuring Analog Port Pins
The ADCON1, TRISA and TRISE 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.
The A/D operation is independent of the state of the
CHS2:CHS0 bits and the TRIS bits.
TABLE 17-1: TAD vs. DEVICE OPERATING FREQUENCIES
Note 1: When reading the port register, all pins configured
as analog input channels 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 AN4:AN0
pins) may cause the input buffer to consume
current that is out of the device’s
specification.
AD Clock Source (TAD) Maximum Device Frequency
Operation ADCS2:ADCS0 PIC18FXX2 PIC18LFXX2
2 TOSC 000 1.25 MHz 666 kHz
4 TOSC 100 2.50 MHz 1.33 MHz
8 TOSC 001 5.00 MHz 2.67 MHz
16 TOSC 101 10.00 MHz 5.33 MHz
32 TOSC 010 20.00 MHz 10.67 MHz
64 TOSC 110 40.00 MHz 21.33 MHz
RC 011 — —© 2006 Microchip Technology Inc. DS39564C-page 187
PIC18FXX2
17.4 A/D Conversions
Figure 17-3 shows the operation of the A/D converter
after the GO bit has been set. 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 2 TAD wait
is required before the next acquisition is started. After
this 2 TAD wait, acquisition on the selected channel is
automatically started. The GO/DONE bit can then be
set to start the conversion.
FIGURE 17-3: A/D CONVERSION TAD CYCLES
17.4.1 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 17-4 shows the operation of the A/D result justification.
The extra bits are loaded with ’0’s. When an
A/D result will not overwrite these locations (A/D
disable), these registers may be used as two general
purpose 8-bit registers.
FIGURE 17-4: A/D RESULT JUSTIFICATION
Note: The GO/DONE bit should NOT be set in
the same instruction that turns on the A/D.
TAD1 TAD2 TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD11
Set GO bit
Holding capacitor is disconnected from analog input (typically 100 ns)
b9 b8 b7 b6 b5 b4 b3 b2
TAD9 TAD10
b1 b0
TCY - TAD
Next Q4: ADRESH/ADRESL is loaded, GO bit is cleared,
ADIF bit is set, holding capacitor is connected to analog input.
Conversion Starts
b0
10-bit Result
ADRESH ADRESL
0000 00
ADFM = 0
7 2 1 0 7 0
10-bit Result
ADRESH ADRESL
10-bit Result
0000 00
7 0 7 6 5 0
ADFM = 1
Right Justified Left JustifiedPIC18FXX2
DS39564C-page 188 © 2006 Microchip Technology Inc.
17.5 Use of the CCP2 Trigger
An A/D conversion can be started by the “special event
trigger” of the CCP2 module. This requires that the
CCP2M3:CCP2M0 bits (CCP2CON<3:0>) be programmed
as 1011 and that the A/D module is enabled
(ADON bit is set). When the trigger occurs, the GO/
DONE bit will be set, starting the A/D conversion, and
the Timer1 (or Timer3) counter will be reset to zero.
Timer1 (or Timer3) is reset to automatically repeat the
A/D acquisition period with minimal software overhead
(moving ADRESH/ADRESL to the desired location).
The appropriate analog input channel must be selected
and the minimum acquisition done before the “special
event trigger” sets the GO/DONE bit (starts a
conversion).
If the A/D module is not enabled (ADON is cleared), the
“special event trigger” will be ignored by the A/D
module, but will still reset the Timer1 (or Timer3)
counter.
TABLE 17-2: SUMMARY OF A/D REGISTERS
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
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
PIR2 — — — EEIF BCLIF LVDIF TMR3IF CCP2IF ---0 0000 ---0 0000
PIE2 — — — EEIE BCLIE LVDIE TMR3IE CCP2IE ---0 0000 ---0 0000
IPR2 — — — EEIP BCLIP LVDIP TMR3IP CCP2IP ---1 1111 ---1 0000
ADRESH A/D Result Register xxxx xxxx uuuu uuuu
ADRESL A/D Result Register xxxx xxxx uuuu uuuu
ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE — ADON 0000 00-0 0000 00-0
ADCON1 ADFM ADCS2 — — PCFG3 PCFG2 PCFG1 PCFG0 ---- -000 ---- -000
PORTA — RA6 RA5 RA4 RA3 RA2 RA1 RA0 --0x 0000 --0u 0000
TRISA — PORTA Data Direction Register --11 1111 --11 1111
PORTE — — — — — RE2 RE1 RE0 ---- -000 ---- -000
LATE — — — — — LATE2 LATE1 LATE0 ---- -xxx ---- -uuu
TRISE IBF OBF IBOV PSPMODE — PORTE Data Direction bits 0000 -111 0000 -111
Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used for A/D conversion.
Note 1: The PSPIF, PSPIE and PSPIP bits are reserved on the PIC18F2X2 devices; always maintain these bits clear.© 2006 Microchip Technology Inc. DS39564C-page 189
PIC18FXX2
18.0 LOW VOLTAGE DETECT
In many applications, the ability to determine if the
device voltage (VDD) 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 a software programmable circuitry,
where a device voltage trip point can be specified.
When the voltage of the device becomes lower then 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 18-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 the time,
until the device voltage is no longer in valid operating
range, to shutdown the system. Voltage point VB is the
minimum valid operating voltage specification. This
occurs at time TB. The difference TB - TA is the total
time for shutdown.
FIGURE 18-1: TYPICAL LOW VOLTAGE DETECT APPLICATION
The block diagram for the LVD module is shown in
Figure 18-2. 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 than), the LVDIF bit is set.
Each node in the resistor 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 1.2V
internal reference voltage generated by the 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 18-2). The trip point is selected by
programming the LVDL3:LVDL0 bits (LVDCON<3:0>).
Time
Voltage
VA
VB
TA TB
VA = LVD trip point
VB = Minimum valid device
operating voltage
Legend:PIC18FXX2
DS39564C-page 190 © 2006 Microchip Technology Inc.
FIGURE 18-2: LOW VOLTAGE DETECT (LVD) BLOCK DIAGRAM
The LVD module has an additional feature that allows
the user to supply the trip voltage to the module from
an external source. This mode is enabled when bits
LVDL3:LVDL0 are set to 1111. In this state, the comparator
input is multiplexed from the external input pin,
LVDIN (Figure 18-3). This gives users flexibility,
because it allows them to configure the Low Voltage
Detect interrupt to occur at any voltage in the valid
operating range.
FIGURE 18-3: LOW VOLTAGE DETECT (LVD) WITH EXTERNAL INPUT BLOCK DIAGRAM
LVDIF
VDD
16 to 1 MUX
LVDEN
LVD Control
Register
Internally Generated
Reference Voltage
LVDIN
1.2V Typical
–
+
LVD
EN
LVD Control
16 to 1 MUX
BGAP
BODEN
LVDEN
VxEN
LVDIN
Register
VDD
VDD
Externally Generated
Trip Point –
+© 2006 Microchip Technology Inc. DS39564C-page 191
PIC18FXX2
18.1 Control Register
The Low Voltage Detect Control register controls the
operation of the Low Voltage Detect circuitry.
REGISTER 18-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 the 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
1111 = External analog input is used (input comes from the LVDIN pin)
1110 = 4.5V - 4.77V
1101 = 4.2V - 4.45V
1100 = 4.0V - 4.24V
1011 = 3.8V - 4.03V
1010 = 3.6V - 3.82V
1001 = 3.5V - 3.71V
1000 = 3.3V - 3.50V
0111 = 3.0V - 3.18V
0110 = 2.8V - 2.97V
0101 = 2.7V - 2.86V
0100 = 2.5V - 2.65V
0011 = 2.4V - 2.54V
0010 = 2.2V - 2.33V
0001 = 2.0V - 2.12V
0000 = Reserved
Note: LVDL3:LVDL0 modes which result in a trip point below the valid operating voltage
of the device are not tested.
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
- n = Value at POR ’1’ = Bit is set ’0’ = Bit is cleared x = Bit is unknownPIC18FXX2
DS39564C-page 192 © 2006 Microchip Technology Inc.
18.2 Operation
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.
The following steps are needed to set up 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 until the LVD module has
stabilized (clear the LVDIF bit).
6. Enable the LVD interrupt (set the LVDIE and the
GIE bits).
Figure 18-4 shows typical waveforms that the LVD
module may be used to detect.
FIGURE 18-4: LOW VOLTAGE DETECT WAVEFORMS
VLVD
VDD
LVDIF
VLVD
VDD
Enable LVD
Internally Generated TIVRST
LVDIF may not be set
Enable LVD
LVDIF
LVDIF cleared in software
LVDIF cleared in software
LVDIF cleared in software,
CASE 1:
CASE 2:
LVDIF remains set since LVD condition still exists
Reference Stable
Internally Generated
Reference Stable
TIVRST© 2006 Microchip Technology Inc. DS39564C-page 193
PIC18FXX2
18.2.1 REFERENCE VOLTAGE SET POINT
The Internal Reference Voltage of the LVD module may
be used by other internal circuitry (the Programmable
Brown-out Reset). If these circuits are disabled (lower
current consumption), the reference voltage circuit
requires a time to become stable before a low voltage
condition can be reliably detected. This time is invariant
of system clock speed. This start-up 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 waveform in Figure 18-4.
18.2.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.
18.3 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 wakeup
from SLEEP. Device execution will continue from
the interrupt vector address if interrupts have been
globally enabled.
18.4 Effects of a RESET
A device RESET forces all registers to their RESET
state. This forces the LVD module to be turned off. PIC18FXX2
DS39564C-page 194 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 195
PIC18FXX2
19.0 SPECIAL FEATURES OF THE
CPU
There are several features intended to maximize system
reliability, minimize cost through elimination of
external components, provide power saving Operating
modes and offer code protection. These are:
• OSC Selection
• RESET
- Power-on Reset (POR)
- Power-up Timer (PWRT)
- Oscillator Start-up Timer (OST)
- Brown-out Reset (BOR)
• Interrupts
• Watchdog Timer (WDT)
• SLEEP
• Code Protection
• ID Locations
• In-Circuit Serial Programming
All PIC18FXX2 devices have a Watchdog Timer, which
is permanently enabled via the configuration bits or
software controlled. It runs off its own RC oscillator for
added reliability. There are two timers that offer necessary
delays on power-up. One is the Oscillator Start-up
Timer (OST), intended to keep the chip in RESET until
the crystal oscillator is stable. The other is the Powerup
Timer (PWRT), which provides a fixed delay on
power-up only, designed to keep the part in RESET
while the power supply stabilizes. With these two timers
on-chip, most applications need no external
RESET circuitry.
SLEEP mode is designed to offer a very low current
Power-down mode. The user can wake-up from
SLEEP through external RESET, Watchdog Timer
Wake-up or through an interrupt. Several oscillator
options are also made available to allow the part to fit
the application. The RC oscillator option saves system
cost, while the LP crystal option saves power. A set of
configuration bits are used to select various options.
19.1 Configuration Bits
The configuration bits can be programmed (read as '0'),
or left unprogrammed (read as '1'), to select various
device configurations. These bits are mapped starting
at program memory location 300000h.
The user will note that address 300000h is beyond the
user program memory space. In fact, it belongs to the
configuration memory space (300000h - 3FFFFFh),
which can only be accessed using Table Reads and
Table Writes.
Programming the configuration registers is done in a
manner similar to programming the FLASH memory
(see Section 5.5.1). The only difference is the configuration
registers are written a byte at a time. The
sequence of events for programming configuration
registers is:
1. Load table pointer with address of configuration
register being written.
2. Write a single byte using the TBLWT instruction.
3. Set EEPGD to point to program memory, set the
CFGS bit to access configuration registers, and
set WREN to enable byte writes.
4. Disable interrupts.
5. Write 55h to EECON2.
6. Write AAh to EECON2.
7. Set the WR bit. This will begin the write cycle.
8. CPU will stall for duration of write (approximately
2 ms using internal timer).
9. Execute a NOP.
10. Re-enable interrupts.PIC18FXX2
DS39564C-page 196 © 2006 Microchip Technology Inc.
TABLE 19-1: CONFIGURATION BITS AND DEVICE IDS
REGISTER 19-1: CONFIGURATION REGISTER 1 HIGH (CONFIG1H: BYTE ADDRESS 300001h)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Default/
Unprogrammed
Value
300001h CONFIG1H — — OSCSEN — — FOSC2 FOSC1 FOSC0 --1- -111
300002h CONFIG2L — — — — BORV1 BORV0 BOREN PWRTEN ---- 1111
300003h CONFIG2H — — — — WDTPS2 WDTPS1 WDTPS0 WDTEN ---- 1111
300005h CONFIG3H — — — — — — — CCP2MX ---- ---1
300006h CONFIG4L DEBUG — — — — LVP — STVREN 1--- -1-1
300008h CONFIG5L — — — — CP3 CP2 CP1 CP0 ---- 1111
300009h CONFIG5H CPD CPB — — — — — — 11-- ----
30000Ah CONFIG6L — — — — WRT3 WRT2 WRT1 WRT0 ---- 1111
30000Bh CONFIG6H WRTD WRTB WRTC — — — — — 111- ----
30000Ch CONFIG7L — — — — EBTR3 EBTR2 EBTR1 EBTR0 ---- 1111
30000Dh CONFIG7H — EBTRB — — — — — — -1-- ----
3FFFFEh DEVID1 DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0 (1)
3FFFFFh DEVID2 DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3 0000 0100
Legend: x = unknown, u = unchanged, - = unimplemented, q = value depends on condition.
Shaded cells are unimplemented, read as ‘0’.
Note 1: See Register 19-12 for DEVID1 values.
U-0 U-0 R/P-1 U-0 U-0 R/P-1 R/P-1 R/P-1
— — OSCSEN — — FOSC2 FOSC1 FOSC0
bit 7 bit 0
bit 7-6 Unimplemented: Read as ‘0’
bit 5 OSCSEN: Oscillator System Clock Switch Enable bit
1 = Oscillator system clock switch option is disabled (main oscillator is source)
0 = Oscillator system clock switch option is enabled (oscillator switching is enabled)
bit 4-3 Unimplemented: Read as ‘0’
bit 2-0 FOSC2:FOSC0: Oscillator Selection bits
111 = RC oscillator w/ OSC2 configured as RA6
110 = HS oscillator with PLL enabled/Clock frequency = (4 x FOSC)
101 = EC oscillator w/ OSC2 configured as RA6
100 = EC oscillator w/ OSC2 configured as divide-by-4 clock output
011 = RC oscillator
010 = HS oscillator
001 = XT oscillator
000 = LP oscillator
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state© 2006 Microchip Technology Inc. DS39564C-page 197
PIC18FXX2
REGISTER 19-2: CONFIGURATION REGISTER 2 LOW (CONFIG2L: BYTE ADDRESS 300002h)
REGISTER 19-3: CONFIGURATION REGISTER 2 HIGH (CONFIG2H: BYTE ADDRESS 300003h)
U-0 U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1
— — — — BORV1 BORV0 BOREN PWRTEN
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3-2 BORV1:BORV0: Brown-out Reset Voltage bits
11 = VBOR set to 2.5V
10 = VBOR set to 2.7V
01 = VBOR set to 4.2V
00 = VBOR set to 4.5V
bit 1 BOREN: Brown-out Reset Enable bit
1 = Brown-out Reset enabled
0 = Brown-out Reset disabled
bit 0 PWRTEN: Power-up Timer Enable bit
1 = PWRT disabled
0 = PWRT enabled
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
U-0 U-0 U-0 U-0 R/P-1 R/P-1 R/P-1 R/P-1
— — — — WDTPS2 WDTPS1 WDTPS0 WDTEN
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3-1 WDTPS2:WDTPS0: Watchdog Timer Postscale Select bits
111 = 1:128
110 = 1:64
101 = 1:32
100 = 1:16
011 = 1:8
010 = 1:4
001 = 1:2
000 = 1:1
bit 0 WDTEN: Watchdog Timer Enable bit
1 = WDT enabled
0 = WDT disabled (control is placed on the SWDTEN bit)
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed statePIC18FXX2
DS39564C-page 198 © 2006 Microchip Technology Inc.
REGISTER 19-4: CONFIGURATION REGISTER 3 HIGH (CONFIG3H: BYTE ADDRESS 300005h)
REGISTER 19-5: CONFIGURATION REGISTER 4 LOW (CONFIG4L: BYTE ADDRESS 300006h)
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/P-1
— — — — — — — CCP2MX
bit 7 bit 0
bit 7-1 Unimplemented: Read as ‘0’
bit 0 CCP2MX: CCP2 Mux bit
1 = CCP2 input/output is multiplexed with RC1
0 = CCP2 input/output is multiplexed with RB3
Legend:
R = Readable bit P = Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
R/P-1 U-0 U-0 U-0 U-0 R/P-1 U-0 R/P-1
BKBUG — — — — LVP — STVREN
bit 7 bit 0
bit 7 DEBUG: Background Debugger Enable bit
1 = Background Debugger disabled. RB6 and RB7 configured as general purpose I/O pins.
0 = Background Debugger enabled. RB6 and RB7 are dedicated to In-Circuit Debug.
bit 6-3 Unimplemented: Read as ‘0’
bit 2 LVP: Low Voltage ICSP Enable bit
1 = Low Voltage ICSP enabled
0 = Low Voltage ICSP disabled
bit 1 Unimplemented: Read as ‘0’
bit 0 STVREN: Stack Full/Underflow Reset Enable bit
1 = Stack Full/Underflow will cause RESET
0 = Stack Full/Underflow will not cause RESET
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state© 2006 Microchip Technology Inc. DS39564C-page 199
PIC18FXX2
REGISTER 19-6: CONFIGURATION REGISTER 5 LOW (CONFIG5L: BYTE ADDRESS 300008h)
REGISTER 19-7: CONFIGURATION REGISTER 5 HIGH (CONFIG5H: BYTE ADDRESS 300009h)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — CP3(1) CP2(1) CP1 CP0
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3 CP3: Code Protection bit(1)
1 = Block 3 (006000-007FFFh) not code protected
0 = Block 3 (006000-007FFFh) code protected
bit 2 CP2: Code Protection bit(1)
1 = Block 2 (004000-005FFFh) not code protected
0 = Block 2 (004000-005FFFh) code protected
bit 1 CP1: Code Protection bit
1 = Block 1 (002000-003FFFh) not code protected
0 = Block 1 (002000-003FFFh) code protected
bit 0 CP0: Code Protection bit
1 = Block 0 (000200-001FFFh) not code protected
0 = Block 0 (000200-001FFFh) code protected
Note 1: Unimplemented in PIC18FX42 devices; maintain this bit set.
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
R/C-1 R/C-1 U-0 U-0 U-0 U-0 U-0 U-0
CPD CPB — — — — — —
bit 7 bit 0
bit 7 CPD: Data EEPROM Code Protection bit
1 = Data EEPROM not code protected
0 = Data EEPROM code protected
bit 6 CPB: Boot Block Code Protection bit
1 = Boot Block (000000-0001FFh) not code protected
0 = Boot Block (000000-0001FFh) code protected
bit 5-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed statePIC18FXX2
DS39564C-page 200 © 2006 Microchip Technology Inc.
REGISTER 19-8: CONFIGURATION REGISTER 6 LOW (CONFIG6L: BYTE ADDRESS 30000Ah)
REGISTER 19-9: CONFIGURATION REGISTER 6 HIGH (CONFIG6H: BYTE ADDRESS 30000Bh)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — WRT3(1) WRT2(1) WRT1 WRT0
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3 WRT3: Write Protection bit(1)
1 = Block 3 (006000-007FFFh) not write protected
0 = Block 3 (006000-007FFFh) write protected
bit 2 WRT2: Write Protection bit(1)
1 = Block 2 (004000-005FFFh) not write protected
0 = Block 2 (004000-005FFFh) write protected
bit 1 WRT1: Write Protection bit
1 = Block 1 (002000-003FFFh) not write protected
0 = Block 1 (002000-003FFFh) write protected
bit 0 WRT0: Write Protection bit
1 = Block 0 (000200h-001FFFh) not write protected
0 = Block 0 (000200h-001FFFh) write protected
Note 1: Unimplemented in PIC18FX42 devices; maintain this bit set.
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
R/C-1 R/C-1 C-1 U-0 U-0 U-0 U-0 U-0
WRTD WRTB WRTC — — — — —
bit 7 bit 0
bit 7 WRTD: Data EEPROM Write Protection bit
1 = Data EEPROM not write protected
0 = Data EEPROM write protected
bit 6 WRTB: Boot Block Write Protection bit
1 = Boot Block (000000-0001FFh) not write protected
0 = Boot Block (000000-0001FFh) write protected
bit 5 WRTC: Configuration Register Write Protection bit
1 = Configuration registers (300000-3000FFh) not write protected
0 = Configuration registers (300000-3000FFh) write protected
Note: This bit is read only, and cannot be changed in User mode.
bit 4-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit C =Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state© 2006 Microchip Technology Inc. DS39564C-page 201
PIC18FXX2
REGISTER 19-10: CONFIGURATION REGISTER 7 LOW (CONFIG7L: BYTE ADDRESS 30000Ch)
REGISTER 19-11: CONFIGURATION REGISTER 7 HIGH (CONFIG7H: BYTE ADDRESS 30000Dh)
U-0 U-0 U-0 U-0 R/C-1 R/C-1 R/C-1 R/C-1
— — — — EBTR3(1) EBTR2(1) EBTR1 EBTR0
bit 7 bit 0
bit 7-4 Unimplemented: Read as ‘0’
bit 3 EBTR3: Table Read Protection bit(1)
1 = Block 3 (006000-007FFFh) not protected from Table Reads executed in other blocks
0 = Block 3 (006000-007FFFh) protected from Table Reads executed in other blocks
bit 2 EBTR2: Table Read Protection bit(1)
1 = Block 2 (004000-005FFFh) not protected from Table Reads executed in other blocks
0 = Block 2 (004000-005FFFh) protected from Table Reads executed in other blocks
bit 1 EBTR1: Table Read Protection bit
1 = Block 1 (002000-003FFFh) not protected from Table Reads executed in other blocks
0 = Block 1 (002000-003FFFh) protected from Table Reads executed in other blocks
bit 0 EBTR0: Table Read Protection bit
1 = Block 0 (000200h-001FFFh) not protected from Table Reads executed in other blocks
0 = Block 0 (000200h-001FFFh) protected from Table Reads executed in other blocks
Note 1: Unimplemented in PIC18FX42 devices; maintain this bit set.
Legend:
R = Readable bit C = Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
U-0 R/C-1 U-0 U-0 U-0 U-0 U-0 U-0
— EBTRB — — — — — —
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6 EBTRB: Boot Block Table Read Protection bit
1 = Boot Block (000000-0001FFh) not protected from Table Reads executed in other blocks
0 = Boot Block (000000-0001FFh) protected from Table Reads executed in other blocks
bit 5-0 Unimplemented: Read as ‘0’
Legend:
R = Readable bit C =Clearable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed statePIC18FXX2
DS39564C-page 202 © 2006 Microchip Technology Inc.
REGISTER 19-12: DEVICE ID REGISTER 1 FOR PIC18FXX2 (DEVID1: BYTE ADDRESS 3FFFFEh)
REGISTER 19-13: DEVICE ID REGISTER 2 FOR PIC18FXX2 (DEVID2: BYTE ADDRESS 3FFFFFh)
RRRRRRRR
DEV2 DEV1 DEV0 REV4 REV3 REV2 REV1 REV0
bit 7 bit 0
bit 7-5 DEV2:DEV0: Device ID bits
000 = PIC18F252
001 = PIC18F452
100 = PIC18F242
101 = PIC18F442
bit 4-0 REV4:REV0: Revision ID bits
These bits are used to indicate the device revision.
Legend:
R = Readable bit P =Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state
RRRRRRRR
DEV10 DEV9 DEV8 DEV7 DEV6 DEV5 DEV4 DEV3
bit 7 bit 0
bit 7-0 DEV10:DEV3: Device ID bits
These bits are used with the DEV2:DEV0 bits in the Device ID Register 1 to identify the
part number.
Legend:
R = Readable bit P =Programmable bit U = Unimplemented bit, read as ‘0’
- n = Value when device is unprogrammed u = Unchanged from programmed state© 2006 Microchip Technology Inc. DS39564C-page 203
PIC18FXX2
19.2 Watchdog Timer (WDT)
The Watchdog Timer is a free running on-chip RC oscillator,
which does not require any external components.
This RC oscillator is separate from the RC oscillator of
the OSC1/CLKI pin. That means that the WDT will run,
even if the clock on the OSC1/CLKI and OSC2/CLKO/
RA6 pins of the device has been stopped, for example,
by execution of a SLEEP instruction.
During normal operation, a WDT time-out generates a
device RESET (Watchdog Timer Reset). If the device is
in SLEEP mode, a WDT time-out causes the device to
wake-up and continue with normal operation (Watchdog
Timer Wake-up). The TO bit in the RCON register
will be cleared upon a WDT time-out.
The Watchdog Timer is enabled/disabled by a device
configuration bit. If the WDT is enabled, software execution
may not disable this function. When the WDTEN
configuration bit is cleared, the SWDTEN bit enables/
disables the operation of the WDT.
The WDT time-out period values may be found in the
Electrical Specifications (Section 22.0) under parameter
D031. Values for the WDT postscaler may be
assigned using the configuration bits.
19.2.1 CONTROL REGISTER
Register 19-14 shows the WDTCON register. This is a
readable and writable register, which contains a control
bit that allows software to override the WDT enable
configuration bit, only when the configuration bit has
disabled the WDT.
REGISTER 19-14: WDTCON REGISTER
Note: The CLRWDT and SLEEP instructions clear
the WDT and the postscaler, if assigned to
the WDT and prevent it from timing out and
generating a device RESET condition.
Note: When a CLRWDT instruction is executed
and the postscaler is assigned to the WDT,
the postscaler count will be cleared, but the
postscaler assignment is not changed.
U-0 U-0 U-0 U-0 U-0 U-0 U-0 R/W-0
— — — — — — — SWDTEN
bit 7 bit 0
bit 7-1 Unimplemented: Read as ’0’
bit 0 SWDTEN: Software Controlled Watchdog Timer Enable bit
1 = Watchdog Timer is on
0 = Watchdog Timer is turned off if the WDTEN configuration bit in the configuration
register = ‘0’
Legend:
R = Readable bit W = Writable bit
U = Unimplemented bit, read as ‘0’ - n = Value at PORPIC18FXX2
DS39564C-page 204 © 2006 Microchip Technology Inc.
19.2.2 WDT POSTSCALER
The WDT has a postscaler that can extend the WDT
Reset period. The postscaler is selected at the time of
the device programming, by the value written to the
CONFIG2H configuration register.
FIGURE 19-1: WATCHDOG TIMER BLOCK DIAGRAM
TABLE 19-2: SUMMARY OF WATCHDOG TIMER REGISTERS
WDT Timer Postscaler
WDTEN
8 - to - 1 MUX WDTPS2:WDTPS0
WDT
Time-out
8
SWDTEN bit
Configuration bit
Note: WDPS2:WDPS0 are bits in register CONFIG2H.
Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
CONFIG2H — — — — WDTPS2 WDTPS2 WDTPS0 WDTEN
RCON IPEN — — RI TO PD POR BOR
WDTCON — — — — — — — SWDTEN
Legend: Shaded cells are not used by the Watchdog Timer.© 2006 Microchip Technology Inc. DS39564C-page 205
PIC18FXX2
19.3 Power-down Mode (SLEEP)
Power-down mode is entered by executing a SLEEP
instruction.
If enabled, the Watchdog Timer will be cleared, but
keeps running, the PD bit (RCON<3>) is cleared, the
TO (RCON<4>) bit is set, and the oscillator driver is
turned off. The I/O ports maintain the status they had
before the SLEEP instruction was executed (driving
high, low or hi-impedance).
For lowest current consumption in this mode, place all
I/O pins at either VDD or VSS, ensure no external circuitry
is drawing current from the I/O pin, power-down
the A/D and disable external clocks. Pull all I/O pins
that are hi-impedance inputs, high or low externally, to
avoid switching currents caused by floating inputs. The
T0CKI input should also be at VDD or VSS for lowest
current consumption. The contribution from on-chip
pull-ups on PORTB should be considered.
The MCLR pin must be at a logic high level (VIHMC).
19.3.1 WAKE-UP FROM SLEEP
The device can wake-up from SLEEP through one of
the following events:
1. External RESET input on MCLR pin.
2. Watchdog Timer Wake-up (if WDT was
enabled).
3. Interrupt from INT pin, RB port change or a
Peripheral Interrupt.
The following peripheral interrupts can wake the device
from SLEEP:
1. PSP read or write.
2. TMR1 interrupt. Timer1 must be operating as
an asynchronous counter.
3. TMR3 interrupt. Timer3 must be operating as
an asynchronous counter.
4. CCP Capture mode interrupt.
5. Special event trigger (Timer1 in Asynchronous
mode using an external clock).
6. MSSP (START/STOP) bit detect interrupt.
7. MSSP transmit or receive in Slave mode
(SPI/I2C).
8. USART RX or TX (Synchronous Slave mode).
9. A/D conversion (when A/D clock source is RC).
10. EEPROM write operation complete.
11. LVD interrupt.
Other peripherals cannot generate interrupts, since
during SLEEP, no on-chip clocks are present.
External MCLR Reset will cause a device RESET. All
other events are considered a continuation of program
execution and will cause a “wake-up”. The TO and PD
bits in the RCON register can be used to determine the
cause of the device RESET. The PD bit, which is set on
power-up, is cleared when SLEEP is invoked. The TO
bit is cleared, if a WDT time-out occurred (and caused
wake-up).
When the SLEEP instruction is being executed, the next
instruction (PC + 2) is pre-fetched. For the device to
wake-up through an interrupt event, the corresponding
interrupt enable bit must be set (enabled). Wake-up is
regardless of the state of the GIE bit. If the GIE bit is
clear (disabled), the device continues execution at the
instruction after the SLEEP instruction. If the GIE bit is
set (enabled), the device executes the instruction after
the SLEEP instruction and then branches to the interrupt
address. In cases where the execution of the
instruction following SLEEP is not desirable, the user
should have a NOP after the SLEEP instruction.
19.3.2 WAKE-UP USING INTERRUPTS
When global interrupts are disabled (GIE cleared) and
any interrupt source has both its interrupt enable bit
and interrupt flag bit set, one of the following will occur:
• If an interrupt condition (interrupt flag bit and interrupt
enable bits are set) occurs before the execution
of a SLEEP instruction, the SLEEP instruction
will complete as a NOP. Therefore, the WDT and
WDT postscaler will not be cleared, the TO bit will
not be set and PD bits will not be cleared.
• If the interrupt condition occurs during or after
the execution of a SLEEP instruction, the device
will immediately wake-up from SLEEP. The
SLEEP instruction will be completely executed
before the wake-up. Therefore, the WDT and
WDT postscaler will be cleared, the TO bit will be
set and the PD bit will be cleared.
Even if the flag bits were checked before executing a
SLEEP instruction, it may be possible for flag bits to
become set before the SLEEP instruction completes. To
determine whether a SLEEP instruction executed, test
the PD bit. If the PD bit is set, the SLEEP instruction
was executed as a NOP.
To ensure that the WDT is cleared, a CLRWDT instruction
should be executed before a SLEEP instruction.PIC18FXX2
DS39564C-page 206 © 2006 Microchip Technology Inc.
FIGURE 19-2: WAKE-UP FROM SLEEP THROUGH INTERRUPT(1,2)
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
OSC1
CLKO(4)
INT pin
INTF flag
(INTCON<1>)
GIEH bit
(INTCON<7>)
INSTRUCTION FLOW
PC
Instruction
Fetched
Instruction
Executed
PC PC+2 PC+4
Inst(PC) = SLEEP
Inst(PC - 1)
Inst(PC + 2)
SLEEP
Processor in
SLEEP
Interrupt Latency(3)
Inst(PC + 4)
Inst(PC + 2)
Inst(0008h) Inst(000Ah)
Dummy Cycle Inst(0008h)
PC + 4 0008h 000Ah
Dummy Cycle
TOST(2)
PC+4
Note 1: XT, HS or LP Oscillator mode assumed.
2: GIE = '1' assumed. In this case, after wake-up, the processor jumps to the interrupt routine. If GIE = '0', execution will continue in-line.
3: TOST = 1024 TOSC (drawing not to scale). This delay will not occur for RC and EC Osc modes.
4: CLKO is not available in these Osc modes, but shown here for timing reference.© 2006 Microchip Technology Inc. DS39564C-page 207
PIC18FXX2
19.4 Program Verification and
Code Protection
The overall structure of the code protection on the
PIC18 FLASH devices differs significantly from other
PICmicro devices.
The user program memory is divided into five blocks.
One of these is a boot block of 512 bytes. The remainder
of the memory is divided into four blocks on binary
boundaries.
Each of the five blocks has three code protection bits
associated with them. They are:
• Code Protect bit (CPn)
• Write Protect bit (WRTn)
• External Block Table Read bit (EBTRn)
Figure 19-3 shows the program memory organization
for 16- and 32-Kbyte devices, and the specific code
protection bit associated with each block. The actual
locations of the bits are summarized in Table 19-3.
FIGURE 19-3: CODE PROTECTED PROGRAM MEMORY FOR PIC18F2XX/4XX
TABLE 19-3: SUMMARY OF CODE PROTECTION REGISTERS
MEMORY SIZE/DEVICE
Block Code Protection
16 Kbytes Controlled By:
(PIC18FX42)
32 Kbytes
(PIC18FX52)
Address
Range
Boot Block Boot Block 000000h
0001FFh CPB, WRTB, EBTRB
Block 0 Block 0
000200h
001FFFh
CP0, WRT0, EBTR0
Block 1 Block 1
002000h
003FFFh
CP1, WRT1, EBTR1
Unimplemented
Read 0’s Block 2
004000h
005FFFh
CP2, WRT2, EBTR2
Unimplemented
Read 0’s Block 3
006000h
007FFFh
CP3, WRT3, EBTR3
Unimplemented
Read 0’s
Unimplemented
Read 0’s
008000h
1FFFFFh
(Unimplemented Memory Space)
File Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
300008h CONFIG5L — — — — CP3 CP2 CP1 CP0
300009h CONFIG5H CPD CPB — — — — — —
30000Ah CONFIG6L — — — — WRT3 WRT2 WRT1 WRT0
30000Bh CONFIG6H WRTD WRTB WRTC — — — — —
30000Ch CONFIG7L — — — — EBTR3 EBTR2 EBTR1 EBTR0
30000Dh CONFIG7H — EBTRB — — — — — —
Legend: Shaded cells are unimplemented.PIC18FXX2
DS39564C-page 208 © 2006 Microchip Technology Inc.
19.4.1 PROGRAM MEMORY
CODE PROTECTION
The user memory may be read to or written from any
location using the Table Read and Table Write instructions.
The device ID may be read with Table Reads.
The configuration registers may be read and written
with the Table Read and Table Write instructions.
In User mode, the CPn bits have no direct effect. CPn
bits inhibit external reads and writes. A block of user
memory may be protected from Table Writes if the
WRTn configuration bit is ‘0’. The EBTRn bits control
Table Reads. For a block of user memory with the
EBTRn bit set to ‘0’, a Table Read instruction that
executes from within that block is allowed to read. A
Table Read instruction that executes from a location
outside of that block is not allowed to read, and will
result in reading ‘0’s. Figures 19-4 through 19-6
illustrate Table Write and Table Read protection.
FIGURE 19-4: TABLE WRITE (WRTn) DISALLOWED
Note: Code protection bits may only be written to
a ‘0’ from a ‘1’ state. It is not possible to
write a ‘1’ to a bit in the ‘0’ state. Code protection
bits are only set to ‘1’ by a full chip
erase or block erase function. The full chip
erase and block erase functions can only
be initiated via ICSP or an external
programmer.
000000h
0001FFh
000200h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFh
WRTB,EBTRB = 11
WRT0,EBTR0 = 01
WRT1,EBTR1 = 11
WRT2,EBTR2 = 11
WRT3,EBTR3 = 11
TBLWT *
TBLPTR = 000FFF
PC = 001FFE
PC = 004FFE TBLWT *
Register Values Program Memory Configuration Bit Settings
Results: All Table Writes disabled to Blockn whenever WRTn = ‘0’.© 2006 Microchip Technology Inc. DS39564C-page 209
PIC18FXX2
FIGURE 19-5: EXTERNAL BLOCK TABLE READ (EBTRn) DISALLOWED
FIGURE 19-6: EXTERNAL BLOCK TABLE READ (EBTRn) ALLOWED
000000h
0001FFh
000200h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFh
WRTB,EBTRB = 11
WRT0,EBTR0 = 10
WRT1,EBTR1 = 11
WRT2,EBTR2 = 11
WRT3,EBTR3 = 11
TBLRD *
TBLPTR = 000FFF
PC = 002FFE
Results: All Table Reads from external blocks to Blockn are disabled whenever EBTRn = ‘0’.
TABLAT register returns a value of “0”.
Register Values Program Memory Configuration Bit Settings
000000h
0001FFh
000200h
001FFFh
002000h
003FFFh
004000h
005FFFh
006000h
007FFFh
WRTB,EBTRB = 11
WRT0,EBTR0 = 10
WRT1,EBTR1 = 11
WRT2,EBTR2 = 11
WRT3,EBTR3 = 11
TBLRD *
TBLPTR = 000FFF
PC = 001FFE
Register Values Program Memory Configuration Bit Settings
Results: Table Reads permitted within Blockn, even when EBTRBn = ‘0’.
TABLAT register returns the value of the data at the location TBLPTR.PIC18FXX2
DS39564C-page 210 © 2006 Microchip Technology Inc.
19.4.2 DATA EEPROM
CODE PROTECTION
The entire Data EEPROM is protected from external
reads and writes by two bits: CPD and WRTD. CPD
inhibits external reads and writes of Data EEPROM.
WRTD inhibits external writes to Data EEPROM. The
CPU can continue to read and write Data EEPROM
regardless of the protection bit settings.
19.4.3 CONFIGURATION REGISTER
PROTECTION
The configuration registers can be write protected. The
WRTC bit controls protection of the configuration registers.
In User mode, the WRTC bit is readable only. WRTC
can only be written via ICSP or an external programmer.
19.5 ID Locations
Eight memory locations (200000h - 200007h) are designated
as ID locations, where the user can store
checksum or other code identification numbers. These
locations are accessible during normal execution
through the TBLRD and TBLWT instructions, or during
program/verify. The ID locations can be read when the
device is code protected.
The sequence for programming the ID locations is similar
to programming the FLASH memory (see
Section 5.5.1).
19.6 In-Circuit Serial Programming
PIC18FXXX microcontrollers can be serially programmed
while in the end application circuit. This is
simply done with two lines for clock and data, and three
other lines for power, ground and the programming
voltage. This allows customers to manufacture boards
with unprogrammed devices, and then program the
microcontroller just before shipping the product. This
also allows the most recent firmware or a custom
firmware to be programmed.
19.7 In-Circuit Debugger
When the DEBUG bit in configuration register
CONFIG4L is programmed to a '0', the In-Circuit
Debugger functionality is enabled. This function allows
simple debugging functions when used with MPLAB®
IDE. When the microcontroller has this feature
enabled, some of the resources are not available for
general use. Table 19-4 shows which features are
consumed by the background debugger.
TABLE 19-4: DEBUGGER RESOURCES
To use the In-Circuit Debugger function of the microcontroller,
the design must implement In-Circuit Serial
Programming connections to MCLR/VPP, VDD, GND,
RB7 and RB6. This will interface to the In-Circuit
Debugger module available from Microchip or one of
the third party development tool companies.
19.8 Low Voltage ICSP Programming
The LVP bit configuration register CONFIG4L enables
low voltage ICSP programming. This mode allows the
microcontroller to be programmed via ICSP using a
VDD source in the operating voltage range. This only
means that VPP does not have to be brought to VIHH,
but can instead be left at the normal operating voltage.
In this mode, the RB5/PGM pin is dedicated to the programming
function and ceases to be a general purpose
I/O pin. During programming, VDD is applied to the
MCLR/VPP pin. To enter Programming mode, VDD must
be applied to the RB5/PGM, provided the LVP bit is set.
The LVP bit defaults to a (‘1’) from the factory.
If Low Voltage Programming mode is not used, the LVP
bit can be programmed to a '0' and RB5/PGM becomes
a digital I/O pin. However, the LVP bit may only be programmed
when programming is entered with VIHH on
MCLR/VPP.
It should be noted that once the LVP bit is programmed
to 0, only the High Voltage Programming mode is available
and only High Voltage Programming mode can be
used to program the device.
When using low voltage ICSP, the part must be supplied
4.5V to 5.5V, if a bulk erase will be executed. This
includes reprogramming of the code protect bits from
an on-state to off-state. For all other cases of low voltage
ICSP, the part may be programmed at the normal
operating voltage. This means unique user IDs, or user
code can be reprogrammed or added. I/O pins RB6, RB7
Stack 2 levels
Program Memory 512 bytes
Data Memory 10 bytes
Note 1: The High Voltage Programming mode is
always available, regardless of the state
of the LVP bit, by applying VIHH to the
MCLR pin.
2: While in low voltage ICSP mode, the RB5
pin can no longer be used as a general
purpose I/O pin, and should be held low
during normal operation to protect
against inadvertent ICSP mode entry.
3: When using low voltage ICSP programming
(LVP), the pull-up on RB5 becomes
disabled. If TRISB bit 5 is cleared,
thereby setting RB5 as an output, LATB
bit 5 must also be cleared for proper
operation.© 2006 Microchip Technology Inc. DS39564C-page 211
PIC18FXX2
20.0 INSTRUCTION SET SUMMARY
The PIC18FXXX instruction set adds many enhancements
to the previous PICmicro instruction sets, while
maintaining an easy migration from these PICmicro
instruction sets.
Most instructions are a single program memory word
(16-bits), but there are three instructions that require
two program memory locations.
Each single word instruction is a 16-bit word divided
into an OPCODE, which specifies the instruction type
and one or more operands, which further specify the
operation of the instruction.
The instruction set is highly orthogonal and is grouped
into four basic categories:
• Byte-oriented operations
• Bit-oriented operations
• Literal operations
• Control operations
The PIC18FXXX instruction set summary in Table 20-2
lists byte-oriented, bit-oriented, literal and control
operations. Table 20-1 shows the opcode field
descriptions.
Most byte-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The destination of the result
(specified by ‘d’)
3. The accessed memory
(specified by ‘a’)
The file register designator 'f' specifies which file
register is to be used by the instruction.
The destination designator ‘d’ specifies where the
result of the operation is to be placed. If 'd' is zero, the
result is placed in the WREG register. If 'd' is one, the
result is placed in the file register specified in the
instruction.
All bit-oriented instructions have three operands:
1. The file register (specified by ‘f’)
2. The bit in the file register
(specified by ‘b’)
3. The accessed memory
(specified by ‘a’)
The bit field designator 'b' selects the number of the bit
affected by the operation, while the file register designator
'f' represents the number of the file in which the
bit is located.
The literal instructions may use some of the following
operands:
• A literal value to be loaded into a file register
(specified by ‘k’)
• The desired FSR register to load the literal value
into (specified by ‘f’)
• No operand required
(specified by ‘—’)
The control instructions may use some of the following
operands:
• A program memory address (specified by ‘n’)
• The mode of the Call or Return instructions
(specified by ‘s’)
• The mode of the Table Read and Table Write
instructions (specified by ‘m’)
• No operand required
(specified by ‘—’)
All instructions are a single word, except for three double-word
instructions. These three instructions were
made double-word instructions so that all the required
information is available in these 32 bits. In the second
word, the 4-MSbs are 1’s. If this second word is executed
as an instruction (by itself), it will execute as a
NOP.
All single word instructions are executed in a single
instruction cycle, unless a conditional test is true or the
program counter is changed as a result of the instruction.
In these cases, the execution takes two instruction
cycles with the additional instruction cycle(s) executed
as a NOP.
The double-word instructions execute in two instruction
cycles.
One instruction cycle consists of four oscillator periods.
Thus, for an oscillator frequency of 4 MHz, the normal
instruction execution time is 1 μs. If a conditional test is
true or the program counter is changed as a result of an
instruction, the instruction execution time is 2 μs.
Two-word branch instructions (if true) would take 3 μs.
Figure 20-1 shows the general formats that the
instructions can have.
All examples use the format ‘nnh’ to represent a
hexadecimal number, where ‘h’ signifies a
hexadecimal digit.
The Instruction Set Summary, shown in Table 20-2,
lists the instructions recognized by the Microchip
Assembler (MPASMTM).
Section 20.1 provides a description of each instruction.PIC18FXX2
DS39564C-page 212 © 2006 Microchip Technology Inc.
TABLE 20-1: OPCODE FIELD DESCRIPTIONS
Field Description
a RAM access bit
a = 0: RAM location in Access RAM (BSR register is ignored)
a = 1: RAM bank is specified by BSR register
bbb Bit address within an 8-bit file register (0 to 7)
BSR Bank Select Register. Used to select the current RAM bank.
d Destination select bit;
d = 0: store result in WREG,
d = 1: store result in file register f.
dest Destination either the WREG register or the specified register file location
f 8-bit Register file address (0x00 to 0xFF)
fs 12-bit Register file address (0x000 to 0xFFF). This is the source address.
fd 12-bit Register file address (0x000 to 0xFFF). This is the destination address.
k Literal field, constant data or label (may be either an 8-bit, 12-bit or a 20-bit value)
label Label name
mm The mode of the TBLPTR register for the Table Read and Table Write instructions.
Only used with Table Read and Table Write instructions:
* No Change to register (such as TBLPTR with Table reads and writes)
*+ Post-Increment register (such as TBLPTR with Table reads and writes)
*- Post-Decrement register (such as TBLPTR with Table reads and writes)
+* Pre-Increment register (such as TBLPTR with Table reads and writes)
n The relative address (2’s complement number) for relative branch instructions, or the direct address for
Call/Branch and Return instructions
PRODH Product of Multiply high byte
PRODL Product of Multiply low byte
s Fast Call/Return mode select bit.
s = 0: do not update into/from shadow registers
s = 1: certain registers loaded into/from shadow registers (Fast mode)
u Unused or Unchanged
WREG Working register (accumulator)
x Don't care (0 or 1)
The assembler will generate code with x = 0. It is the recommended form of use for compatibility with all
Microchip software tools.
TBLPTR 21-bit Table Pointer (points to a Program Memory location)
TABLAT 8-bit Table Latch
TOS Top-of-Stack
PC Program Counter
PCL Program Counter Low Byte
PCH Program Counter High Byte
PCLATH Program Counter High Byte Latch
PCLATU Program Counter Upper Byte Latch
GIE Global Interrupt Enable bit
WDT Watchdog Timer
TO Time-out bit
PD Power-down bit
C, DC, Z, OV, N ALU status bits Carry, Digit Carry, Zero, Overflow, Negative
[ ] Optional
( ) Contents
→ Assigned to
< > Register bit field
∈ In the set of
italics User defined term (font is courier)© 2006 Microchip Technology Inc. DS39564C-page 213
PIC18FXX2
FIGURE 20-1: GENERAL FORMAT FOR INSTRUCTIONS
Byte-oriented file register operations
15 10 9 8 7 0
d = 0 for result destination to be WREG register
OPCODE d a f (FILE #)
d = 1 for result destination to be file register (f)
a = 0 to force Access Bank
Bit-oriented file register operations
15 12 11 9 8 7 0
OPCODE b (BIT #) a f (FILE #)
b = 3-bit position of bit in file register (f)
Literal operations
15 8 7 0
OPCODE k (literal)
k = 8-bit immediate value
Byte to Byte move operations (2-word)
15 12 11 0
OPCODE f (Source FILE #)
CALL, GOTO and Branch operations
15 8 7 0
OPCODE n<7:0> (literal)
n = 20-bit immediate value
a = 1 for BSR to select bank
f = 8-bit file register address
a = 0 to force Access Bank
a = 1 for BSR to select bank
f = 8-bit file register address
15 12 11 0
1111 n<19:8> (literal)
15 12 11 0
1111 f (Destination FILE #)
f = 12-bit file register address
Control operations
Example Instruction
ADDWF MYREG, W, B
MOVFF MYREG1, MYREG2
BSF MYREG, bit, B
MOVLW 0x7F
GOTO Label
15 8 7 0
OPCODE n<7:0> (literal)
15 12 11 0
n<19:8> (literal)
CALL MYFUNC
15 11 10 0
OPCODE n<10:0> (literal)
S = Fast bit
BRA MYFUNC
15 8 7 0
OPCODE n<7:0> (literal) BC MYFUNC
SPIC18FXX2
DS39564C-page 214 © 2006 Microchip Technology Inc.
TABLE 20-2: PIC18FXXX INSTRUCTION SET
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
SUBWF
SUBWFB
SWAPF
TSTFSZ
XORWF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, skip =
Compare f with WREG, skip >
Compare f with WREG, skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to 1st word
fd (destination) 2nd word
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
borrow
Subtract WREG from f
Subtract WREG from f with
borrow
Swap nibbles in f
Test f, skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1 (2 or 3)
1
0010
0010
0001
0110
0001
0110
0110
0110
0000
0010
0100
0010
0011
0100
0001
0101
1100
1111
0110
0000
0110
0011
0100
0011
0100
0110
0101
0101
0101
0011
0110
0001
01da0
0da
01da
101a
11da
001a
010a
000a
01da
11da
11da
10da
11da
10da
00da
00da
ffff
ffff
111a
001a
110a
01da
01da
00da
00da
100a
01da
11da
10da
10da
011a
10da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z, N
Z, N
None
None
None
C, DC, Z, OV, N
C, Z, N
Z, N
C, Z, N
Z, N
None
C, DC, Z, OV, N
C, DC, Z, OV, N
C, DC, Z, OV, N
None
None
Z, N
1, 2
1, 2
1,2
2
1, 2
4
4
1, 2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
4
1, 2
1, 2
1
1, 2
1, 2
1, 2
1, 2
4
1, 2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
Note 1: When a PORT 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.
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 of the instruction 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.© 2006 Microchip Technology Inc. DS39564C-page 215
PIC18FXX2
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
CLRWDT
DAW
GOTO
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
RETLW
RETURN
SLEEP
n
n
n
n
n
n
n
n
n
n, s
—
—
n
—
—
—
—
n
s
k
s
—
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call subroutine1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to address1st word
2nd word
No Operation
No Operation
Pop top of return stack (TOS)
Push top of return stack (TOS)
Relative Call
Software device RESET
Return from interrupt enable
Return with literal in WREG
Return from Subroutine
Go into Standby mode
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
1 (2)
1 (2)
2
1
1
2
1
1
1
1
2
1
2
2
2
1
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0000
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
1100
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
kkkk
0001
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
kkkk
001s
0011
None
None
None
None
None
None
None
None
None
None
TO, PD
C
None
None
None
None
None
None
All
GIE/GIEH,
PEIE/GIEL
None
None
TO, PD
4
TABLE 20-2: PIC18FXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT 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.
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 of the instruction 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.PIC18FXX2
DS39564C-page 216 © 2006 Microchip Technology Inc.
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
LFSR
MOVLB
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
f, k
k
k
k
k
k
k
Add literal and WREG
AND literal with WREG
Inclusive OR literal with WREG
Move literal (12-bit) 2nd word
to FSRx 1st word
Move literal to BSR<3:0>
Move literal to WREG
Multiply literal with WREG
Return with literal in WREG
Subtract WREG from literal
Exclusive OR literal with WREG
1
1
1
2
1
1
1
2
1
1
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
0000
1111
1011
1001
1110
0000
0001
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
00ff
kkkk
0000
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
None
None
None
None
C, DC, Z, OV, N
Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD*
TBLRD*+
TBLRD*-
TBLRD+*
TBLWT*
TBLWT*+
TBLWT*-
TBLWT+*
Table Read
Table Read with post-increment
Table Read with post-decrement
Table Read with pre-increment
Table Write
Table Write with post-increment
Table Write with post-decrement
Table Write with pre-increment
2
2 (5)
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
1000
1001
1010
1011
1100
1101
1110
1111
None
None
None
None
None
None
None
None
TABLE 20-2: PIC18FXXX INSTRUCTION SET (CONTINUED)
Mnemonic,
Operands Description Cycles
16-Bit Instruction Word Status
Affected Notes
MSb LSb
Note 1: When a PORT 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.
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 of the instruction 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.© 2006 Microchip Technology Inc. DS39564C-page 217
PIC18FXX2
20.1 Instruction Set
ADDLW ADD literal to W
Syntax: [ label ] ADDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) + k → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1111 kkkk kkkk
Description: The contents of W are added to the
8-bit literal 'k' and the result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write to W
Example: ADDLW 0x15
Before Instruction
W = 0x10
After Instruction
W = 0x25
ADDWF ADD W to f
Syntax: [ label ] ADDWF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0010 01da ffff ffff
Description: Add W to register 'f'. If 'd' is 0, the
result is stored in W. If 'd' is 1, the
result is stored back in register 'f'
(default). If ‘a’ is 0, the Access
Bank will be selected. If ‘a’ is 1, the
BSR is used.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: ADDWF REG, 0, 0
Before Instruction
W = 0x17
REG = 0xC2
After Instruction
W = 0xD9
REG = 0xC2PIC18FXX2
DS39564C-page 218 © 2006 Microchip Technology Inc.
ADDWFC ADD W and Carry bit to f
Syntax: [ label ] ADDWFC f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) + (f) + (C) → dest
Status Affected: N,OV, C, DC, Z
Encoding: 0010 00da ffff ffff
Description: Add W, the Carry Flag and data
memory location 'f'. If 'd' is 0, the
result is placed in W. If 'd' is 1, the
result is placed in data memory location
'f'. If ‘a’ is 0, the Access Bank
will be selected. If ‘a’ is 1, the BSR
will not be overridden.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: ADDWFC REG, 0, 1
Before Instruction
Carry bit = 1
REG = 0x02
W = 0x4D
After Instruction
Carry bit = 0
REG = 0x02
W = 0x50
ANDLW AND literal with W
Syntax: [ label ] ANDLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .AND. k → W
Status Affected: N,Z
Encoding: 0000 1011 kkkk kkkk
Description: The contents of W are ANDed with
the 8-bit literal 'k'. The result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'k'
Process
Data
Write to W
Example: ANDLW 0x5F
Before Instruction
W = 0xA3
After Instruction
W = 0x03© 2006 Microchip Technology Inc. DS39564C-page 219
PIC18FXX2
ANDWF AND W with f
Syntax: [ label ] ANDWF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .AND. (f) → dest
Status Affected: N,Z
Encoding: 0001 01da ffff ffff
Description: The contents of W are AND’ed with
register 'f'. If 'd' is 0, the result is
stored in W. If 'd' is 1, the result is
stored back in register 'f' (default). If
‘a’ is 0, the Access Bank will be
selected. If ‘a’ is 1, the BSR will not
be overridden (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: ANDWF REG, 0, 0
Before Instruction
W = 0x17
REG = 0xC2
After Instruction
W = 0x02
REG = 0xC2
BC Branch if Carry
Syntax: [ label ] BC n
Operands: -128 ≤ n ≤ 127
Operation: if carry bit is ’1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0010 nnnn nnnn
Description: If the Carry bit is ’1’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BC 5
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 1;
PC = address (HERE+12)
If Carry = 0;
PC = address (HERE+2)PIC18FXX2
DS39564C-page 220 © 2006 Microchip Technology Inc.
BCF Bit Clear f
Syntax: [ label ] BCF f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 0 → f
Status Affected: None
Encoding: 1001 bbba ffff ffff
Description: Bit 'b' in register 'f' is cleared. If ‘a’
is 0, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: BCF FLAG_REG, 7, 0
Before Instruction
FLAG_REG = 0xC7
After Instruction
FLAG_REG = 0x47
BN Branch if Negative
Syntax: [ label ] BN n
Operands: -128 ≤ n ≤ 127
Operation: if negative bit is ’1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0110 nnnn nnnn
Description: If the Negative bit is ’1’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 1;
PC = address (Jump)
If Negative = 0;
PC = address (HERE+2)© 2006 Microchip Technology Inc. DS39564C-page 221
PIC18FXX2
BNC Branch if Not Carry
Syntax: [ label ] BNC n
Operands: -128 ≤ n ≤ 127
Operation: if carry bit is ’0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0011 nnnn nnnn
Description: If the Carry bit is ’0’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BNC Jump
Before Instruction
PC = address (HERE)
After Instruction
If Carry = 0;
PC = address (Jump)
If Carry = 1;
PC = address (HERE+2)
BNN Branch if Not Negative
Syntax: [ label ] BNN n
Operands: -128 ≤ n ≤ 127
Operation: if negative bit is ’0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0111 nnnn nnnn
Description: If the Negative bit is ’0’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BNN Jump
Before Instruction
PC = address (HERE)
After Instruction
If Negative = 0;
PC = address (Jump)
If Negative = 1;
PC = address (HERE+2)PIC18FXX2
DS39564C-page 222 © 2006 Microchip Technology Inc.
BNOV Branch if Not Overflow
Syntax: [ label ] BNOV n
Operands: -128 ≤ n ≤ 127
Operation: if overflow bit is ’0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0101 nnnn nnnn
Description: If the Overflow bit is ’0’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BNOV Jump
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 0;
PC = address (Jump)
If Overflow = 1;
PC = address (HERE+2)
BNZ Branch if Not Zero
Syntax: [ label ] BNZ n
Operands: -128 ≤ n ≤ 127
Operation: if zero bit is ’0’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0001 nnnn nnnn
Description: If the Zero bit is ’0’, then the program
will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BNZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 0;
PC = address (Jump)
If Zero = 1;
PC = address (HERE+2)© 2006 Microchip Technology Inc. DS39564C-page 223
PIC18FXX2
BRA Unconditional Branch
Syntax: [ label ] BRA n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 0nnn nnnn nnnn
Description: Add the 2’s complement number
’2n’ to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is a
two-cycle instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE BRA Jump
Before Instruction
PC = address (HERE)
After Instruction
PC = address (Jump)
BSF Bit Set f
Syntax: [ label ] BSF f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: 1 → f
Status Affected: None
Encoding: 1000 bbba ffff ffff
Description: Bit 'b' in register 'f' is set. If ‘a’ is 0
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: BSF FLAG_REG, 7, 1
Before Instruction
FLAG_REG = 0x0A
After Instruction
FLAG_REG = 0x8APIC18FXX2
DS39564C-page 224 © 2006 Microchip Technology Inc.
BTFSC Bit Test File, Skip if Clear
Syntax: [ label ] BTFSC f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: skip if (f) = 0
Status Affected: None
Encoding: 1011 bbba ffff ffff
Description: If bit 'b' in register ’f' is 0, then the
next instruction is skipped.
If bit 'b' is 0, then the next instruction
fetched during the current instruction
execution is discarded, and a NOP is
executed instead, making this a twocycle
instruction. If ‘a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process Data No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSC
:
:
FLAG, 1, 0
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (TRUE)
If FLAG<1> = 1;
PC = address (FALSE)
BTFSS Bit Test File, Skip if Set
Syntax: [ label ] BTFSS f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: skip if (f) = 1
Status Affected: None
Encoding: 1010 bbba ffff ffff
Description: If bit 'b' in register 'f' is 1, then the
next instruction is skipped.
If bit 'b' is 1, then the next instruction
fetched during the current instruction
execution, is discarded and a
NOP is executed instead, making this
a two-cycle instruction. If ‘a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process Data No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE
FALSE
TRUE
BTFSS
:
:
FLAG, 1, 0
Before Instruction
PC = address (HERE)
After Instruction
If FLAG<1> = 0;
PC = address (FALSE)
If FLAG<1> = 1;
PC = address (TRUE)© 2006 Microchip Technology Inc. DS39564C-page 225
PIC18FXX2
BTG Bit Toggle f
Syntax: [ label ] BTG f,b[,a]
Operands: 0 ≤ f ≤ 255
0 ≤ b ≤ 7
a ∈ [0,1]
Operation: (f) → f
Status Affected: None
Encoding: 0111 bbba ffff ffff
Description: Bit 'b' in data memory location 'f' is
inverted. If ‘a’ is 0, the Access Bank
will be selected, overriding the BSR
value. If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: BTG PORTC, 4, 0
Before Instruction:
PORTC = 0111 0101 [0x75]
After Instruction:
PORTC = 0110 0101 [0x65]
BOV Branch if Overflow
Syntax: [ label ] BOV n
Operands: -128 ≤ n ≤ 127
Operation: if overflow bit is ’1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0100 nnnn nnnn
Description: If the Overflow bit is ’1’, then the
program will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BOV Jump
Before Instruction
PC = address (HERE)
After Instruction
If Overflow = 1;
PC = address (Jump)
If Overflow = 0;
PC = address (HERE+2)PIC18FXX2
DS39564C-page 226 © 2006 Microchip Technology Inc.
BZ Branch if Zero
Syntax: [ label ] BZ n
Operands: -128 ≤ n ≤ 127
Operation: if Zero bit is ’1’
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1110 0000 nnnn nnnn
Description: If the Zero bit is ’1’, then the program
will branch.
The 2’s complement number ’2n’ is
added to the PC. Since the PC will
have incremented to fetch the next
instruction, the new address will be
PC+2+2n. This instruction is then
a two-cycle instruction.
Words: 1
Cycles: 1(2)
Q Cycle Activity:
If Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
If No Jump:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Process
Data
No
operation
Example: HERE BZ Jump
Before Instruction
PC = address (HERE)
After Instruction
If Zero = 1;
PC = address (Jump)
If Zero = 0;
PC = address (HERE+2)
CALL Subroutine Call
Syntax: [ label ] CALL k [,s]
Operands: 0 ≤ k ≤ 1048575
s ∈ [0,1]
Operation: (PC) + 4 → TOS,
k → PC<20:1>,
if s = 1
(W) → WS,
(STATUS) → STATUSS,
(BSR) → BSRS
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
110s
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: Subroutine call of entire 2 Mbyte
memory range. First, return
address (PC+ 4) is pushed onto the
return stack. If ’s’ = 1, the W,
STATUS and BSR registers are
also pushed into their respective
shadow registers, WS, STATUSS
and BSRS. If 's' = 0, no update
occurs (default). Then, the 20-bit
value ’k’ is loaded into PC<20:1>.
CALL is a two-cycle instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'k'<7:0>,
Push PC to
stack
Read literal
’k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE CALL THERE,1
Before Instruction
PC = address (HERE)
After Instruction
PC = address (THERE)
TOS = address (HERE + 4)
WS = W
BSRS = BSR
STATUSS= STATUS© 2006 Microchip Technology Inc. DS39564C-page 227
PIC18FXX2
CLRF Clear f
Syntax: [ label ] CLRF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: 000h → f
1 → Z
Status Affected: Z
Encoding: 0110 101a ffff ffff
Description: Clears the contents of the specified
register. If ‘a’ is 0, the Access Bank
will be selected, overriding the BSR
value. If ‘a’ = 1, then the bank will
be selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: CLRF FLAG_REG,1
Before Instruction
FLAG_REG = 0x5A
After Instruction
FLAG_REG = 0x00
CLRWDT Clear Watchdog Timer
Syntax: [ label ] CLRWDT
Operands: None
Operation: 000h → WDT,
000h → WDT postscaler,
1 → TO,
1 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0100
Description: CLRWDT instruction resets the
Watchdog Timer. It also resets the
postscaler of the WDT. Status bits
TO and PD are set.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
No
operation
Example: CLRWDT
Before Instruction
WDT Counter = ?
After Instruction
WDT Counter = 0x00
WDT Postscaler = 0
TO = 1
PD = 1PIC18FXX2
DS39564C-page 228 © 2006 Microchip Technology Inc.
COMF Complement f
Syntax: [ label ] COMF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: → dest
Status Affected: N, Z
Encoding: 0001 11da ffff ffff
Description: The contents of register 'f' are complemented.
If 'd' is 0, the result is
stored in W. If 'd' is 1, the result is
stored back in register 'f' (default). If
‘a’ is 0, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: COMF REG, 0, 0
Before Instruction
REG = 0x13
After Instruction
REG = 0x13
W = 0xEC
(f)
CPFSEQ Compare f with W, skip if f = W
Syntax: [ label ] CPFSEQ f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) = (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 001a ffff ffff
Description: Compares the contents of data
memory location 'f' to the contents
of W by performing an unsigned
subtraction.
If 'f' = W, then the fetched instruction
is discarded and a NOP is executed
instead, making this a twocycle
instruction. If ‘a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSEQ REG, 0
NEQUAL :
EQUAL :
Before Instruction
PC Address = HERE
W =?
REG = ?
After Instruction
If REG = W;
PC = Address (EQUAL)
If REG ≠ W;
PC = Address (NEQUAL)© 2006 Microchip Technology Inc. DS39564C-page 229
PIC18FXX2
CPFSGT Compare f with W, skip if f > W
Syntax: [ label ] CPFSGT f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) − (W),
skip if (f) > (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 010a ffff ffff
Description: Compares the contents of data
memory location 'f' to the contents
of the W by performing an
unsigned subtraction.
If the contents of 'f' are greater than
the contents of WREG, then the
fetched instruction is discarded and
a NOP is executed instead, making
this a two-cycle instruction. If ‘a’ is
0, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSGT REG, 0
NGREATER :
GREATER :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG > W;
PC = Address (GREATER)
If REG ≤ W;
PC = Address (NGREATER)
CPFSLT Compare f with W, skip if f < W
Syntax: [ label ] CPFSLT f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (f) – (W),
skip if (f) < (W)
(unsigned comparison)
Status Affected: None
Encoding: 0110 000a ffff ffff
Description: Compares the contents of data
memory location 'f' to the contents
of W by performing an unsigned
subtraction.
If the contents of 'f' are less than
the contents of W, then the fetched
instruction is discarded and a NOP
is executed instead, making this a
two-cycle instruction. If ‘a’ is 0, the
Access Bank will be selected. If ’a’
is 1, the BSR will not be overridden
(default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE CPFSLT REG, 1
NLESS :
LESS :
Before Instruction
PC = Address (HERE)
W = ?
After Instruction
If REG < W;
PC = Address (LESS)
If REG ≥ W;
PC = Address (NLESS)PIC18FXX2
DS39564C-page 230 © 2006 Microchip Technology Inc.
DAW Decimal Adjust W Register
Syntax: [ label ] DAW
Operands: None
Operation: If [W<3:0> >9] or [DC = 1] then
(W<3:0>) + 6 → W<3:0>;
else
(W<3:0>) → W<3:0>;
If [W<7:4> >9] or [C = 1] then
(W<7:4>) + 6 → W<7:4>;
else
(W<7:4>) → W<7:4>;
Status Affected: C
Encoding: 0000 0000 0000 0111
Description: DAW adjusts the eight-bit value in
W, resulting from the earlier addition
of two variables (each in
packed BCD format) and produces
a correct packed BCD result.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register W
Process
Data
Write
W
Example1: DAW
Before Instruction
W = 0xA5
C =0
DC = 0
After Instruction
W = 0x05
C =1
DC = 0
Example 2:
Before Instruction
W = 0xCE
C =0
DC = 0
After Instruction
W = 0x34
C =1
DC = 0
DECF Decrement f
Syntax: [ label ] DECF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0000 01da ffff ffff
Description: Decrement register 'f'. If 'd' is 0, the
result is stored in W. If 'd' is 1, the
result is stored back in register 'f'
(default). If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: DECF CNT, 1, 0
Before Instruction
CNT = 0x01
Z =0
After Instruction
CNT = 0x00
Z =1© 2006 Microchip Technology Inc. DS39564C-page 231
PIC18FXX2
DECFSZ Decrement f, skip if 0
Syntax: [ label ] DECFSZ f [,d [,a]]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0010 11da ffff ffff
Description: The contents of register 'f' are decremented.
If 'd' is 0, the result is
placed in W. If 'd' is 1, the result is
placed back in register 'f' (default).
If the result is 0, the next instruction,
which is already fetched, is
discarded, and a NOP is executed
instead, making it a two-cycle
instruction. If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DECFSZ CNT, 1, 1
GOTO LOOP
CONTINUE
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT - 1
If CNT = 0;
PC = Address (CONTINUE)
If CNT ≠ 0;
PC = Address (HERE+2)
DCFSNZ Decrement f, skip if not 0
Syntax: [ label ] DCFSNZ f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 11da ffff ffff
Description: The contents of register 'f' are decremented.
If 'd' is 0, the result is
placed in W. If 'd' is 1, the result is
placed back in register 'f' (default).
If the result is not 0, the next
instruction, which is already
fetched, is discarded, and a NOP is
executed instead, making it a twocycle
instruction. If ’a’ is 0, the
Access Bank will be selected,
overriding the BSR value. If ’a’ = 1,
then the bank will be selected as
per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE DCFSNZ TEMP, 1, 0
ZERO :
NZERO :
Before Instruction
TEMP = ?
After Instruction
TEMP = TEMP - 1,
If TEMP = 0;
PC = Address (ZERO)
If TEMP ≠ 0;
PC = Address (NZERO)PIC18FXX2
DS39564C-page 232 © 2006 Microchip Technology Inc.
GOTO Unconditional Branch
Syntax: [ label ] GOTO k
Operands: 0 ≤ k ≤ 1048575
Operation: k → PC<20:1>
Status Affected: None
Encoding:
1st word (k<7:0>)
2nd word(k<19:8>)
1110
1111
1111
k19kkk
k7kkk
kkkk
kkkk0
kkkk8
Description: GOTO allows an unconditional
branch anywhere within entire
2 Mbyte memory range. The 20-bit
value ’k’ is loaded into PC<20:1>.
GOTO is always a two-cycle
instruction.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'k'<7:0>,
No
operation
Read literal
’k’<19:8>,
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: GOTO THERE
After Instruction
PC = Address (THERE)
INCF Increment f
Syntax: [ label ] INCF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest
Status Affected: C, DC, N, OV, Z
Encoding: 0010 10da ffff ffff
Description: The contents of register 'f' are
incremented. If 'd' is 0, the result is
placed in W. If 'd' is 1, the result is
placed back in register 'f' (default).
If ’a’ is 0, the Access Bank will be
selected, overriding the BSR value.
If ’a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: INCF CNT, 1, 0
Before Instruction
CNT = 0xFF
Z =0
C =?
DC = ?
After Instruction
CNT = 0x00
Z =1
C =1
DC = 1© 2006 Microchip Technology Inc. DS39564C-page 233
PIC18FXX2
INCFSZ Increment f, skip if 0
Syntax: [ label ] INCFSZ f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result = 0
Status Affected: None
Encoding: 0011 11da ffff ffff
Description: The contents of register 'f' are
incremented. If 'd' is 0, the result is
placed in W. If 'd' is 1, the result is
placed back in register 'f'. (default)
If the result is 0, the next instruction,
which is already fetched, is
discarded, and a NOP is executed
instead, making it a two-cycle
instruction. If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INCFSZ CNT, 1, 0
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
CNT = CNT + 1
If CNT = 0;
PC = Address (ZERO)
If CNT ≠ 0;
PC = Address (NZERO)
INFSNZ Increment f, skip if not 0
Syntax: [ label ] INFSNZ f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) + 1 → dest,
skip if result ≠ 0
Status Affected: None
Encoding: 0100 10da ffff ffff
Description: The contents of register 'f' are
incremented. If 'd' is 0, the result is
placed in W. If 'd' is 1, the result is
placed back in register 'f' (default).
If the result is not 0, the next
instruction, which is already
fetched, is discarded, and a NOP is
executed instead, making it a twocycle
instruction. If ’a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ’a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE INFSNZ REG, 1, 0
ZERO
NZERO
Before Instruction
PC = Address (HERE)
After Instruction
REG = REG + 1
If REG ≠ 0;
PC = Address (NZERO)
If REG = 0;
PC = Address (ZERO)PIC18FXX2
DS39564C-page 234 © 2006 Microchip Technology Inc.
IORLW Inclusive OR literal with W
Syntax: [ label ] IORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .OR. k → W
Status Affected: N, Z
Encoding: 0000 1001 kkkk kkkk
Description: The contents of W are OR’ed with
the eight-bit literal 'k'. The result is
placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write to W
Example: IORLW 0x35
Before Instruction
W = 0x9A
After Instruction
W = 0xBF
IORWF Inclusive OR W with f
Syntax: [ label ] IORWF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .OR. (f) → dest
Status Affected: N, Z
Encoding: 0001 00da ffff ffff
Description: Inclusive OR W with register 'f'. If 'd'
is 0, the result is placed in W. If 'd'
is 1, the result is placed back in
register 'f' (default). If ’a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ’a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: IORWF RESULT, 0, 1
Before Instruction
RESULT = 0x13
W = 0x91
After Instruction
RESULT = 0x13
W = 0x93© 2006 Microchip Technology Inc. DS39564C-page 235
PIC18FXX2
LFSR Load FSR
Syntax: [ label ] LFSR f,k
Operands: 0 ≤ f ≤ 2
0 ≤ k ≤ 4095
Operation: k → FSRf
Status Affected: None
Encoding: 1110
1111
1110
0000
00ff
k7kkk
k11kkk
kkkk
Description: The 12-bit literal 'k' is loaded into
the file select register pointed to
by 'f'.
Words: 2
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'k' MSB
Process
Data
Write
literal 'k'
MSB to
FSRfH
Decode Read literal
'k' LSB
Process
Data
Write literal
'k' to FSRfL
Example: LFSR 2, 0x3AB
After Instruction
FSR2H = 0x03
FSR2L = 0xAB
MOVF Move f
Syntax: [ label ] MOVF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: f → dest
Status Affected: N, Z
Encoding: 0101 00da ffff ffff
Description: The contents of register 'f' are
moved to a destination dependent
upon the status of ’d’. If 'd' is 0, the
result is placed in W. If 'd' is 1, the
result is placed back in register 'f'
(default). Location 'f' can be anywhere
in the 256 byte bank. If ’a’ is
0, the Access Bank will be
selected, overriding the BSR value.
If ‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write W
Example: MOVF REG, 0, 0
Before Instruction
REG = 0x22
W = 0xFF
After Instruction
REG = 0x22
W = 0x22PIC18FXX2
DS39564C-page 236 © 2006 Microchip Technology Inc.
MOVFF Move f to f
Syntax: [ label ] MOVFF fs,fd
Operands: 0 ≤ fs ≤ 4095
0 ≤ fd ≤ 4095
Operation: (fs) → fd
Status Affected: None
Encoding:
1st word (source)
2nd word (destin.)
1100
1111
ffff
ffff
ffff
ffff
ffffs
ffffd
Description: The contents of source register 'fs'
are moved to destination register
'fd'. Location of source 'fs' can be
anywhere in the 4096 byte data
space (000h to FFFh), and location
of destination 'fd' can also be anywhere
from 000h to FFFh.
Either source or destination can be
W (a useful special situation).
MOVFF is particularly useful for
transferring a data memory location
to a peripheral register (such as the
transmit buffer or an I/O port).
The MOVFF instruction cannot use
the PCL, TOSU, TOSH or TOSL as
the destination register.
Note: The MOVFF instruction
should not be used to modify
interrupt settings while
any interrupt is enabled.
See Section 8.0 for more
information.
Words: 2
Cycles: 2 (3)
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
(src)
Process
Data
No
operation
Decode No
operation
No dummy
read
No
operation
Write
register 'f'
(dest)
Example: MOVFF REG1, REG2
Before Instruction
REG1 = 0x33
REG2 = 0x11
After Instruction
REG1 = 0x33,
REG2 = 0x33
MOVLB Move literal to low nibble in BSR
Syntax: [ label ] MOVLB k
Operands: 0 ≤ k ≤ 255
Operation: k → BSR
Status Affected: None
Encoding: 0000 0001 kkkk kkkk
Description: The 8-bit literal 'k' is loaded into
the Bank Select Register (BSR).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'k'
Process
Data
Write
literal 'k' to
BSR
Example: MOVLB 5
Before Instruction
BSR register = 0x02
After Instruction
BSR register = 0x05© 2006 Microchip Technology Inc. DS39564C-page 237
PIC18FXX2
MOVLW Move literal to W
Syntax: [ label ] MOVLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W
Status Affected: None
Encoding: 0000 1110 kkkk kkkk
Description: The eight-bit literal 'k' is loaded
into W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write to W
Example: MOVLW 0x5A
After Instruction
W = 0x5A
MOVWF Move W to f
Syntax: [ label ] MOVWF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) → f
Status Affected: None
Encoding: 0110 111a ffff ffff
Description: Move data from W to register 'f'.
Location 'f' can be anywhere in the
256 byte bank. If ‘a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ‘a’ = 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: MOVWF REG, 0
Before Instruction
W = 0x4F
REG = 0xFF
After Instruction
W = 0x4F
REG = 0x4FPIC18FXX2
DS39564C-page 238 © 2006 Microchip Technology Inc.
MULLW Multiply Literal with W
Syntax: [ label ] MULLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) x k → PRODH:PRODL
Status Affected: None
Encoding: 0000 1101 kkkk kkkk
Description: An unsigned multiplication is carried
out between the contents of
W and the 8-bit literal 'k'. The
16-bit result is placed in
PRODH:PRODL register pair.
PRODH contains the high byte.
W is unchanged.
None of the status flags are
affected.
Note that neither overflow nor
carry is possible in this operation.
A zero result is possible but
not detected.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write
registers
PRODH:
PRODL
Example: MULLW 0xC4
Before Instruction
W = 0xE2
PRODH = ?
PRODL = ?
After Instruction
W = 0xE2
PRODH = 0xAD
PRODL = 0x08
MULWF Multiply W with f
Syntax: [ label ] MULWF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: (W) x (f) → PRODH:PRODL
Status Affected: None
Encoding: 0000 001a ffff ffff
Description: An unsigned multiplication is carried
out between the contents of
W and the register file location 'f'.
The 16-bit result is stored in the
PRODH:PRODL register pair.
PRODH contains the high byte.
Both W and 'f' are unchanged.
None of the status flags are
affected.
Note that neither overflow nor
carry is possible in this operation.
A zero result is possible but
not detected. If ‘a’ is 0, the
Access Bank will be selected,
overriding the BSR value. If
‘a’ = 1, then the bank will be
selected as per the BSR value
(default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
registers
PRODH:
PRODL
Example: MULWF REG, 1
Before Instruction
W = 0xC4
REG = 0xB5
PRODH = ?
PRODL = ?
After Instruction
W = 0xC4
REG = 0xB5
PRODH = 0x8A
PRODL = 0x94© 2006 Microchip Technology Inc. DS39564C-page 239
PIC18FXX2
NEGF Negate f
Syntax: [ label ] NEGF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: ( f ) + 1 → f
Status Affected: N, OV, C, DC, Z
Encoding: 0110 110a ffff ffff
Description: Location ‘f’ is negated using two’s
complement. The result is placed in
the data memory location 'f'. If ’a’ is
0, the Access Bank will be
selected, overriding the BSR value.
If ’a’ = 1, then the bank will be
selected as per the BSR value.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: NEGF REG, 1
Before Instruction
REG = 0011 1010 [0x3A]
After Instruction
REG = 1100 0110 [0xC6]
NOP No Operation
Syntax: [ label ] NOP
Operands: None
Operation: No operation
Status Affected: None
Encoding: 0000
1111
0000
xxxx
0000
xxxx
0000
xxxx
Description: No operation.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
Example:
None.PIC18FXX2
DS39564C-page 240 © 2006 Microchip Technology Inc.
POP Pop Top of Return Stack
Syntax: [ label ] POP
Operands: None
Operation: (TOS) → bit bucket
Status Affected: None
Encoding: 0000 0000 0000 0110
Description: The TOS value is pulled off the
return stack and is discarded. The
TOS value then becomes the previous
value that was pushed onto the
return stack.
This instruction is provided to
enable the user to properly manage
the return stack to incorporate a
software stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
POP TOS
value
No
operation
Example: POP
GOTO NEW
Before Instruction
TOS = 0031A2h
Stack (1 level down) = 014332h
After Instruction
TOS = 014332h
PC = NEW
PUSH Push Top of Return Stack
Syntax: [ label ] PUSH
Operands: None
Operation: (PC+2) → TOS
Status Affected: None
Encoding: 0000 0000 0000 0101
Description: The PC+2 is pushed onto the top of
the return stack. The previous TOS
value is pushed down on the stack.
This instruction allows to implement
a software stack by modifying TOS,
and then push it onto the return
stack.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode PUSH PC+2
onto return
stack
No
operation
No
operation
Example: PUSH
Before Instruction
TOS = 00345Ah
PC = 000124h
After Instruction
PC = 000126h
TOS = 000126h
Stack (1 level down) = 00345Ah© 2006 Microchip Technology Inc. DS39564C-page 241
PIC18FXX2
RCALL Relative Call
Syntax: [ label ] RCALL n
Operands: -1024 ≤ n ≤ 1023
Operation: (PC) + 2 → TOS,
(PC) + 2 + 2n → PC
Status Affected: None
Encoding: 1101 1nnn nnnn nnnn
Description: Subroutine call with a jump up to
1K from the current location. First,
return address (PC+2) is pushed
onto the stack. Then, add the 2’s
complement number ’2n’ to the PC.
Since the PC will have incremented
to fetch the next instruction, the
new address will be PC+2+2n.
This instruction is a two-cycle
instruction.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read literal
'n'
Push PC to
stack
Process
Data
Write to PC
No
operation
No
operation
No
operation
No
operation
Example: HERE RCALL Jump
Before Instruction
PC = Address (HERE)
After Instruction
PC = Address (Jump)
TOS = Address (HERE+2)
RESET Reset
Syntax: [ label ] RESET
Operands: None
Operation: Reset all registers and flags that
are affected by a MCLR Reset.
Status Affected: All
Encoding: 0000 0000 1111 1111
Description: This instruction provides a way to
execute a MCLR Reset in software.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Start
reset
No
operation
No
operation
Example: RESET
After Instruction
Registers = Reset Value
Flags* = Reset ValuePIC18FXX2
DS39564C-page 242 © 2006 Microchip Technology Inc.
RETFIE Return from Interrupt
Syntax: [ label ] RETFIE [s]
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
1 → GIE/GIEH or PEIE/GIEL,
if s = 1
(WS) → W,
(STATUSS) → STATUS,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged.
Status Affected: GIE/GIEH, PEIE/GIEL.
Encoding: 0000 0000 0001 000s
Description: Return from Interrupt. Stack is
popped and Top-of-Stack (TOS) is
loaded into the PC. Interrupts are
enabled by setting either the high
or low priority global interrupt
enable bit. If ‘s’ = 1, the contents of
the shadow registers WS,
STATUSS and BSRS are loaded
into their corresponding registers,
W, STATUS and BSR. If ‘s’ = 0, no
update of these registers occurs
(default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
pop PC from
stack
Set GIEH or
GIEL
No
operation
No
operation
No
operation
No
operation
Example: RETFIE 1
After Interrupt
PC = TOS
W = WS
BSR = BSRS
STATUS = STATUSS
GIE/GIEH, PEIE/GIEL = 1
RETLW Return Literal to W
Syntax: [ label ] RETLW k
Operands: 0 ≤ k ≤ 255
Operation: k → W,
(TOS) → PC,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 1100 kkkk kkkk
Description: W is loaded with the eight-bit literal
'k'. The program counter is loaded
from the top of the stack (the return
address). The high address latch
(PCLATH) remains unchanged.
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
pop PC from
stack, Write
to W
No
operation
No
operation
No
operation
No
operation
Example:
CALL TABLE ; W contains table
; offset value
; W now has
; table value
:
TABLE
ADDWF PCL ; W = offset
RETLW k0 ; Begin table
RETLW k1 ;
:
:
RETLW kn ; End of table
Before Instruction
W = 0x07
After Instruction
W = value of kn© 2006 Microchip Technology Inc. DS39564C-page 243
PIC18FXX2
RETURN Return from Subroutine
Syntax: [ label ] RETURN [s]
Operands: s ∈ [0,1]
Operation: (TOS) → PC,
if s = 1
(WS) → W,
(STATUSS) → STATUS,
(BSRS) → BSR,
PCLATU, PCLATH are unchanged
Status Affected: None
Encoding: 0000 0000 0001 001s
Description: Return from subroutine. The stack
is popped and the top of the stack
(TOS) is loaded into the program
counter. If ‘s’= 1, the contents of the
shadow registers WS, STATUSS
and BSRS are loaded into their corresponding
registers, W, STATUS
and BSR. If ‘s’ = 0, no update of
these registers occurs (default).
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
pop PC from
stack
No
operation
No
operation
No
operation
No
operation
Example: RETURN
After Interrupt
PC = TOS
RLCF Rotate Left f through Carry
Syntax: [ label ] RLCF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → C,
(C) → dest<0>
Status Affected: C, N, Z
Encoding: 0011 01da ffff ffff
Description: The contents of register 'f' are
rotated one bit to the left through
the Carry Flag. If 'd' is 0, the result
is placed in W. If 'd' is 1, the result
is stored back in register 'f'
(default). If ‘a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ = 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: RLCF REG, 0, 0
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 1100 1100
C =1
C register fPIC18FXX2
DS39564C-page 244 © 2006 Microchip Technology Inc.
RLNCF Rotate Left f (no carry)
Syntax: [ label ] RLNCF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<7>) → dest<0>
Status Affected: N, Z
Encoding: 0100 01da ffff ffff
Description: The contents of register 'f' are
rotated one bit to the left. If 'd' is 0,
the result is placed in W. If 'd' is 1,
the result is stored back in register
'f' (default). If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ is 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: RLNCF REG, 1, 0
Before Instruction
REG = 1010 1011
After Instruction
REG = 0101 0111
register f
RRCF Rotate Right f through Carry
Syntax: [ label ] RRCF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → C,
(C) → dest<7>
Status Affected: C, N, Z
Encoding: 0011 00da ffff ffff
Description: The contents of register 'f' are
rotated one bit to the right through
the Carry Flag. If 'd' is 0, the result
is placed in W. If 'd' is 1, the result
is placed back in register 'f'
(default). If ‘a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ is 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: RRCF REG, 0, 0
Before Instruction
REG = 1110 0110
C =0
After Instruction
REG = 1110 0110
W = 0111 0011
C =0
C register f© 2006 Microchip Technology Inc. DS39564C-page 245
PIC18FXX2
RRNCF Rotate Right f (no carry)
Syntax: [ label ] RRNCF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) → dest,
(f<0>) → dest<7>
Status Affected: N, Z
Encoding: 0100 00da ffff ffff
Description: The contents of register 'f' are
rotated one bit to the right. If 'd' is 0,
the result is placed in W. If 'd' is 1,
the result is placed back in register
'f' (default). If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ is 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example 1: RRNCF REG, 1, 0
Before Instruction
REG = 1101 0111
After Instruction
REG = 1110 1011
Example 2: RRNCF REG, 0, 0
Before Instruction
W =?
REG = 1101 0111
After Instruction
W = 1110 1011
REG = 1101 0111
register f
SETF Set f
Syntax: [ label ] SETF f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: FFh → f
Status Affected: None
Encoding: 0110 100a ffff ffff
Description: The contents of the specified register
are set to FFh. If ’a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ’a’ is 1, then
the bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write
register 'f'
Example: SETF REG,1
Before Instruction
REG = 0x5A
After Instruction
REG = 0xFFPIC18FXX2
DS39564C-page 246 © 2006 Microchip Technology Inc.
SLEEP Enter SLEEP mode
Syntax: [ label ] SLEEP
Operands: None
Operation: 00h → WDT,
0 → WDT postscaler,
1 → TO,
0 → PD
Status Affected: TO, PD
Encoding: 0000 0000 0000 0011
Description: The power-down status bit (PD) is
cleared. The time-out status bit
(TO) is set. Watchdog Timer and
its postscaler are cleared.
The processor is put into SLEEP
mode with the oscillator stopped.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
Process
Data
Go to
sleep
Example: SLEEP
Before Instruction
TO = ?
PD = ?
After Instruction
TO = 1 †
PD = 0
† If WDT causes wake-up, this bit is cleared.
SUBFWB Subtract f from W with borrow
Syntax: [ label ] SUBFWB f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) – (f) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 01da ffff ffff
Description: Subtract register 'f' and carry flag
(borrow) from W (2’s complement
method). If 'd' is 0, the result is
stored in W. If 'd' is 1, the result is
stored in register 'f' (default). If ’a’ is
0, the Access Bank will be selected,
overriding the BSR value. If ’a’ is 1,
then the bank will be selected as
per the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example 1: SUBFWB REG, 1, 0
Before Instruction
REG = 3
W =2
C =1
After Instruction
REG = FF
W =2
C =0
Z =0
N = 1 ; result is negative
Example 2: SUBFWB REG, 0, 0
Before Instruction
REG = 2
W =5
C =1
After Instruction
REG = 2
W =3
C =1
Z =0
N = 0 ; result is positive
Example 3: SUBFWB REG, 1, 0
Before Instruction
REG = 1
W =2
C =0
After Instruction
REG = 0
W =2
C =1
Z = 1 ; result is zero
N =0© 2006 Microchip Technology Inc. DS39564C-page 247
PIC18FXX2
SUBLW Subtract W from literal
Syntax: [ label ] SUBLW k
Operands: 0 ≤ k ≤ 255
Operation: k – (W) → W
Status Affected: N, OV, C, DC, Z
Encoding: 0000 1000 kkkk kkkk
Description: W is subtracted from the eight-bit
literal 'k'. The result is placed
in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write to W
Example 1: SUBLW 0x02
Before Instruction
W =1
C =?
After Instruction
W =1
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBLW 0x02
Before Instruction
W =2
C =?
After Instruction
W =0
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBLW 0x02
Before Instruction
W =3
C =?
After Instruction
W = FF ; (2’s complement)
C = 0 ; result is negative
Z =0
N =1
SUBWF Subtract W from f
Syntax: [ label ] SUBWF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 11da ffff ffff
Description: Subtract W from register 'f' (2’s
complement method). If 'd' is 0,
the result is stored in W. If 'd' is 1,
the result is stored back in register
'f' (default). If ’a’ is 0, the
Access Bank will be selected,
overriding the BSR value. If ’a’ is
1, then the bank will be selected
as per the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example 1: SUBWF REG, 1, 0
Before Instruction
REG = 3
W =2
C =?
After Instruction
REG = 1
W =2
C = 1 ; result is positive
Z =0
N =0
Example 2: SUBWF REG, 0, 0
Before Instruction
REG = 2
W =2
C =?
After Instruction
REG = 2
W =0
C = 1 ; result is zero
Z =1
N =0
Example 3: SUBWF REG, 1, 0
Before Instruction
REG = 1
W =2
C =?
After Instruction
REG = FFh ;(2’s complement)
W =2
C = 0 ; result is negative
Z =0
N =1PIC18FXX2
DS39564C-page 248 © 2006 Microchip Technology Inc.
SUBWFB Subtract W from f with Borrow
Syntax: [ label ] SUBWFB f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f) – (W) – (C) → dest
Status Affected: N, OV, C, DC, Z
Encoding: 0101 10da ffff ffff
Description: Subtract W and the carry flag (borrow)
from register 'f' (2’s complement
method). If 'd' is 0, the result is stored
in W. If 'd' is 1, the result is stored
back in register 'f' (default). If ’a’ is 0,
the Access Bank will be selected,
overriding the BSR value. If ’a’ is 1,
then the bank will be selected as per
the BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example 1: SUBWFB REG, 1, 0
Before Instruction
REG = 0x19 (0001 1001)
W = 0x0D (0000 1101)
C =1
After Instruction
REG = 0x0C (0000 1011)
W = 0x0D (0000 1101)
C =1
Z =0
N = 0 ; result is positive
Example 2: SUBWFB REG, 0, 0
Before Instruction
REG = 0x1B (0001 1011)
W = 0x1A (0001 1010)
C =0
After Instruction
REG = 0x1B (0001 1011)
W = 0x00
C =1
Z = 1 ; result is zero
N =0
Example 3: SUBWFB REG, 1, 0
Before Instruction
REG = 0x03 (0000 0011)
W = 0x0E (0000 1101)
C =1
After Instruction
REG = 0xF5 (1111 0100)
; [2’s comp]
W = 0x0E (0000 1101)
C =0
Z =0
N = 1 ; result is negative
SWAPF Swap f
Syntax: [ label ] SWAPF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (f<3:0>) → dest<7:4>,
(f<7:4>) → dest<3:0>
Status Affected: None
Encoding: 0011 10da ffff ffff
Description: The upper and lower nibbles of register
'f' are exchanged. If 'd' is 0, the
result is placed in W. If 'd' is 1, the
result is placed in register 'f'
(default). If ’a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ is 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: SWAPF REG, 1, 0
Before Instruction
REG = 0x53
After Instruction
REG = 0x35© 2006 Microchip Technology Inc. DS39564C-page 249
PIC18FXX2
TBLRD Table Read
Syntax: [ label ] TBLRD ( *; *+; *-; +*)
Operands: None
Operation: if TBLRD *,
(Prog Mem (TBLPTR)) → TABLAT;
TBLPTR - No Change;
if TBLRD *+,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) +1 → TBLPTR;
if TBLRD *-,
(Prog Mem (TBLPTR)) → TABLAT;
(TBLPTR) -1 → TBLPTR;
if TBLRD +*,
(TBLPTR) +1 → TBLPTR;
(Prog Mem (TBLPTR)) → TABLAT;
Status Affected:None
Encoding: 0000 0000 0000 10nn
nn=0 *
=1 *+
=2 *-
=3 +*
Description: This instruction is used to read the contents
of Program Memory (P.M.). To
address the program memory, a pointer
called Table Pointer (TBLPTR) is used.
The TBLPTR (a 21-bit pointer) points
to each byte in the program memory.
TBLPTR has a 2 Mbyte address range.
TBLPTR[0] = 0: Least Significant
Byte of Program
Memory Word
TBLPTR[0] = 1: Most Significant
Byte of Program
Memory Word
The TBLRD instruction can modify the
value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No operation
(Read Program
Memory)
No
operation
No operation
(Write TABLAT)
TBLRD Table Read (cont’d)
Example1: TBLRD *+ ;
Before Instruction
TABLAT = 0x55
TBLPTR = 0x00A356
MEMORY(0x00A356) = 0x34
After Instruction
TABLAT = 0x34
TBLPTR = 0x00A357
Example2: TBLRD +* ;
Before Instruction
TABLAT = 0xAA
TBLPTR = 0x01A357
MEMORY(0x01A357) = 0x12
MEMORY(0x01A358) = 0x34
After Instruction
TABLAT = 0x34
TBLPTR = 0x01A358PIC18FXX2
DS39564C-page 250 © 2006 Microchip Technology Inc.
TBLWT Table Write
Syntax: [ label ] TBLWT ( *; *+; *-; +*)
Operands: None
Operation: if TBLWT*,
(TABLAT) → Holding Register;
TBLPTR - No Change;
if TBLWT*+,
(TABLAT) → Holding Register;
(TBLPTR) +1 → TBLPTR;
if TBLWT*-,
(TABLAT) → Holding Register;
(TBLPTR) -1 → TBLPTR;
if TBLWT+*,
(TBLPTR) +1 → TBLPTR;
(TABLAT) → Holding Register;
Status Affected: None
Encoding: 0000 0000 0000 11nn
nn=0 *
=1 *+
=2 *-
=3 +*
Description: This instruction uses the 3 LSbs of the
TBLPTR to determine which of the 8
holding registers the TABLAT data is
written to. The 8 holding registers are
used to program the contents of Program
Memory (P.M.). See Section 5.0
for information on writing to FLASH
memory.
The TBLPTR (a 21-bit pointer) points
to each byte in the program memory.
TBLPTR has a 2 MBtye address
range. The LSb of the TBLPTR selects
which byte of the program memory
location to access.
TBLPTR[0] = 0: Least Significant
Byte of Program
Memory Word
TBLPTR[0] = 1: Most Significant
Byte of Program
Memory Word
The TBLWT instruction can modify the
value of TBLPTR as follows:
• no change
• post-increment
• post-decrement
• pre-increment
Words: 1
Cycles: 2
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode No
operation
No
operation
No
operation
No
operation
No
operation
(Read
TABLAT)
No
operation
No
operation
(Write to Holding
Register or Memory)
TBLWT Table Write (Continued)
Example1: TBLWT *+;
Before Instruction
TABLAT = 0x55
TBLPTR = 0x00A356
HOLDING REGISTER
(0x00A356) = 0xFF
After Instructions (table write completion)
TABLAT = 0x55
TBLPTR = 0x00A357
HOLDING REGISTER
(0x00A356) = 0x55
Example 2: TBLWT +*;
Before Instruction
TABLAT = 0x34
TBLPTR = 0x01389A
HOLDING REGISTER
(0x01389A) = 0xFF
HOLDING REGISTER
(0x01389B) = 0xFF
After Instruction (table write completion)
TABLAT = 0x34
TBLPTR = 0x01389B
HOLDING REGISTER
(0x01389A) = 0xFF
HOLDING REGISTER
(0x01389B) = 0x34
© 2006 Microchip Technology Inc. DS39564C-page 251
PIC18FXX2
TSTFSZ Test f, skip if 0
Syntax: [ label ] TSTFSZ f [,a]
Operands: 0 ≤ f ≤ 255
a ∈ [0,1]
Operation: skip if f = 0
Status Affected: None
Encoding: 0110 011a ffff ffff
Description: If 'f' = 0, the next instruction,
fetched during the current instruction
execution, is discarded and a
NOP is executed, making this a twocycle
instruction. If ’a’ is 0, the
Access Bank will be selected, overriding
the BSR value. If ’a’ is 1,
then the bank will be selected as
per the BSR value (default).
Words: 1
Cycles: 1(2)
Note: 3 cycles if skip and followed
by a 2-word instruction.
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
No
operation
If skip:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
If skip and followed by 2-word instruction:
Q1 Q2 Q3 Q4
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
No
operation
Example: HERE TSTFSZ CNT, 1
NZERO :
ZERO :
Before Instruction
PC = Address (HERE)
After Instruction
If CNT = 0x00,
PC = Address (ZERO)
If CNT ≠ 0x00,
PC = Address (NZERO)
XORLW Exclusive OR literal with W
Syntax: [ label ] XORLW k
Operands: 0 ≤ k ≤ 255
Operation: (W) .XOR. k → W
Status Affected: N, Z
Encoding: 0000 1010 kkkk kkkk
Description: The contents of W are XORed
with the 8-bit literal 'k'. The result
is placed in W.
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
literal 'k'
Process
Data
Write to W
Example: XORLW 0xAF
Before Instruction
W = 0xB5
After Instruction
W = 0x1APIC18FXX2
DS39564C-page 252 © 2006 Microchip Technology Inc.
XORWF Exclusive OR W with f
Syntax: [ label ] XORWF f [,d [,a]
Operands: 0 ≤ f ≤ 255
d ∈ [0,1]
a ∈ [0,1]
Operation: (W) .XOR. (f) → dest
Status Affected: N, Z
Encoding: 0001 10da ffff ffff
Description: Exclusive OR the contents of W
with register 'f'. If 'd' is 0, the result
is stored in W. If 'd' is 1, the result is
stored back in the register 'f'
(default). If ‘a’ is 0, the Access
Bank will be selected, overriding
the BSR value. If ’a’ is 1, then the
bank will be selected as per the
BSR value (default).
Words: 1
Cycles: 1
Q Cycle Activity:
Q1 Q2 Q3 Q4
Decode Read
register 'f'
Process
Data
Write to
destination
Example: XORWF REG, 1, 0
Before Instruction
REG = 0xAF
W = 0xB5
After Instruction
REG = 0x1A
W = 0xB5© 2006 Microchip Technology Inc. DS39564C-page 253
PIC18FXX2
21.0 DEVELOPMENT SUPPORT
The PICmicro® microcontrollers are supported with a
full range of hardware and software development tools:
• Integrated Development Environment
- MPLAB® IDE Software
• Assemblers/Compilers/Linkers
- MPASMTM Assembler
- MPLAB C17 and MPLAB C18 C Compilers
- MPLINKTM Object Linker/
MPLIBTM Object Librarian
• Simulators
- MPLAB SIM Software Simulator
• Emulators
- MPLAB ICE 2000 In-Circuit Emulator
- ICEPIC™ In-Circuit Emulator
• In-Circuit Debugger
- MPLAB ICD
• Device Programmers
- PRO MATE® II Universal Device Programmer
- PICSTART® Plus Entry-Level Development
Programmer
• Low Cost Demonstration Boards
- PICDEMTM 1 Demonstration Board
- PICDEM 2 Demonstration Board
- PICDEM 3 Demonstration Board
- PICDEM 17 Demonstration Board
- KEELOQ® Demonstration Board
21.1 MPLAB Integrated Development
Environment Software
The MPLAB IDE software brings an ease of software
development previously unseen in the 8-bit microcontroller
market. The MPLAB IDE is a Windows® based
application that contains:
• An interface to debugging tools
- simulator
- programmer (sold separately)
- emulator (sold separately)
- in-circuit debugger (sold separately)
• A full-featured editor
• A project manager
• Customizable toolbar and key mapping
• A status bar
• On-line help
The MPLAB IDE allows you to:
• Edit your source files (either assembly or ‘C’)
• One touch assemble (or compile) and download
to PICmicro emulator and simulator tools (automatically
updates all project information)
• Debug using:
- source files
- absolute listing file
- machine code
The ability to use MPLAB IDE with multiple debugging
tools allows users to easily switch from the costeffective
simulator to a full-featured emulator with
minimal retraining.
21.2 MPASM Assembler
The MPASM assembler is a full-featured universal
macro assembler for all PICmicro MCU’s.
The MPASM assembler has a command line interface
and a Windows shell. It can be used as a stand-alone
application on a Windows 3.x or greater system, or it
can be used through MPLAB IDE. The MPASM assembler
generates relocatable object files for the MPLINK
object linker, Intel® standard HEX files, MAP files to
detail memory usage and symbol reference, an absolute
LST file that contains source lines and generated
machine code, and a COD file for debugging.
The MPASM assembler features include:
• Integration into MPLAB IDE projects.
• User-defined macros to streamline assembly
code.
• Conditional assembly for multi-purpose source
files.
• Directives that allow complete control over the
assembly process.
21.3 MPLAB C17 and MPLAB C18
C Compilers
The MPLAB C17 and MPLAB C18 Code Development
Systems are complete ANSI ‘C’ compilers for
Microchip’s PIC17CXXX and PIC18CXXX family of
microcontrollers, respectively. These compilers provide
powerful integration capabilities and ease of use not
found with other compilers.
For easier source level debugging, the compilers provide
symbol information that is compatible with the
MPLAB IDE memory display.PIC18FXX2
DS39564C-page 254 © 2006 Microchip Technology Inc.
21.4 MPLINK Object Linker/
MPLIB Object Librarian
The MPLINK object linker combines relocatable
objects created by the MPASM assembler and the
MPLAB C17 and MPLAB C18 C compilers. It can also
link relocatable objects from pre-compiled libraries,
using directives from a linker script.
The MPLIB object librarian is a librarian for precompiled
code to be used with the MPLINK object
linker. When a routine from a library is called from
another source file, only the modules that contain that
routine will be linked in with the application. This allows
large libraries to be used efficiently in many different
applications. The MPLIB object librarian manages the
creation and modification of library files.
The MPLINK object linker features include:
• Integration with MPASM assembler and MPLAB
C17 and MPLAB C18 C compilers.
• Allows all memory areas to be defined as sections
to provide link-time flexibility.
The MPLIB object librarian features include:
• Easier linking because single libraries can be
included instead of many smaller files.
• Helps keep code maintainable by grouping
related modules together.
• Allows libraries to be created and modules to be
added, listed, replaced, deleted or extracted.
21.5 MPLAB SIM Software Simulator
The MPLAB SIM software simulator allows code development
in a PC-hosted environment by simulating the
PICmicro series microcontrollers on an instruction
level. On any given instruction, the data areas can be
examined or modified and stimuli can be applied from
a file, or user-defined key press, to any of the pins. The
execution can be performed in single step, execute
until break, or trace mode.
The MPLAB SIM simulator fully supports symbolic debugging
using the MPLAB C17 and the MPLAB C18 C compilers
and the MPASM assembler. The software simulator
offers the flexibility to develop and debug code outside of
the laboratory environment, making it an excellent multiproject
software development tool.
21.6 MPLAB ICE High Performance
Universal In-Circuit Emulator with
MPLAB IDE
The MPLAB ICE universal in-circuit emulator is intended
to provide the product development engineer with a
complete microcontroller design tool set for PICmicro
microcontrollers (MCUs). Software control of the
MPLAB ICE in-circuit emulator is provided by the
MPLAB Integrated Development Environment (IDE),
which allows editing, building, downloading and source
debugging from a single environment.
The MPLAB ICE 2000 is a full-featured emulator system
with enhanced trace, trigger and data monitoring
features. Interchangeable processor modules allow the
system to be easily reconfigured for emulation of different
processors. The universal architecture of the
MPLAB ICE in-circuit emulator allows expansion to
support new PICmicro microcontrollers.
The MPLAB ICE in-circuit emulator system has been
designed as a real-time emulation system, with
advanced features that are generally found on more
expensive development tools. The PC platform and
Microsoft® Windows environment were chosen to best
make these features available to you, the end user.
21.7 ICEPIC In-Circuit Emulator
The ICEPIC low cost, in-circuit emulator is a solution
for the Microchip Technology PIC16C5X, PIC16C6X,
PIC16C7X and PIC16CXXX families of 8-bit OneTime-Programmable
(OTP) microcontrollers. The modular
system can support different subsets of PIC16C5X
or PIC16CXXX products through the use of interchangeable
personality modules, or daughter boards.
The emulator is capable of emulating without target
application circuitry being present.© 2006 Microchip Technology Inc. DS39564C-page 255
PIC18FXX2
21.8 MPLAB ICD In-Circuit Debugger
Microchip's In-Circuit Debugger, MPLAB ICD, is a powerful,
low cost, run-time development tool. This tool is
based on the FLASH PICmicro MCUs and can be used
to develop for this and other PICmicro microcontrollers.
The MPLAB ICD utilizes the in-circuit debugging capability
built into the FLASH devices. This feature, along
with Microchip's In-Circuit Serial ProgrammingTM protocol,
offers cost-effective in-circuit FLASH debugging
from the graphical user interface of the MPLAB
Integrated Development Environment. This enables a
designer to develop and debug source code by watching
variables, single-stepping and setting break points.
Running at full speed enables testing hardware in realtime.
21.9 PRO MATE II Universal Device
Programmer
The PRO MATE II universal device programmer is a
full-featured programmer, capable of operating in
stand-alone mode, as well as PC-hosted mode. The
PRO MATE II device programmer is CE compliant.
The PRO MATE II device programmer has programmable
VDD and VPP supplies, which allow it to verify
programmed memory at VDD min and VDD max for maximum
reliability. It has an LCD display for instructions
and error messages, keys to enter commands and a
modular detachable socket assembly to support various
package types. In stand-alone mode, the PRO MATE II
device programmer can read, verify, or program
PICmicro devices. It can also set code protection in this
mode.
21.10 PICSTART Plus Entry Level
Development Programmer
The PICSTART Plus development programmer is an
easy-to-use, low cost, prototype programmer. It connects
to the PC via a COM (RS-232) port. MPLAB
Integrated Development Environment software makes
using the programmer simple and efficient.
The PICSTART Plus development programmer supports
all PICmicro devices with up to 40 pins. Larger pin
count devices, such as the PIC16C92X and
PIC17C76X, may be supported with an adapter socket.
The PICSTART Plus development programmer is CE
compliant.
21.11 PICDEM 1 Low Cost PICmicro
Demonstration Board
The PICDEM 1 demonstration board is a simple board
which demonstrates the capabilities of several of
Microchip’s microcontrollers. The microcontrollers supported
are: PIC16C5X (PIC16C54 to PIC16C58A),
PIC16C61, PIC16C62X, PIC16C71, PIC16C8X,
PIC17C42, PIC17C43 and PIC17C44. All necessary
hardware and software is included to run basic demo
programs. The user can program the sample microcontrollers
provided with the PICDEM 1 demonstration
board on a PRO MATE II device programmer, or a
PICSTART Plus development programmer, and easily
test firmware. The user can also connect the
PICDEM 1 demonstration board to the MPLAB ICE incircuit
emulator and download the firmware to the emulator
for testing. A prototype area is available for the
user to build some additional hardware and connect it
to the microcontroller socket(s). Some of the features
include an RS-232 interface, a potentiometer for simulated
analog input, push button switches and eight
LEDs connected to PORTB.
21.12 PICDEM 2 Low Cost PIC16CXX
Demonstration Board
The PICDEM 2 demonstration board is a simple demonstration
board that supports the PIC16C62,
PIC16C64, PIC16C65, PIC16C73 and PIC16C74
microcontrollers. All the necessary hardware and software
is included to run the basic demonstration programs.
The user can program the sample
microcontrollers provided with the PICDEM 2 demonstration
board on a PRO MATE II device programmer,
or a PICSTART Plus development programmer, and
easily test firmware. The MPLAB ICE in-circuit emulator
may also be used with the PICDEM 2 demonstration
board to test firmware. A prototype area has been provided
to the user for adding additional hardware and
connecting it to the microcontroller socket(s). Some of
the features include a RS-232 interface, push button
switches, a potentiometer for simulated analog input, a
serial EEPROM to demonstrate usage of the I2CTM bus
and separate headers for connection to an LCD
module and a keypad.PIC18FXX2
DS39564C-page 256 © 2006 Microchip Technology Inc.
21.13 PICDEM 3 Low Cost PIC16CXXX
Demonstration Board
The PICDEM 3 demonstration board is a simple demonstration
board that supports the PIC16C923 and
PIC16C924 in the PLCC package. It will also support
future 44-pin PLCC microcontrollers with an LCD Module.
All the necessary hardware and software is
included to run the basic demonstration programs. The
user can program the sample microcontrollers provided
with the PICDEM 3 demonstration board on a
PRO MATE II device programmer, or a PICSTART Plus
development programmer with an adapter socket, and
easily test firmware. The MPLAB ICE in-circuit emulator
may also be used with the PICDEM 3 demonstration
board to test firmware. A prototype area has been provided
to the user for adding hardware and connecting it
to the microcontroller socket(s). Some of the features
include a RS-232 interface, push button switches, a
potentiometer for simulated analog input, a thermistor
and separate headers for connection to an external
LCD module and a keypad. Also provided on the
PICDEM 3 demonstration board is a LCD panel, with 4
commons and 12 segments, that is capable of displaying
time, temperature and day of the week. The
PICDEM 3 demonstration board provides an additional
RS-232 interface and Windows software for showing
the demultiplexed LCD signals on a PC. A simple serial
interface allows the user to construct a hardware
demultiplexer for the LCD signals.
21.14 PICDEM 17 Demonstration Board
The PICDEM 17 demonstration board is an evaluation
board that demonstrates the capabilities of several
Microchip microcontrollers, including PIC17C752,
PIC17C756A, PIC17C762 and PIC17C766. All necessary
hardware is included to run basic demo programs,
which are supplied on a 3.5-inch disk. A programmed
sample is included and the user may erase it and
program it with the other sample programs using the
PRO MATE II device programmer, or the PICSTART
Plus development programmer, and easily debug and
test the sample code. In addition, the PICDEM 17 demonstration
board supports downloading of programs to
and executing out of external FLASH memory on board.
The PICDEM 17 demonstration board is also usable
with the MPLAB ICE in-circuit emulator, or the
PICMASTER emulator and all of the sample programs
can be run and modified using either emulator. Additionally,
a generous prototype area is available for user
hardware.
21.15 KEELOQ Evaluation and
Programming Tools
KEELOQ evaluation and programming tools support
Microchip’s HCS Secure Data Products. The HCS evaluation
kit includes a LCD display to show changing
codes, a decoder to decode transmissions and a
programming interface to program test transmitters.© 2006 Microchip Technology Inc. DS39564C-page 257
PIC18FXX2
TABLE 21-1: DEVELOPMENT TOOLS FROM MICROCHIP
PIC12CXXX
PIC14000
PIC16C5X
PIC16C6X
PIC16CXXX
PIC16F62X
PIC16C7X
PIC16C7XX
PIC16C8X/
PIC16F8X
PIC16F8XX
PIC16C9XX
PIC17C4X
PIC17C7XX
PIC18CXX2
PIC18FXXX
24CXX/
25CXX/
93CXX
HCSXXX
MCRFXXX
MCP2510
Software ToolsMPLAB® Integrated Development Environment !!! ! ! ! ! ! ! ! !! ! ! ! MPLAB® C17 C Compiler ! ! MPLAB® C18 C Compiler ! ! MPASMTM Assembler/ MPLINKTM Object Linker !!! ! ! ! ! ! ! ! !! ! ! ! ! !
EmulatorsMPLAB® ICE In-Circuit Emulator !!! ! !!** ! ! ! ! !! ! ! ! ICEPICTM In-Circuit Emulator ! !! ! ! ! ! !
Debugger MPLAB® ICD In-Circuit Debugger
!* !* ! !
ProgrammersPICSTART® Plus Entry Level Development Programmer !!! ! !!** ! ! ! ! !! ! ! ! PRO MATE® II Universal Device Programmer !!! ! !!** ! ! ! ! !! ! ! ! ! !
Demo Boards and Eval Kits
PICDEMTM 1 Demonstration
Board !!!† ! !
PICDEMTM 2 Demonstration
Board
!† !† ! !
PICDEMTM 3 Demonstration
Board
!
PICDEMTM 14A Demonstration
Board
!
PICDEMTM 17 Demonstration
Board
!
KEELOQ® Evaluation Kit
!
KEELOQ® Transponder Kit
!
microIDTM Programmer’s Kit
!
125 kHz microIDTM
Developer’s Kit
!
125 kHz Anticollision microIDTM
Developer’s Kit
!
13.56 MHz Anticollision
microIDTM Developer’s Kit
!
MCP2510 CAN Developer’s Kit
!
* Contact the Microchip Technology Inc. web site at www.microchip.com for information on how to use the MPLAB® ICD In-Circuit Debugger (DV164001) with PIC16C62, 63, 64, 65, 72, 73, 74, 76, 77.
** Contact Microchip Technology Inc. for availability date.
† Development tool is available on select devices.PIC18FXX2
DS39564C-page 258 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 259
PIC18FXX2
22.0 ELECTRICAL CHARACTERISTICS
Absolute Maximum Ratings (†)
Ambient temperature under bias.............................................................................................................-55°C to +125°C
Storage temperature .............................................................................................................................. -65°C to +150°C
Voltage on any pin with respect to VSS (except VDD, MCLR, and RA4) ......................................... -0.3V to (VDD + 0.3V)
Voltage on VDD with respect to VSS ......................................................................................................... -0.3V to +7.5V
Voltage on MCLR with respect to VSS (Note 2) ......................................................................................... 0V to +13.25V
Voltage on RA4 with respect to Vss............................................................................................................... 0V to +8.5V
Total power dissipation (Note 1) ...............................................................................................................................1.0W
Maximum current out of VSS pin ...........................................................................................................................300 mA
Maximum current into VDD pin ..............................................................................................................................250 mA
Input clamp current, IIK (VI < 0 or VI > VDD)...................................................................................................................... ±20 mA
Output clamp current, IOK (VO < 0 or VO > VDD) .............................................................................................................. ±20 mA
Maximum output current sunk by any I/O pin..........................................................................................................25 mA
Maximum output current sourced by any I/O pin ....................................................................................................25 mA
Maximum current sunk by PORTA, PORTB, and PORTE (Note 3) (combined)...................................................200 mA
Maximum current sourced by PORTA, PORTB, and PORTE (Note 3) (combined)..............................................200 mA
Maximum current sunk by PORTC and PORTD (Note 3) (combined)..................................................................200 mA
Maximum current sourced by PORTC and PORTD (Note 3) (combined).............................................................200 mA
Note 1: Power dissipation is calculated as follows:
Pdis = VDD x {IDD - ∑ IOH} + ∑ {(VDD-VOH) x IOH} + ∑(VOl x IOL)
2: Voltage spikes below VSS at the MCLR/VPP pin, inducing currents greater than 80 mA, may cause latchup.
Thus, a series resistor of 50-100Ω should be used when applying a “low” level to the MCLR/VPP pin, rather
than pulling this pin directly to VSS.
3: PORTD and PORTE not available on the PIC18F2X2 devices.
† NOTICE: Stresses above those listed under “Absolute Maximum Ratings” may cause permanent damage to the
device. This is a stress rating only and functional operation of the device at those or any other conditions above those
indicated in the operation listings of this specification is not implied. Exposure to maximum rating conditions for
extended periods may affect device reliability.PIC18FXX2
DS39564C-page 260 © 2006 Microchip Technology Inc.
FIGURE 22-1: PIC18FXX2 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
FIGURE 22-2: PIC18LFXX2 VOLTAGE-FREQUENCY GRAPH (INDUSTRIAL)
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
PIC18FXXX
4.2V
Frequency
Voltage
6.0V
5.5V
4.5V
4.0V
2.0V
40 MHz
5.0V
3.5V
3.0V
2.5V
PIC18LFXXX
FMAX = (16.36 MHz/V) (VDDAPPMIN – 2.0V) + 4 MHz
Note: VDDAPPMIN is the minimum voltage of the PICmicro® device in the application.
4 MHz
4.2V© 2006 Microchip Technology Inc. DS39564C-page 261
PIC18FXX2
22.1 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial)
PIC18LFXX2
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18FXX2
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
VDD Supply Voltage
D001 PIC18LFXX2 2.0 — 5.5 V HS, XT, RC and LP Osc mode
D001 PIC18FXX2 4.2 — 5.5 V
D002 VDR RAM Data Retention
Voltage(1)
1.5 — — V
D003 VPOR VDD Start Voltage
to ensure internal
Power-on Reset signal
— — 0.7 V See Section 3.1 (Power-on Reset) for details
D004 SVDD VDD Rise Rate
to ensure internal
Power-on Reset signal
0.05 — — V/ms See Section 3.1 (Power-on Reset) for details
VBOR Brown-out Reset Voltage
D005 PIC18LFXX2
BORV1:BORV0 = 11 1.98 — 2.14 V 85°C ≥ T ≥ 25°C
BORV1:BORV0 = 10 2.67 — 2.89 V
BORV1:BORV0 = 01 4.16 — 4.5 V
BORV1:BORV0 = 00 4.45 — 4.83 V
D005 PIC18FXX2
BORV1:BORV0 = 1x N.A. — N.A. V Not in operating voltage range of device
BORV1:BORV0 = 01 4.16 — 4.5 V
BORV1:BORV0 = 00 4.45 — 4.83 V
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in SLEEP mode, or during a device RESET, without losing RAM data.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active Operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins in hi-impedance state and tied to VDD or VSS, and all
features that add delta current disabled (such as WDT, Timer1 Oscillator, BOR,...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be
estimated by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
5: The LVD and BOR modules share a large portion of circuitry. The ΔIBOR and ΔILVD currents are not additive.
Once one of these modules is enabled, the other may also be enabled without further penalty.PIC18FXX2
DS39564C-page 262 © 2006 Microchip Technology Inc.
IDD Supply Current(2,4)
D010 PIC18LFXX2
—
—
—
—
—
—
—
—
—
.5
.5
1.2
.3
.3
1.5
.3
.3
.75
1
1.25
2
1
1
3
1
1
3
mA
mA
mA
mA
mA
mA
mA
mA
mA
XT osc configuration
VDD = 2.0V, +25°C, FOSC = 4 MHz
VDD = 2.0V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
RC osc configuration
VDD = 2.0V, +25°C, FOSC = 4 MHz
VDD = 2.0V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
RCIO osc configuration
VDD = 2.0V, +25°C, FOSC = 4 MHz
VDD = 2.0V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
D010 PIC18FXX2
—
—
—
—
—
—
—
—
—
1.2
1.2
1.2
1.5
1.5
1.6
.75
.75
.8
1.5
2
3
3
4
4
2
3
3
mA
mA
mA
mA
mA
mA
mA
mA
mA
XT osc configuration
VDD = 4.2V, +25°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +125°C, FOSC = 4 MHz
RC osc configuration
VDD = 4.2V, +25°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +125°C, FOSC = 4 MHz
RCIO osc configuration
VDD = 4.2V, +25°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +85°C, FOSC = 4 MHz
VDD = 4.2V, -40°C to +125°C, FOSC = 4 MHz
D010A PIC18LFXX2
— 14 30 μA
LP osc, FOSC = 32 kHz, WDT disabled
VDD = 2.0V, -40°C to +85°C
D010A PIC18FXX2
—
—
40
50
70
100
μA
μA
LP osc, FOSC = 32 kHz, WDT disabled
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
22.1 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial) (Continued)
PIC18LFXX2
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18FXX2
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in SLEEP mode, or during a device RESET, without losing RAM data.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active Operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins in hi-impedance state and tied to VDD or VSS, and all
features that add delta current disabled (such as WDT, Timer1 Oscillator, BOR,...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be
estimated by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
5: The LVD and BOR modules share a large portion of circuitry. The ΔIBOR and ΔILVD currents are not additive.
Once one of these modules is enabled, the other may also be enabled without further penalty.© 2006 Microchip Technology Inc. DS39564C-page 263
PIC18FXX2
IDD Supply Current(2,4) (Continued)
D010C PIC18LFXX2
— 10 25 mA
EC, ECIO osc configurations
VDD = 4.2V, -40°C to +85°C
D010C PIC18FXX2
— 10 25 mA
EC, ECIO osc configurations
VDD = 4.2V, -40°C to +125°C
D013 PIC18LFXX2
—
—
—
.6
10
15
2
15
25
mA
mA
mA
HS osc configuration
FOSC = 4 MHz, VDD = 2.0V
FOSC = 25 MHz, VDD = 5.5V
HS + PLL osc configurations
FOSC = 10 MHz, VDD = 5.5V
D013 PIC18FXX2
—
—
10
15
15
25
mA
mA
HS osc configuration
FOSC = 25 MHz, VDD = 5.5V
HS + PLL osc configurations
FOSC = 10 MHz, VDD = 5.5V
D014 PIC18LFXX2
— 15 55 μA
Timer1 osc configuration
FOSC = 32 kHz, VDD = 2.0V
D014 PIC18FXX2
—
—
—
—
200
250
μA
μA
Timer1 osc configuration
FOSC = 32 kHz, VDD = 4.2V, -40°C to +85°C
FOSC = 32 kHz, VDD = 4.2V, -40°C to +125°C
IPD Power-down Current(3)
D020 PIC18LFXX2 —
—
—
.08
.1
3
.9
4
10
μA
μA
μA
VDD = 2.0V, +25°C
VDD = 2.0V, -40°C to +85°C
VDD = 4.2V, -40°C to +85°C
D020
D021B
PIC18FXX2 —
—
—
.1
3
15
.9
10
25
μA
μA
μA
VDD = 4.2V, +25°C
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
22.1 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial) (Continued)
PIC18LFXX2
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18FXX2
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in SLEEP mode, or during a device RESET, without losing RAM data.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active Operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins in hi-impedance state and tied to VDD or VSS, and all
features that add delta current disabled (such as WDT, Timer1 Oscillator, BOR,...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be
estimated by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
5: The LVD and BOR modules share a large portion of circuitry. The ΔIBOR and ΔILVD currents are not additive.
Once one of these modules is enabled, the other may also be enabled without further penalty.PIC18FXX2
DS39564C-page 264 © 2006 Microchip Technology Inc.
Module Differential Current
D022 ΔIWDT Watchdog Timer
PIC18LFXX2
—
—
—
.75
2
10
1.5
8
25
μA
μA
μA
VDD = 2.0V, +25°C
VDD = 2.0V, -40°C to +85°C
VDD = 4.2V, -40°C to +85°C
D022 Watchdog Timer
PIC18FXX2
—
—
—
7
10
25
15
25
40
μA
μA
μA
VDD = 4.2V, +25°C
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
D022A ΔIBOR Brown-out Reset(5)
PIC18LFXX2
—
—
—
29
29
33
35
45
50
μA
μA
μA
VDD = 2.0V, +25°C
VDD = 2.0V, -40°C to +85°C
VDD = 4.2V, -40°C to +85°C
D022A Brown-out Reset(5)
PIC18FXX2
—
—
—
36
36
36
40
50
65
μA
μA
μA
VDD = 4.2V, +25°C
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
D022B ΔILVD Low Voltage Detect(5)
PIC18LFXX2
—
—
—
29
29
33
35
45
50
μA
μA
μA
VDD = 2.0V, +25°C
VDD = 2.0V, -40°C to +85°C
VDD = 4.2V, -40°C to +85°C
D022B Low Voltage Detect(5)
PIC18FXX2
—
—
—
33
33
33
40
50
65
μA
μA
μA
VDD = 4.2V, +25°C
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
D025 ΔITMR1 Timer1 Oscillator
PIC18LFXX2
—
—
—
5.2
5.2
6.5
30
40
50
μA
μA
μA
VDD = 2.0V, +25°C
VDD = 2.0V, -40°C to +85°C
VDD = 4.2V, -40°C to +85°C
D025 Timer1 Oscillator
PIC18FXX2
—
—
—
6.5
6.5
6.5
40
50
65
μA
μA
μA
VDD = 4.2V, +25°C
VDD = 4.2V, -40°C to +85°C
VDD = 4.2V, -40°C to +125°C
22.1 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial) (Continued)
PIC18LFXX2
(Industrial)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
PIC18FXX2
(Industrial, Extended)
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
Legend: Shading of rows is to assist in readability of the table.
Note 1: This is the limit to which VDD can be lowered in SLEEP mode, or during a device RESET, without losing RAM data.
2: The supply current is mainly a function of the operating voltage and frequency. Other factors, such as I/O pin
loading and switching rate, oscillator type, internal code execution pattern and temperature, also have an
impact on the current consumption.
The test conditions for all IDD measurements in active Operation mode are:
OSC1 = external square wave, from rail-to-rail; all I/O pins tri-stated, pulled to VDD
MCLR = VDD; WDT enabled/disabled as specified.
3: The power-down current in SLEEP mode does not depend on the oscillator type. Power-down current is
measured with the part in SLEEP mode, with all I/O pins in hi-impedance state and tied to VDD or VSS, and all
features that add delta current disabled (such as WDT, Timer1 Oscillator, BOR,...).
4: For RC osc configuration, current through REXT is not included. The current through the resistor can be
estimated by the formula Ir = VDD/2REXT (mA) with REXT in kOhm.
5: The LVD and BOR modules share a large portion of circuitry. The ΔIBOR and ΔILVD currents are not additive.
Once one of these modules is enabled, the other may also be enabled without further penalty.© 2006 Microchip Technology Inc. DS39564C-page 265
PIC18FXX2
22.2 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial)
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Max Units Conditions
VIL Input Low Voltage
I/O ports:
D030 with TTL buffer Vss 0.15 VDD V VDD < 4.5V
D030A — 0.8 V 4.5V ≤ VDD ≤ 5.5V
D031 with Schmitt Trigger buffer
RC3 and RC4
Vss
Vss
0.2 VDD
0.3 VDD
V
V
D032 MCLR VSS 0.2 VDD V
D032A OSC1 (in XT, HS and LP modes)
and T1OSI
VSS 0.3 VDD V
D033 OSC1 (in RC and EC mode)(1) VSS 0.2 VDD V
VIH Input High Voltage
I/O ports:
D040 with TTL buffer 0.25 VDD +
0.8V
VDD V VDD < 4.5V
D040A 2.0 VDD V 4.5V ≤ VDD ≤ 5.5V
D041 with Schmitt Trigger buffer
RC3 and RC4
0.8 VDD
0.7 VDD
VDD
VDD
V
V
D042 MCLR, OSC1 (EC mode) 0.8 VDD VDD V
D042A OSC1 (in XT, HS and LP modes)
and T1OSI
0.7 VDD VDD V
D043 OSC1 (RC mode)(1) 0.9 VDD VDD V
IIL Input Leakage Current(2,3)
D060 I/O ports .02 ±1 μA VSS ≤ VPIN ≤ VDD,
Pin at hi-impedance
D061 MCLR — ±1 μA Vss ≤ VPIN ≤ VDD
D063 OSC1 — ±1 μA Vss ≤ VPIN ≤ VDD
IPU Weak Pull-up Current
D070 IPURB PORTB weak pull-up current 50 450 μA VDD = 5V, VPIN = VSS
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PICmicro device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.
4: Parameter is characterized but not tested.PIC18FXX2
DS39564C-page 266 © 2006 Microchip Technology Inc.
VOL Output Low Voltage
D080 I/O ports — 0.6 V IOL = 8.5 mA, VDD = 4.5V,
-40°C to +85°C
D080A — 0.6 V IOL = 7.0 mA, VDD = 4.5V,
-40°C to +125°C
D083 OSC2/CLKO
(RC mode)
— 0.6 V IOL = 1.6 mA, VDD = 4.5V,
-40°C to +85°C
D083A — 0.6 V IOL = 1.2 mA, VDD = 4.5V,
-40°C to +125°C
VOH Output High Voltage(3)
D090 I/O ports VDD – 0.7 — V IOH = -3.0 mA, VDD = 4.5V,
-40°C to +85°C
D090A VDD – 0.7 — V IOH = -2.5 mA, VDD = 4.5V,
-40°C to +125°C
D092 OSC2/CLKO
(RC mode)
VDD – 0.7 — V IOH = -1.3 mA, VDD = 4.5V,
-40°C to +85°C
D092A VDD – 0.7 — V IOH = -1.0 mA, VDD = 4.5V,
-40°C to +125°C
D150 VOD Open Drain High Voltage — 8.5 V RA4 pin
Capacitive Loading Specs
on Output Pins
D100(4) COSC2 OSC2 pin — 15 pF In XT, HS and LP modes
when external clock is used
to drive OSC1
D101 CIO All I/O pins and OSC2
(in RC mode)
— 50 pF To meet the AC Timing
Specifications
D102 CB SCL, SDA — 400 pF In I2C mode
22.2 DC Characteristics: PIC18FXX2 (Industrial, Extended)
PIC18LFXX2 (Industrial) (Continued)
DC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Max Units Conditions
Note 1: In RC oscillator configuration, the OSC1/CLKI pin is a Schmitt Trigger input. It is not recommended that the
PICmicro device be driven with an external clock while in RC mode.
2: The leakage current on the MCLR pin is strongly dependent on the applied voltage level. The specified
levels represent normal operating conditions. Higher leakage current may be measured at different input
voltages.
3: Negative current is defined as current sourced by the pin.
4: Parameter is characterized but not tested.© 2006 Microchip Technology Inc. DS39564C-page 267
PIC18FXX2
FIGURE 22-3: LOW VOLTAGE DETECT CHARACTERISTICS
TABLE 22-1: LOW VOLTAGE DETECT CHARACTERISTICS
VLVD
LVDIF
VDD
(LVDIF set by hardware)
(LVDIF can be
cleared in software)
37
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Symbol Characteristic Min Typ Max Units Conditions
D420 VLVD LVD Voltage on VDD
transition high to
low
LVV = 0001 1.98 2.06 2.14 V T ≥ 25°C
LVV = 0010 2.18 2.27 2.36 V T ≥ 25°C
LVV = 0011 2.37 2.47 2.57 V T ≥ 25°C
LVV = 0100 2.48 2.58 2.68 V
LVV = 0101 2.67 2.78 2.89 V
LVV = 0110 2.77 2.89 3.01 V
LVV = 0111 2.98 3.1 3.22 V
LVV = 1000 3.27 3.41 3.55 V
LVV = 1001 3.47 3.61 3.75 V
LVV = 1010 3.57 3.72 3.87 V
LVV = 1011 3.76 3.92 4.08 V
LVV = 1100 3.96 4.13 4.3 V
LVV = 1101 4.16 4.33 4.5 V
LVV = 1110 4.45 4.64 4.83 VPIC18FXX2
DS39564C-page 268 © 2006 Microchip Technology Inc.
TABLE 22-2: MEMORY PROGRAMMING REQUIREMENTS
DC Characteristics
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Param
No. Sym Characteristic Min Typ† Max Units Conditions
Internal Program Memory
Programming Specifications
D110 VPP Voltage on MCLR/VPP pin 9.00 — 13.25 V
D113 IDDP Supply Current during
Programming
— — 10 mA
Data EEPROM Memory
D120 ED Cell Endurance 100K 1M — E/W -40°C to +85°C
D121 VDRW VDD for Read/Write VMIN — 5.5 V Using EECON to read/write
VMIN = Minimum operating
voltage
D122 TDEW Erase/Write Cycle Time — 4 — ms
D123 TRETD Characteristic Retention 40 — — Year Provided no other
specifications are violated
D124 TREF Number of Total Erase/Write
Cycles before Refresh(1)
1M 10M — E/W -40°C to +85°C
Program FLASH Memory
D130 EP Cell Endurance 10K 100K — E/W -40°C to +85°C
D131 VPR VDD for Read VMIN — 5.5 V VMIN = Minimum operating
voltage
D132 VIE VDD for Block Erase 4.5 — 5.5 V Using ICSP port
D132A VIW VDD for Externally Timed Erase
or Write
4.5 — 5.5 V Using ICSP port
D132B VPEW VDD for Self-timed Write VMIN — 5.5 V VMIN = Minimum operating
voltage
D133 TIE ICSP Block Erase Cycle Time — 4 — ms VDD ≥ 4.5V
D133A TIW ICSP Erase or Write Cycle Time
(externally timed)
1 — — ms VDD ≥ 4.5V
D133A TIW Self-timed Write Cycle Time — 2 — ms
D134 TRETD Characteristic Retention 40 — — Year Provided no other
specifications are violated
† Data in “Typ” column is at 5.0V, 25°C unless otherwise stated. These parameters are for design guidance
only and are not tested.
Note 1: Refer to Section 6.8 for a more detailed discussion on data EEPROM endurance.© 2006 Microchip Technology Inc. DS39564C-page 269
PIC18FXX2
22.3 AC (Timing) Characteristics
22.3.1 TIMING PARAMETER SYMBOLOGY
The timing parameter symbols have been created
following one of the following formats:
1. TppS2ppS 3. TCC:ST (I2C specifications only)
2. TppS 4. Ts (I2C specifications only)
T
F Frequency T Time
Lowercase letters (pp) and their meanings:
pp
cc CCP1 osc OSC1
ck CLKO rd RD
cs CS rw RD or WR
di SDI sc SCK
do SDO ss SS
dt Data in t0 T0CKI
io I/O port t1 T1CKI
mc MCLR wr WR
Uppercase letters and their meanings:
S
F Fall P Period
H High R Rise
I Invalid (Hi-impedance) V Valid
L Low Z Hi-impedance
I
2C only
AA output access High High
BUF Bus free Low Low
TCC:ST (I2C specifications only)
CC
HD Hold SU Setup
ST
DAT DATA input hold STO STOP condition
STA START conditionPIC18FXX2
DS39564C-page 270 © 2006 Microchip Technology Inc.
22.3.2 TIMING CONDITIONS
The temperature and voltages specified in Table 22-3
apply to all timing specifications unless otherwise
noted. Figure 22-4 specifies the load conditions for the
timing specifications.
TABLE 22-3: TEMPERATURE AND VOLTAGE SPECIFICATIONS - AC
FIGURE 22-4: LOAD CONDITIONS FOR DEVICE TIMING SPECIFICATIONS
AC CHARACTERISTICS
Standard Operating Conditions (unless otherwise stated)
Operating temperature -40°C ≤ TA ≤ +85°C for industrial
-40°C ≤ TA ≤ +125°C for extended
Operating voltage VDD range as described in DC spec Section 22.1 and
Section 22.2.
LC parts operate for industrial temperatures only.
VDD/2
CL
RL
Pin
Pin
VSS
VSS
CL
RL = 464Ω
CL = 50 pF for all pins except OSC2/CLKO
and including D and E outputs as ports
Load condition 1 Load condition 2© 2006 Microchip Technology Inc. DS39564C-page 271
PIC18FXX2
22.3.3 TIMING DIAGRAMS AND SPECIFICATIONS
FIGURE 22-5: EXTERNAL CLOCK TIMING (ALL MODES EXCEPT PLL)
TABLE 22-4: EXTERNAL CLOCK TIMING REQUIREMENTS
OSC1
CLKO
Q4 Q1 Q2 Q3 Q4 Q1
1
2
3 3 4 4
Param.
No. Symbol Characteristic Min Max Units Conditions
1A FOSC External CLKI Frequency(1) DC 40 MHz EC, ECIO, -40°C to +85°C
Oscillator Frequency(1) DC 25 MHz EC, ECIO, +85°C to +125°C
DC 4 MHz RC osc
0.1 4 MHz XT osc
4 25 MHz HS osc
4 10 MHz HS + PLL osc, -40°C to +85°C
4 6.25 MHz HS + PLL osc, +85°C to +125°C
5 200 kHz LP Osc mode
1 TOSC External CLKI Period(1) 25 — ns EC, ECIO, -40°C to +85°C
Oscillator Period(1) 40 — ns EC, ECIO, +85°C to +125°C
250 — ns RC osc
250 10,000 ns XT osc
40 250 ns HS osc
100 250 ns HS + PLL osc, -40°C to +85°C
160 250 ns HS + PLL osc, +85°C to +125°C
25 — μs LP osc
2 TCY Instruction Cycle Time(1) 100 — ns TCY = 4/FOSC, -40°C to +85°C
160 — ns TCY = 4/FOSC, +85°C to +125°C
3 TosL,
TosH
External Clock in (OSC1)
High or Low Time
30 — ns XT osc
2.5 — μs LP osc
10 — ns HS osc
4 TosR,
TosF
External Clock in (OSC1)
Rise or Fall Time
— 20 ns XT osc
— 50 ns LP osc
— 7.5 ns HS osc
Note 1: Instruction cycle period (TCY) equals four times the input oscillator time-base period for all configurations
except PLL. All specified values are based on characterization data for that particular oscillator type under
standard operating conditions with the device executing code. Exceeding these specified limits may result in
an unstable oscillator operation and/or higher than expected current consumption. All devices are tested to
operate at “min.” values with an external clock applied to the OSC1/CLKI pin. When an external clock input
is used, the “max.” cycle time limit is “DC” (no clock) for all devices.PIC18FXX2
DS39564C-page 272 © 2006 Microchip Technology Inc.
TABLE 22-5: PLL CLOCK TIMING SPECIFICATIONS (VDD = 4.2 TO 5.5V)
FIGURE 22-6: CLKO AND I/O TIMING
Param
No. Sym Characteristic Min Typ† Max Units Conditions
— FOSC Oscillator Frequency Range 4 — 10 MHz HS mode only
— FSYS On-chip VCO System Frequency 16 — 40 MHz HS mode only
— trc PLL Start-up Time (Lock Time) — — 2 ms
— ΔCLK CLKO Stability (Jitter) -2 — +2 %
† Data in “Typ” column is at 5V, 25°C unless otherwise stated. These parameters are for design guidance only
and are not tested.
Note: Refer to Figure 22-4 for load conditions.
OSC1
CLKO
I/O Pin
(input)
I/O Pin
(output)
Q4 Q1 Q2 Q3
10
13
14
17
20, 21
19 18
15
11
12
16
Old Value New Value© 2006 Microchip Technology Inc. DS39564C-page 273
PIC18FXX2
TABLE 22-6: CLKO AND I/O TIMING REQUIREMENTS
FIGURE 22-7: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER AND POWER-UP
TIMER TIMING
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
10 TosH2ckL OSC1↑ to CLKO↓ — 75 200 ns (Note 1)
11 TosH2ckH OSC1↑ to CLKO↑ — 75 200 ns (Note 1)
12 TckR CLKO rise time — 35 100 ns (Note 1)
13 TckF CLKO fall time — 35 100 ns (Note 1)
14 TckL2ioV CLKO↓ to Port out valid — — 0.5 TCY + 20 ns (Note 1)
15 TioV2ckH Port in valid before CLKO ↑ 0.25 TCY + 25 — — ns (Note 1)
16 TckH2ioI Port in hold after CLKO ↑ 0 — — ns (Note 1)
17 TosH2ioV OSC1↑ (Q1 cycle) to Port out valid — 50 150 ns
18 TosH2ioI OSC1↑ (Q2 cycle) to Port
input invalid (I/O in hold time)
PIC18FXXX 100 — — ns
18A PIC18LFXXX 200 — — ns
19 TioV2osH Port input valid to OSC1↑ (I/O in setup time) 0 — — ns
20 TioR Port output rise time PIC18FXXX — 10 25 ns
20A PIC18LFXXX — — 60 ns VDD = 2V
21 TioF Port output fall time PIC18FXXX — 10 25 ns
21A PIC18LFXXX — — 60 ns VDD = 2V
22†† TINP INT pin high or low time TCY — — ns
23†† TRBP RB7:RB4 change INT high or low time TCY — — ns
24†† TRCP RC7:RC4 change INT high or low time 20 ns
†† These parameters are asynchronous events not related to any internal clock edges.
Note 1: Measurements are taken in RC mode, where CLKO output is 4 x TOSC.
VDD
MCLR
Internal
POR
PWRT
Time-out
OSC
Time-out
Internal
Reset
Watchdog
Timer
Reset
33
32
30
31
34
I/O Pins
34
Note: Refer to Figure 22-4 for load conditions.PIC18FXX2
DS39564C-page 274 © 2006 Microchip Technology Inc.
FIGURE 22-8: BROWN-OUT RESET TIMING
TABLE 22-7: RESET, WATCHDOG TIMER, OSCILLATOR START-UP TIMER, POWER-UP TIMER
AND BROWN-OUT RESET REQUIREMENTS
VDD
BVDD
35
VBGAP = 1.2V
VIRVST
Enable Internal Reference Voltage
Internal Reference Voltage stable 36
Typical
Param.
No. Symbol Characteristic Min Typ Max Units Conditions
30 TmcL MCLR Pulse Width (low) 2 — — μs
31 TWDT Watchdog Timer Time-out Period
(No Postscaler)
7 18 33 ms
32 TOST Oscillation Start-up Timer Period 1024 TOSC — 1024 TOSC — TOSC = OSC1 period
33 TPWRT Power up Timer Period 28 72 132 ms
34 TIOZ I/O Hi-impedance from MCLR Low
or Watchdog Timer Reset
—2— μs
35 TBOR Brown-out Reset Pulse Width 200 — — μs VDD ≤ BVDD (see
D005)
36 TIVRST Time for Internal Reference
Voltage to become stable
— 20 500 μs
37 TLVD Low Voltage Detect Pulse Width 200 — — μs VDD ≤ VLVD (see
D420)© 2006 Microchip Technology Inc. DS39564C-page 275
PIC18FXX2
FIGURE 22-9: TIMER0 AND TIMER1 EXTERNAL CLOCK TIMINGS
TABLE 22-8: TIMER0 AND TIMER1 EXTERNAL CLOCK REQUIREMENTS
Note: Refer to Figure 22-4 for load conditions.
46
47
45
48
41
42
40
T0CKI
T1OSO/T1CKI
TMR0 or
TMR1
Param
No. Symbol Characteristic Min Max Units Conditions
40 Tt0H T0CKI High Pulse Width No Prescaler 0.5TCY + 20 — ns
With Prescaler 10 — ns
41 Tt0L T0CKI Low Pulse Width No Prescaler 0.5TCY + 20 — ns
With Prescaler 10 — ns
42 Tt0P T0CKI Period No Prescaler TCY + 10 — ns
With Prescaler Greater of:
20 nS or TCY + 40
N
— ns N = prescale
value
(1, 2, 4,..., 256)
45 Tt1H T1CKI High
Time
Synchronous, no prescaler 0.5TCY + 20 — ns
Synchronous,
with prescaler
PIC18FXXX 10 — ns
PIC18LFXXX 25 — ns
Asynchronous PIC18FXXX 30 — ns
PIC18LFXXX 50 — ns
46 Tt1L T1CKI Low
Time
Synchronous, no prescaler 0.5TCY + 5 — ns
Synchronous,
with prescaler
PIC18FXXX 10 — ns
PIC18LFXXX 25 — ns
Asynchronous PIC18FXXX 30 — ns
PIC18LFXXX 50 — ns
47 Tt1P T1CKI input
period
Synchronous Greater of:
20 nS or TCY + 40
N
— ns N = prescale
value
(1, 2, 4, 8)
Asynchronous 60 — ns
Ft1 T1CKI oscillator input frequency range DC 50 kHz
48 Tcke2tmrI Delay from external T1CKI clock edge to timer
increment
2 TOSC 7 TOSC —PIC18FXX2
DS39564C-page 276 © 2006 Microchip Technology Inc.
FIGURE 22-10: CAPTURE/COMPARE/PWM TIMINGS (CCP1 AND CCP2)
TABLE 22-9: CAPTURE/COMPARE/PWM REQUIREMENTS (CCP1 AND CCP2)
Note: Refer to Figure 22-4 for load conditions.
CCPx
(Capture Mode)
50 51
52
CCPx
53 54
(Compare or PWM Mode)
Param.
No. Symbol Characteristic Min Max Units Conditions
50 TccL CCPx input low
time
No Prescaler 0.5 TCY + 20 — ns
With
Prescaler
PIC18FXXX 10 — ns
PIC18LFXXX 20 — ns
51 TccH CCPx input
high time
No Prescaler 0.5 TCY + 20 — ns
With
Prescaler
PIC18FXXX 10 — ns
PIC18LFXXX 20 — ns
52 TccP CCPx input period 3 TCY + 40
N
— ns N = prescale
value (1,4 or 16)
53 TccR CCPx output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
54 TccF CCPx output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V© 2006 Microchip Technology Inc. DS39564C-page 277
PIC18FXX2
FIGURE 22-11: PARALLEL SLAVE PORT TIMING (PIC18F4X2)
TABLE 22-10: PARALLEL SLAVE PORT REQUIREMENTS (PIC18F4X2)
Note: Refer to Figure 22-4 for load conditions.
RE2/CS
RE0/RD
RE1/WR
RD7:RD0
62
63
64
65
Param.
No. Symbol Characteristic Min Max Units Conditions
62 TdtV2wrH Data in valid before WR↑ or CS↑
(setup time)
20
25
—
—
ns
ns Extended Temp. Range
63 TwrH2dtI WR↑ or CS↑ to data–in invalid
(hold time)
PIC18FXXX 20 — ns
PIC18LFXXX 35 — ns VDD = 2V
64 TrdL2dtV RD↓ and CS↓ to data–out valid —
—
80
90
ns
ns Extended Temp. Range
65 TrdH2dtI RD↑ or CS↓ to data–out invalid 10 30 ns
66 TibfINH Inhibit of the IBF flag bit being cleared from
WR↑ or CS↑
— 3 TCYPIC18FXX2
DS39564C-page 278 © 2006 Microchip Technology Inc.
FIGURE 22-12: EXAMPLE SPI MASTER MODE TIMING (CKE = 0)
TABLE 22-11: EXAMPLE SPI MODE REQUIREMENTS (MASTER MODE, CKE = 0)
Param.
No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the 1st clock edge of Byte2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
76 TdoF SDO data output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
78 TscR SCK output rise time
(Master mode)
PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
79 TscF SCK output fall time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
80 TscH2doV,
TscL2doV
SDO data output valid after SCK
edge
PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter # 71A and # 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76
79 78 80
78 79
MSb LSb bit6 - - - - - -1
MSb In bit6 - - - -1 LSb In
Note: Refer to Figure 22-4 for load conditions.© 2006 Microchip Technology Inc. DS39564C-page 279
PIC18FXX2
FIGURE 22-13: EXAMPLE SPI MASTER MODE TIMING (CKE = 1)
TABLE 22-12: EXAMPLE SPI MODE REQUIREMENTS (MASTER MODE, CKE = 1)
Param.
No. Symbol Characteristic Min Max Units Conditions
71 TscH SCK input high time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the 1st clock edge of Byte2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
76 TdoF SDO data output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
78 TscR SCK output rise time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
79 TscF SCK output fall time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
80 TscH2doV,
TscL2doV
SDO data output valid after SCK
edge
PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
81 TdoV2scH,
TdoV2scL
SDO data output setup to SCK edge TCY — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter # 71A and # 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
81
71 72
74
75, 76
78
80
MSb
79
73
MSb In
bit6 - - - - - -1
bit6 - - - -1 LSb In
LSb
Note: Refer to Figure 22-4 for load conditions.PIC18FXX2
DS39564C-page 280 © 2006 Microchip Technology Inc.
FIGURE 22-14: EXAMPLE SPI SLAVE MODE TIMING (CKE = 0)
TABLE 22-13: EXAMPLE SPI MODE REQUIREMENTS (SLAVE MODE TIMING (CKE = 0))
Param. No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time (Slave mode) Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time (Slave mode) Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73 TdiV2scH,
TdiV2scL
Setup time of SDI data input to SCK edge 100 — ns
73A TB2B Last clock edge of Byte1 to the first clock edge of Byte2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
76 TdoF SDO data output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
77 TssH2doZ SS↑ to SDO output hi-impedance 10 50 ns
78 TscR SCK output rise time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
79 TscF SCK output fall time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
80 TscH2doV,
TscL2doV
SDO data output valid after SCK edge PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK edge 1.5 TCY + 40 — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter # 71A and # 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
73
74
75, 76 77
79 78 80
78 79
SDI
MSb LSb bit6 - - - - - -1
MSb In bit6 - - - -1 LSb In
83
Note: Refer to Figure 22-4 for load conditions.© 2006 Microchip Technology Inc. DS39564C-page 281
PIC18FXX2
FIGURE 22-15: EXAMPLE SPI SLAVE MODE TIMING (CKE = 1)
TABLE 22-14: EXAMPLE SPI SLAVE MODE REQUIREMENTS (CKE = 1)
Param. No. Symbol Characteristic Min Max Units Conditions
70 TssL2scH,
TssL2scL
SS↓ to SCK↓ or SCK↑ input TCY — ns
71 TscH SCK input high time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
71A Single Byte 40 — ns (Note 1)
72 TscL SCK input low time
(Slave mode)
Continuous 1.25 TCY + 30 — ns
72A Single Byte 40 — ns (Note 1)
73A TB2B Last clock edge of Byte1 to the first clock edge of Byte2 1.5 TCY + 40 — ns (Note 2)
74 TscH2diL,
TscL2diL
Hold time of SDI data input to SCK edge 100 — ns
75 TdoR SDO data output rise time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
76 TdoF SDO data output fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
77 TssH2doZ SS↑ to SDO output hi-impedance 10 50 ns
78 TscR SCK output rise time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
79 TscF SCK output fall time (Master mode) PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
80 TscH2doV,
TscL2doV
SDO data output valid after SCK
edge
PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
82 TssL2doV SDO data output valid after SS↓ edge PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
83 TscH2ssH,
TscL2ssH
SS ↑ after SCK edge 1.5 TCY + 40 — ns
Note 1: Requires the use of Parameter # 73A.
2: Only if Parameter # 71A and # 72A are used.
SS
SCK
(CKP = 0)
SCK
(CKP = 1)
SDO
SDI
70
71 72
82
74
75, 76
MSb bit6 - - - - - -1 LSb
77
MSb In bit6 - - - -1 LSb In
80
83
Note: Refer to Figure 22-4 for load conditions.PIC18FXX2
DS39564C-page 282 © 2006 Microchip Technology Inc.
FIGURE 22-16: I2C BUS START/STOP BITS TIMING
TABLE 22-15: I2C BUS START/STOP BITS REQUIREMENTS (SLAVE MODE)
FIGURE 22-17: I2C BUS DATA TIMING
Note: Refer to Figure 22-4 for load conditions.
91
92
93
SCL
SDA
START
Condition
STOP
Condition
90
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA START condition 100 kHz mode 4700 — ns Only relevant for Repeated
Setup time 400 kHz mode 600 — START condition
91 THD:STA START condition 100 kHz mode 4000 — ns After this period, the first
Hold time 400 kHz mode 600 — clock pulse is generated
92 TSU:STO STOP condition 100 kHz mode 4700 — ns
Setup time 400 kHz mode 600 —
93 THD:STO STOP condition 100 kHz mode 4000 — ns
Hold time 400 kHz mode 600 —
Note: Refer to Figure 22-4 for load conditions.
90
91 92
100
101
103
106 107
109 109
110
102
SCL
SDA
In
SDA
Out© 2006 Microchip Technology Inc. DS39564C-page 283
PIC18FXX2
TABLE 22-16: I2C BUS DATA REQUIREMENTS (SLAVE MODE)
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock high time 100 kHz mode 4.0 — μs PIC18FXXX must operate at a
minimum of 1.5 MHz
400 kHz mode 0.6 — μs PIC18FXXX must operate at a
minimum of 10 MHz
SSP Module 1.5 TCY —
101 TLOW Clock low time 100 kHz mode 4.7 — μs PIC18FXXX must operate at a
minimum of 1.5 MHz
400 kHz mode 1.3 — μs PIC18FXXX must operate at a
minimum of 10 MHz
SSP Module 1.5 TCY —
102 TR SDA and SCL rise
time
100 kHz mode — 1000 ns
400 kHz mode 20 + 0.1 CB 300 ns CB is specified to be from
10 to 400 pF
103 TF SDA and SCL fall
time
100 kHz mode — 1000 ns VDD ≥ 4.2V
400 kHz mode 20 + 0.1 CB 300 ns VDD ≥ 4.2V
90 TSU:STA START condition
setup time
100 kHz mode 4.7 — μs Only relevant for Repeated
START condition 400 kHz mode 0.6 — μs
91 THD:STA START condition hold
time
100 kHz mode 4.0 — μs After this period, the first clock
pulse is generated 400 kHz mode 0.6 — μs
106 THD:DAT Data input hold time 100 kHz mode 0 — ns
400 kHz mode 0 0.9 μs
107 TSU:DAT Data input setup time 100 kHz mode 250 — ns (Note 2)
400 kHz mode 100 — ns
92 TSU:STO STOP condition
setup time
100 kHz mode 4.7 — μs
400 kHz mode 0.6 — μs
109 TAA Output valid from
clock
100 kHz mode — 3500 ns (Note 1)
400 kHz mode — — ns
110 TBUF Bus free time 100 kHz mode 4.7 — μs Time the bus must be free
before a new transmission can
start
400 kHz mode 1.3 — μs
D102 CB Bus capacitive loading — 400 pF
Note 1: As a transmitter, the device must provide this internal minimum delay time to bridge the undefined region (min. 300 ns) of
the falling edge of SCL to avoid unintended generation of START or STOP conditions.
2: A Fast mode I2C bus device can be used in a Standard mode I2C bus system, but the requirement TSU:DAT ≥ 250 ns
must then be met. This will automatically be the case if the device does not stretch the LOW period of the SCL signal. If
such a device does stretch the LOW period of the SCL signal, it must output the next data bit to the SDA line.
TR max. + TSU:DAT = 1000 + 250 = 1250 ns (according to the Standard mode I2C bus specification) before the SCL line is
released. PIC18FXX2
DS39564C-page 284 © 2006 Microchip Technology Inc.
FIGURE 22-18: MASTER SSP I2C BUS START/STOP BITS TIMING WAVEFORMS
TABLE 22-17: MASTER SSP I2C BUS START/STOP BITS REQUIREMENTS
FIGURE 22-19: MASTER SSP I2C BUS DATA TIMING
Note: Refer to Figure 22-4 for load conditions.
91 93
SCL
SDA
START
Condition
STOP
Condition
90 92
Param.
No. Symbol Characteristic Min Max Units Conditions
90 TSU:STA START condition 100 kHz mode 2(TOSC)(BRG + 1) — ns Only relevant for
Repeated START
condition Setup time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
91 THD:STA START condition 100 kHz mode 2(TOSC)(BRG + 1) — ns After this period, the
first clock pulse is
generated Hold time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
92 TSU:STO STOP condition 100 kHz mode 2(TOSC)(BRG + 1) — ns
Setup time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
93 THD:STO STOP condition 100 kHz mode 2(TOSC)(BRG + 1) — ns
Hold time 400 kHz mode 2(TOSC)(BRG + 1) —
1 MHz mode(1) 2(TOSC)(BRG + 1) —
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
Note: Refer to Figure 22-4 for load conditions.
90
91 92
100
101
103
106
107
109 109 110
102
SCL
SDA
In
SDA
Out© 2006 Microchip Technology Inc. DS39564C-page 285
PIC18FXX2
TABLE 22-18: MASTER SSP I2C BUS DATA REQUIREMENTS
Param.
No. Symbol Characteristic Min Max Units Conditions
100 THIGH Clock high time 100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
101 TLOW Clock low time 100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
102 TR SDA and SCL
rise time
100 kHz mode — 1000 ns CB is specified to be from
10 to 400 pF 400 kHz mode 20 + 0.1 CB 300 ns
1 MHz mode(1) — 300 ns
103 TF SDA and SCL
fall time
100 kHz mode — 1000 ns VDD ≥ 4.2V
400 kHz mode 20 + 0.1 CB 300 ns VDD ≥ 4.2V
90 TSU:STA START condition
setup time
100 kHz mode 2(TOSC)(BRG + 1) — ms Only relevant for
Repeated START
condition 400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
91 THD:STA START condition
hold time
100 kHz mode 2(TOSC)(BRG + 1) — ms After this period, the first
clock pulse is generated 400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
106 THD:DAT Data input
hold time
100 kHz mode 0 — ns
400 kHz mode 0 0.9 ms
107 TSU:DAT Data input
setup time
100 kHz mode 250 — ns (Note 2)
400 kHz mode 100 — ns
92 TSU:STO STOP condition
setup time
100 kHz mode 2(TOSC)(BRG + 1) — ms
400 kHz mode 2(TOSC)(BRG + 1) — ms
1 MHz mode(1) 2(TOSC)(BRG + 1) — ms
109 TAA Output valid from
clock
100 kHz mode — 3500 ns
400 kHz mode — 1000 ns
1 MHz mode(1) — — ns
110 TBUF Bus free time 100 kHz mode 4.7 — ms Time the bus must be free
before a new transmission
can start
400 kHz mode 1.3 — ms
D102 CB Bus capacitive loading — 400 pF
Note 1: Maximum pin capacitance = 10 pF for all I2C pins.
2: A Fast mode I2C bus device can be used in a Standard mode I2C bus system, but parameter #107 ≥ 250 ns
must then be met. This will automatically be the case if the device does not stretch the LOW period of the SCL
signal. If such a device does stretch the LOW period of the SCL signal, it must output the next data bit to the
SDA line, parameter #102 + parameter #107 = 1000 + 250 = 1250 ns (for 100 kHz mode) before the SCL line
is released.PIC18FXX2
DS39564C-page 286 © 2006 Microchip Technology Inc.
FIGURE 22-20: USART SYNCHRONOUS TRANSMISSION (MASTER/SLAVE) TIMING
TABLE 22-19: USART SYNCHRONOUS TRANSMISSION REQUIREMENTS
FIGURE 22-21: USART SYNCHRONOUS RECEIVE (MASTER/SLAVE) TIMING
TABLE 22-20: USART SYNCHRONOUS RECEIVE REQUIREMENTS
121 121
120
122
RC6/TX/CK
RC7/RX/DT
pin
pin
Note: Refer to Figure 22-4 for load conditions.
Param.
No. Symbol Characteristic Min Max Units Conditions
120 TckH2dtV SYNC XMIT (MASTER & SLAVE)
Clock high to data out valid PIC18FXXX — 50 ns
PIC18LFXXX — 150 ns VDD = 2V
121 Tckr Clock out rise time and fall time
(Master mode)
PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
122 Tdtr Data out rise time and fall time PIC18FXXX — 25 ns
PIC18LFXXX — 60 ns VDD = 2V
125
126
RC6/TX/CK
RC7/RX/DT
pin
pin
Note: Refer to Figure 22-4 for load conditions.
Param.
No. Symbol Characteristic Min Max Units Conditions
125 TdtV2ckl SYNC RCV (MASTER & SLAVE)
Data hold before CK ↓ (DT hold time) 10 — ns
126 TckL2dtl Data hold after CK ↓ (DT hold time) PIC18FXXX 15 — ns
PIC18LFXXX 20 — ns VDD = 2V© 2006 Microchip Technology Inc. DS39564C-page 287
PIC18FXX2
TABLE 22-21: A/D CONVERTER CHARACTERISTICS: PIC18FXX2 (INDUSTRIAL, EXTENDED)
PIC18LFXX2 (INDUSTRIAL)
FIGURE 22-22: A/D CONVERSION TIMING
Param
No. Symbol Characteristic Min Typ Max Units Conditions
A01 NR Resolution — — 10 bit
A03 EIL Integral linearity error — — <±1 LSb VREF = VDD = 5.0V
A04 EDL Differential linearity error — — <±1 LSb VREF = VDD = 5.0V
A05 EG Gain error — — <±1 LSb VREF = VDD = 5.0V
A06 EOFF Offset error — — <±1.5 LSb VREF = VDD = 5.0V
A10 — Monotonicity guaranteed(2) — VSS ≤ VAIN ≤ VREF
A20
A20A
VREF Reference Voltage
(VREFH – VREFL)
1.8V
3V
—
—
—
—
V
V
VDD < 3.0V
VDD ≥ 3.0V
A21 VREFH Reference voltage High AVSS — AVDD + 0.3V V
A22 VREFL Reference voltage Low AVSS – 0.3V — VREFH V
A25 VAIN Analog input voltage AVSS – 0.3V — AVDD + 0.3V V VDD ≥ 2.5V (Note 3)
A30 ZAIN Recommended impedance of
analog voltage source
— — 2.5 kΩ (Note 4)
A50 IREF VREF input current (Note 1) —
—
—
—
5
150
μA
μA
During VAIN acquisition
During A/D conversion cycle
Note 1: Vss ≤ VAIN ≤ VREF
2: The A/D conversion result never decreases with an increase in the Input Voltage, and has no missing codes.
3: For VDD < 2.5V, VAIN should be limited to < .5 VDD.
4: Maximum allowed impedance for analog voltage source is 10 kΩ. This requires higher acquisition times.
131
130
132
BSF ADCON0, GO
Q4
A/D CLK
A/D DATA
ADRES
ADIF
GO
SAMPLE
OLD_DATA
SAMPLING STOPPED
DONE
NEW_DATA
(Note 2)
9 87 2 1 0
Note 1: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts.
This allows the SLEEP instruction to be executed.
2: This is a minimal RC delay (typically 100 nS), which also disconnects the holding capacitor from the analog input.
. . . . . .
TCYPIC18FXX2
DS39564C-page 288 © 2006 Microchip Technology Inc.
TABLE 22-22: A/D CONVERSION REQUIREMENTS
Param
No. Symbol Characteristic Min Max Units Conditions
130 TAD A/D clock period PIC18FXXX 1.6 20(4) μs TOSC based
PIC18FXXX 2.0 6.0 μs A/D RC mode
131 TCNV Conversion time
(not including acquisition time) (Note 1)
11 12 TAD
132 TACQ Acquisition time (Note 2) 5
10
—
—
μs
μs
VREF = VDD = 5.0V
VREF = VDD = 2.5V
135 TSWC Switching Time from convert → sample — (Note 3)
Note 1: ADRES register may be read on the following TCY cycle.
2: The time for the holding capacitor to acquire the “New” input voltage, when the new input value has not
changed by more than 1 LSB from the last sampled voltage. The source impedance (RS) on the input channels
is 50Ω. See Section 17.0 for more information on acquisition time consideration.
3: On the next Q4 cycle of the device clock.
4: The time of the A/D clock period is dependent on the device frequency and the TAD clock divider. © 2006 Microchip Technology Inc. DS39564C-page 289
PIC18FXX2
23.0 DC AND AC CHARACTERISTICS GRAPHS AND TABLES
“Typical” represents the mean of the distribution at 25°C. “Maximum” or “minimum” represents (mean + 3σ) or (mean - 3σ)
respectively, where σ is a standard deviation, over the whole temperature range.
FIGURE 23-1: TYPICAL IDD vs. FOSC OVER VDD (HS MODE)
FIGURE 23-2: MAXIMUM IDD vs. FOSC OVER VDD (HS MODE)
Note: The graphs and tables provided following this note are a statistical summary based on a limited number of
samples and are provided for informational purposes only. The performance characteristics listed herein are
not tested or guaranteed. In some graphs or tables, the data presented may be outside the specified
operating range (e.g., outside specified power supply range) and therefore, outside the warranted range.
0
2
4
6
8
10
12
4 6 8 10 12 14 16 18 20 22 24 26
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
2
4
6
8
10
12
4 6 8 10 12 14 16 18 20 22 24 26
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)PIC18FXX2
DS39564C-page 290 © 2006 Microchip Technology Inc.
FIGURE 23-3: TYPICAL IDD vs. FOSC OVER VDD (HS/PLL MODE)
FIGURE 23-4: MAXIMUM IDD vs. FOSC OVER VDD (HS/PLL MODE)
0
2
4
6
8
10
12
14
16
18
20
4 5 6 7 8 9 10
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
2
4
6
8
10
12
14
16
18
20
4 5 6 7 8 9 10
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.2V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)© 2006 Microchip Technology Inc. DS39564C-page 291
PIC18FXX2
FIGURE 23-5: TYPICAL IDD vs. FOSC OVER VDD (XT MODE)
FIGURE 23-6: MAXIMUM IDD vs. FOSC OVER VDD (XT MODE)
0
200
400
600
800
1,000
1,200
1,400
1,600
1,800
2,000
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (uA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
IDD (μA)
0
200
400
600
800
1,000
1,200
1,400
1,600
1,800
2,000
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
FOSC (MHz)
IDD (μA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)PIC18FXX2
DS39564C-page 292 © 2006 Microchip Technology Inc.
FIGURE 23-7: TYPICAL IDD vs. FOSC OVER VDD (LP MODE)
FIGURE 23-8: MAXIMUM IDD vs. FOSC OVER VDD (LP MODE)
0
10
20
30
40
50
60
70
80
90
100
20 30 40 50 60 70 80 90 100
FOSC (kHz)
IDD (uA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
20
40
60
80
100
120
140
20 30 40 50 60 70 80 90 100
FOSC (kHz)
IDD (uA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)© 2006 Microchip Technology Inc. DS39564C-page 293
PIC18FXX2
FIGURE 23-9: TYPICAL IDD vs. FOSC OVER VDD (EC MODE)
FIGURE 23-10: MAXIMUM IDD vs. FOSC OVER VDD (EC MODE)
0
2
4
6
8
10
12
14
16
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
4.2V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
2
4
6
8
10
12
14
16
4 8 12 16 20 24 28 32 36 40
FOSC (MHz)
IDD (mA)
5.5V
5.0V
4.5V
4.0V
3.5V
3.0V
2.5V
2.0V
4.2V
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)PIC18FXX2
DS39564C-page 294 © 2006 Microchip Technology Inc.
FIGURE 23-11: TYPICAL AND MAXIMUM IDD vs. VDD
(TIMER1 AS MAIN OSCILLATOR, 32.768 kHz, C1 AND C2 = 47 pF)
FIGURE 23-12: AVERAGE FOSC vs. VDD FOR VARIOUS VALUES OF R
(RC MODE, C = 20 pF, +25°C)
0
20
40
60
80
100
120
140
160
180
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
Typ (25C)
Max (70C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-10°C to 70°C)
Minimum: mean – 3σ (-10°C to 70°C)
IDD (μA)
Max (+70°C)
Typ (+25°C)
0
500
1,000
1,500
2,000
2,500
3,000
3,500
4,000
4,500
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (kHz)
3.3kΩ
5.1kΩ
10kΩ
100kΩ
Operation above 4 MHz is not recommended.© 2006 Microchip Technology Inc. DS39564C-page 295
PIC18FXX2
FIGURE 23-13: AVERAGE FOSC vs. VDD FOR VARIOUS VALUES OF R
(RC MODE, C = 100 pF, +25°C)
FIGURE 23-14: AVERAGE FOSC vs. VDD FOR VARIOUS VALUES OF R
(RC MODE, C = 300 pF, +25°C)
0
200
400
600
800
1,000
1,200
1,400
1,600
1,800
2,000
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (kHz)
3.3kΩ
5.1kΩ
10kΩ
100kΩ
0
100
200
300
400
500
600
700
800
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
Freq (MHz)
3.3kΩ
5.1kΩ
10kΩ
100kΩPIC18FXX2
DS39564C-page 296 © 2006 Microchip Technology Inc.
FIGURE 23-15: IPD vs. VDD, -40°C TO +125°C (SLEEP MODE, ALL PERIPHERALS DISABLED)
FIGURE 23-16: ΔIBOR vs. VDD OVER TEMPERATURE (BOR ENABLED, VBOR = 2.00 - 2.16V)
0.01
0.1
1
10
100
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
Typ (+25°C)
Max
(+85°C)
Max
(-40°C to +125°C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
10
20
30
40
50
60
70
80
90
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (μA)
Max (125C)
Max (85C)
Typ (25C)
Device
Held in
Reset
Device
in
Sleep
Max (+125°C)
Max (+85°C)
Typ (+25°C)
Device
Held in
RESET
Device
in
SLEEP© 2006 Microchip Technology Inc. DS39564C-page 297
PIC18FXX2
FIGURE 23-17: TYPICAL AND MAXIMUM ΔITMR1 vs. VDD OVER TEMPERATURE (-10°C TO +70°C,
TIMER1 WITH OSCILLATOR, XTAL = 32 kHz, C1 AND C2 = 47 pF)
FIGURE 23-18: TYPICAL AND MAXIMUM ΔIWDT vs. VDD OVER TEMPERATURE (WDT ENABLED)
0
2
4
6
8
10
12
14
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (uA)
Typ (25C)
Max (70C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-10°C to 70°C)
Minimum: mean – 3σ (-10°C to 70°C)
IPD (μA)
Max (+70°C)
Typ (+25°C)
0
10
20
30
40
50
60
70
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IPD (μA)
Max (125C)
Max (85C)
Typ (25C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
Max (+125°C)
Max (+85°C)
Typ (+25°C)PIC18FXX2
DS39564C-page 298 © 2006 Microchip Technology Inc.
FIGURE 23-19: TYPICAL, MINIMUM AND MAXIMUM WDT PERIOD vs. VDD (-40°C TO +125°C)
FIGURE 23-20: ΔILVD vs. VDD OVER TEMPERATURE (LVD ENABLED, VLVD = 4.5 - 4.78V)
0
5
10
15
20
25
30
35
40
45
50
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
WDT Period (ms)
Max
(125C)
MAX
(85C)
Typ
(25C)
Min
(-40C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
Max
(+125°C)
Max
(+85°C)
Typ
(+25°C)
Min
(-40°C)
0
10
20
30
40
50
60
70
80
90
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
IDD (μA)
Max (125C)
Typ (25C)
Max (125C)
Typ (25C)
LVDIF is set
by hardware
LVDIF can be
cleared by
firmware
LVDIF state
is unknown
Max (+125°C)
Max (+125°C)
Typ (+25°C)
Typ (+25°C)© 2006 Microchip Technology Inc. DS39564C-page 299
PIC18FXX2
FIGURE 23-21: TYPICAL, MINIMUM AND MAXIMUM VOH vs. IOH (VDD = 5V, -40°C TO +125°C)
FIGURE 23-22: TYPICAL, MINIMUM AND MAXIMUM VOH vs. IOH (VDD = 3V, -40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
0 5 10 15 20 25
IOH (-mA)
VOH (V)
Typ (25C)
Max
Min
Max
Typ (+25°C)
Min
0.0
0.5
1.0
1.5
2.0
2.5
3.0
0 5 10 15 20 25
IOH (-mA)
VOH (V)
Typ (25C)
Max
Min
Typ (+25°C)
Min
MaxPIC18FXX2
DS39564C-page 300 © 2006 Microchip Technology Inc.
FIGURE 23-23: TYPICAL AND MAXIMUM VOL vs. IOL (VDD = 5V, -40°C TO +125°C)
FIGURE 23-24: TYPICAL AND MAXIMUM VOL vs. IOL (VDD = 3V, -40°C TO +125°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
0 5 10 15 20 25
IOL (-mA)
VOL (V)
Max
Typ (25C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
Typ (+25°C)
Max
0.0
0.5
1.0
1.5
2.0
2.5
0 5 10 15 20 25
IOL (-mA)
VOL (V)
Max
Typ (25C)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
Typ (+25°C)
Max© 2006 Microchip Technology Inc. DS39564C-page 301
PIC18FXX2
FIGURE 23-25: MINIMUM AND MAXIMUM VIN vs. VDD (ST INPUT, -40°C TO +125°C)
FIGURE 23-26: MINIMUM AND MAXIMUM VIN vs. VDD (TTL INPUT, -40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
VIN (V)
VIH Max
VIH Min
VIL Max
VIL Min
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0.0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
VIN (V)
VTH (Max)
VTH (Min)
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)PIC18FXX2
DS39564C-page 302 © 2006 Microchip Technology Inc.
FIGURE 23-27: MINIMUM AND MAXIMUM VIN vs. VDD (I2C INPUT, -40°C TO +125°C)
FIGURE 23-28: A/D NON-LINEARITY vs. VREFH (VDD = VREFH, -40°C TO +125°C)
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (V)
VIN (V)
VIH Max
VIH Min
VILMax
VIL Min
Typical: statistical mean @ 25°C
Maximum: mean + 3σ (-40°C to 125°C)
Minimum: mean – 3σ (-40°C to 125°C)
0
0.5
1
1.5
2
2.5
3
3.5
4
2 2.5 3 3.5 4 4.5 5 5.5
VDD and VREFH (V)
Differential or Integral Nonlinearity (LSB)
-40C
25C
85C
125C
-40°C
+25°C
+85°C
+125°C© 2006 Microchip Technology Inc. DS39564C-page 303
PIC18FXX2
FIGURE 23-29: A/D NON-LINEARITY vs. VREFH (VDD = 5V, -40°C TO +125°C)
0
0.5
1
1.5
2
2.5
3
2 2.5 3 3.5 4 4.5 5 5.5
VREFH (V)
Differential or Integral Nonlinearilty (LSB)
Max (-40C to 125C)
Typ (+25°C) Typ (25C)
Max (-40°C to +125°C)PIC18FXX2
DS39564C-page 304 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 305
PIC18FXX2
24.0 PACKAGING INFORMATION
24.1 Package Marking Information
28-Lead SPDIP
XXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F242-I/SP
0610017
28-Lead SOIC
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F242-E/SO
0610017
40-Lead PDIP
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
YYWWNNN
Example
PIC18F442-I/P
0610017
Legend: XX...X Customer-specific information
Y Year code (last digit of calendar year)
YY Year code (last 2 digits of calendar year)
WW Week code (week of January 1 is week ‘01’)
NNN Alphanumeric traceability code
Pb-free JEDEC designator for Matte Tin (Sn)
* This package is Pb-free. The Pb-free JEDEC designator ( )
can be found on the outer packaging for this package.
Note: In the event the full Microchip part number cannot be marked on one line, it will
be carried over to the next line, thus limiting the number of available
characters for customer-specific information.
e3
e3
e3
e3
e3PIC18FXX2
DS39564C-page 306 © 2006 Microchip Technology Inc.
Package Marking Information (Cont’d)
44-Lead TQFP
XXXXXXXXXX
XXXXXXXXXX
XXXXXXXXXX
YYWWNNN
Example
PIC18F452
-E/PT
0610017
44-Lead PLCC
XXXXXXXXXX
XXXXXXXXXX
XXXXXXXXXX
YYWWNNN
Example
PIC18F442
-I/L
0610017
e3
e3© 2006 Microchip Technology Inc. DS39564C-page 307
PIC18FXX2
24.2 Package Details
The following sections give the technical details of the packages.
28-Lead Skinny Plastic Dual In-line (SP) – 300 mil Body (PDIP)
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Mold Draft Angle Bottom β 5 10 15 5 10 15
Mold Draft Angle Top α 5 10 15 5 10 15
Overall Row Spacing § eB .320 .350 .430 8.13 8.89 10.92
Lower Lead Width B .016 .019 .022 0.41 0.48 0.56
Upper Lead Width B1 .040 .053 .065 1.02 1.33 1.65
Lead Thickness c .008 .012 .015 0.20 0.29 0.38
Tip to Seating Plane L .125 .130 .135 3.18 3.30 3.43
Overall Length D 1.345 1.365 1.385 34.16 34.67 35.18
Molded Package Width E1 .275 .285 .295 6.99 7.24 7.49
Shoulder to Shoulder Width E .300 .310 .325 7.62 7.87 8.26
Base to Seating Plane A1 .015 0.38
Molded Package Thickness A2 .125 .130 .135 3.18 3.30 3.43
Top to Seating Plane A .140 .150 .160 3.56 3.81 4.06
Pitch p .100 2.54
Number of Pins n 28 28
Dimension Limits MIN NOM MAX MIN NOM MAX
Units INCHES* MILLIMETERS
2
1
D
n
E1
c
eB
β
E
α
p
L
A2
B
B1
A
A1
Notes:
JEDEC Equivalent: MO-095
Drawing No. C04-070
* Controlling Parameter
Dimension D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010” (0.254mm) per side.
§ Significant CharacteristicPIC18FXX2
DS39564C-page 308 © 2006 Microchip Technology Inc.
28-Lead Plastic Small Outline (SO) – Wide, 300 mil Body (SOIC)
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Foot Angle Top φ 048048
Mold Draft Angle Bottom β 0 12 15 0 12 15
Mold Draft Angle Top α 0 12 15 0 12 15
Lead Width B .014 .017 .020 0.36 0.42 0.51
Lead Thickness c .009 .011 .013 0.23 0.28 0.33
Foot Length L .016 .033 .050 0.41 0.84 1.27
Chamfer Distance h .010 .020 .029 0.25 0.50 0.74
Overall Length D .695 .704 .712 17.65 17.87 18.08
Molded Package Width E1 .288 .295 .299 7.32 7.49 7.59
Overall Width E .394 .407 .420 10.01 10.34 10.67
Standoff § A1 .004 .008 .012 0.10 0.20 0.30
Molded Package Thickness A2 .088 .091 .094 2.24 2.31 2.39
Overall Height A .093 .099 .104 2.36 2.50 2.64
Pitch p .050 1.27
Number of Pins n 28 28
Dimension Limits MIN NOM MAX MIN NOM MAX
Units INCHES* MILLIMETERS
2
1
D
p
n
B
E
E1
L
c
β
45°
h
φ
A2
α
A
A1
* Controlling Parameter
Notes:
Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010” (0.254mm) per side.
JEDEC Equivalent: MS-013
Drawing No. C04-052
§ Significant Characteristic© 2006 Microchip Technology Inc. DS39564C-page 309
PIC18FXX2
40-Lead Plastic Dual In-line (P) – 600 mil Body (PDIP)
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
Mold Draft Angle Bottom β 5 10 15 5 10 15
Mold Draft Angle Top α 5 10 15 5 10 15
Overall Row Spacing § eB .620 .650 .680 15.75 16.51 17.27
Lower Lead Width B .014 .018 .022 0.36 0.46 0.56
Upper Lead Width B1 .030 .050 .070 0.76 1.27 1.78
Lead Thickness c .008 .012 .015 0.20 0.29 0.38
Tip to Seating Plane L .120 .130 .135 3.05 3.30 3.43
Overall Length D 2.045 2.058 2.065 51.94 52.26 52.45
Molded Package Width E1 .530 .545 .560 13.46 13.84 14.22
Shoulder to Shoulder Width E .595 .600 .625 15.11 15.24 15.88
Base to Seating Plane A1 .015 0.38
Molded Package Thickness A2 .140 .150 .160 3.56 3.81 4.06
Top to Seating Plane A .160 .175 .190 4.06 4.45 4.83
Pitch p .100 2.54
Number of Pins n 40 40
Dimension Limits MIN NOM MAX MIN NOM MAX
Units INCHES* MILLIMETERS
A2
1
2
D
n
E1
c
β
eB
E
α
p
L
B
B1
A
A1
* Controlling Parameter
Notes:
Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010” (0.254mm) per side.
JEDEC Equivalent: MO-011
Drawing No. C04-016
§ Significant CharacteristicPIC18FXX2
DS39564C-page 310 © 2006 Microchip Technology Inc.
44-Lead Plastic Thin Quad Flatpack (PT) 10x10x1 mm Body, 1.0/0.10 mm Lead Form (TQFP)
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
F
A
A1 A2
α
E
E1
#leads=n1
p
B
D1 D
n
1
2
φ
c
β
L
CH x 45°
Pin 1 Corner Chamfer CH .025 .035 .045 0.64 0.89 1.14
Footprint (Reference) F .039 REF. 1.00 REF.
Units INCHES MILLIMETERS*
Dimension Limits MIN NOM MAX MIN NOM MAX
Number of Pins n 44 44
Pitch p .031 0.80
Overall Height A .039 .043 .047 1.00 1.10 1.20
Molded Package Thickness A2 .037 .039 .041 0.95 1.00 1.05
Standoff A1 .002 .004 .006 0.05 0.10 0.15
Foot Length L .018 .024 .030 0.45 0.60 0.75
Foot Angle φ 0 3.5 7 0 3.5 7
Overall Width E .463 .472 .482 11.75 12.00 12.25
Overall Length D .463 .472 .482 11.75 12.00 12.25
Molded Package Width E1 .390 .394 .398 9.90 10.00 10.10
Molded Package Length D1 .390 .394 .398 9.90 10.00 10.10
Pins per Side n1 11 11
Lead Thickness c .004 .006 .008 0.09 0.15 0.20
Lead Width B .012 .015 .017 0.30 0.38 0.44
Mold Draft Angle Top α 5 10 15 5 10 15
Mold Draft Angle Bottom β 5 10 15 5 10 15
Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010" (0.254mm) per side.
Notes:
JEDEC Equivalent: MS-026
Revised 07-22-05
* Controlling Parameter
REF: Reference Dimension, usually without tolerance, for information purposes only.
See ASME Y14.5M
Drawing No. C04-076© 2006 Microchip Technology Inc. DS39564C-page 311
PIC18FXX2
44-Lead Plastic Leaded Chip Carrier (L) – Square (PLCC)
Note: For the most current package drawings, please see the Microchip Packaging Specification located at
http://www.microchip.com/packaging
CH2 x 45° CH1 x 45°
Mold Draft Angle Bottom β 0 5 10 0 5 10
Mold Draft Angle Top α 0 5 10 0 5 10
B .013 .020 .021 0.33 0.51 0.53
Upper Lead Width B1 .026 .029 .032 0.66 0.74 0.81
Lead Thickness c .008 .011 .013 0.20 0.27 0.33
Pins per Side n1 11 11
Footprint Length D2 .590 .620 .630 14.99 15.75 16.00
Footprint Width E2 .590 .620 .630 14.99 15.75 16.00
Molded Package Length D1 .650 .653 .656 16.51 16.59 16.66
Molded Package Width E1 .650 .653 .656 16.51 16.59 16.66
Overall Length D .685 .690 .695 17.40 17.53 17.65
Overall Width E .685 .690 .695 17.40 17.53 17.65
Corner Chamfer (others) CH2 .000 .005 .010 0.00 0.13 0.25
Corner Chamfer 1 CH1 .040 .045 .050 1.02 1.14 1.27
Side 1 Chamfer Height A3 .024 .029 .034 0.61 0.74 0.86
Standoff § A1 .020 0.51
Molded Package Thickness A2
Overall Height A .165 .173 .180 4.19 4.39 4.57
Pitch p .050 1.27
Number of Pins n 44 44
Dimension Limits MIN NOM MAX MIN NOM MAX
Units INCHES* MILLIMETERS
β
A2
c
E2
2
D1 D
n
#leads=n1
E
E1
1
α
p
A3
A 35°
B1
B
D2
A1
.145 .153 .160 3.68 3.87 4.06
.028 .035 0.71 0.89
Lower Lead Width
* Controlling Parameter
Notes:
Dimensions D and E1 do not include mold flash or protrusions. Mold flash or protrusions shall not exceed .010” (0.254mm) per side.
JEDEC Equivalent: MO-047
Drawing No. C04-048
§ Significant CharacteristicPIC18FXX2
DS39564C-page 312 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 313
PIC18FXX2
APPENDIX A: REVISION HISTORY
Revision A (June 2001)
Original data sheet for the PIC18FXX2 family.
Revision B (August 2002)
This revision includes the DC and AC Characteristics
Graphs and Tables. The Electrical Specifications in
Section 22.0 have been updated and there have been
minor corrections to the data sheet text.
Revision C (October 2006)
Packaging diagrams updated.
APPENDIX B: DEVICE
DIFFERENCES
The differences between the devices listed in this data
sheet are shown in Table B-1.
TABLE B-1: DEVICE DIFFERENCES
Feature PIC18F242 PIC18F252 PIC18F442 PIC18F452
Program Memory (Kbytes) 16 32 16 32
Data Memory (Bytes) 768 1536 768 1536
A/D Channels 5 5 8 8
Parallel Slave Port (PSP) No No Yes Yes
Package Types 28-pin DIP
28-pin SOIC
28-pin DIP
28-pin SOIC
40-pin DIP
44-pin PLCC
44-pin TQFP
40-pin DIP
44-pin PLCC
44-pin TQFPPIC18FXX2
DS39564C-page 314 © 2006 Microchip Technology Inc.
APPENDIX C: CONVERSION
CONSIDERATIONS
This appendix discusses the considerations for converting
from previous versions of a device to the ones
listed in this data sheet. Typically, these changes are
due to the differences in the process technology used.
An example of this type of conversion is from a
PIC16C74A to a PIC16C74B.
Not Applicable
APPENDIX D: MIGRATION FROM
BASELINE TO
ENHANCED DEVICES
This section discusses how to migrate from a Baseline
device (i.e., PIC16C5X) to an Enhanced MCU device
(i.e., PIC18FXXX).
The following are the list of modifications over the
PIC16C5X microcontroller family:
Not Currently Available© 2006 Microchip Technology Inc. DS39564C-page 315
PIC18FXX2
APPENDIX E: MIGRATION FROM
MID-RANGE TO
ENHANCED DEVICES
A detailed discussion of the differences between the
mid-range MCU devices (i.e., PIC16CXXX) and the
enhanced devices (i.e., PIC18FXXX) is provided in
AN716, “Migrating Designs from PIC16C74A/74B to
PIC18F442”. The changes discussed, while device
specific, are generally applicable to all mid-range to
enhanced device migrations.
This Application Note is available as Literature Number
DS00716.
APPENDIX F: MIGRATION FROM
HIGH-END TO
ENHANCED DEVICES
A detailed discussion of the migration pathway and differences
between the high-end MCU devices (i.e.,
PIC17CXXX) and the enhanced devices (i.e.,
PIC18FXXX) is provided in AN726, “PIC17CXXX to
PIC18FXXX Migration”. This Application Note is
available as Literature Number DS00726.PIC18FXX2
DS39564C-page 316 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 317
PIC18FXX2
INDEX
A
A/D ................................................................................... 181
A/D Converter Flag (ADIF Bit) ................................. 183
A/D Converter Interrupt, Configuring ....................... 184
Acquisition Requirements ........................................ 184
ADCON0 Register .................................................... 181
ADCON1 Register .................................................... 181
ADRESH Register .................................................... 181
ADRESH/ADRESL Registers .................................. 183
ADRESL Register .................................................... 181
Analog Port Pins ................................................ 99, 100
Analog Port Pins, Configuring .................................. 186
Associated Registers ............................................... 188
Configuring the Module ............................................ 184
Conversion Clock (TAD) ........................................... 186
Conversion Status (GO/DONE Bit) .......................... 183
Conversions ............................................................. 187
Converter Characteristics ........................................ 287
Equations
Acquisition Time ............................................... 185
Minimum Charging Time .................................. 185
Examples
Calculating the Minimum Required
Acquisition Time ...................................... 185
Result Registers ....................................................... 187
Special Event Trigger (CCP) ............................ 120, 188
TAD vs. Device Operating Frequencies .................... 186
Use of the CCP2 Trigger .......................................... 188
Absolute Maximum Ratings ............................................. 259
AC (Timing) Characteristics ............................................. 269
Load Conditions for Device Timing
Specifications ................................................... 270
Parameter Symbology ............................................. 269
Temperature and Voltage Specifications - AC ......... 270
Timing Conditions .................................................... 270
ACKSTAT Status Flag ..................................................... 155
ADCON0 Register ............................................................ 181
GO/DONE Bit ........................................................... 183
ADCON1 Register ............................................................ 181
ADDLW ............................................................................ 217
ADDWF ............................................................................ 217
ADDWFC ......................................................................... 218
ADRESH Register ............................................................ 181
ADRESH/ADRESL Registers ........................................... 183
ADRESL Register ............................................................ 181
Analog-to-Digital Converter. See A/D
ANDLW ............................................................................ 218
ANDWF ............................................................................ 219
Assembler
MPASM Assembler .................................................. 253
B
Baud Rate Generator ....................................................... 151
BC .................................................................................... 219
BCF .................................................................................. 220
BF Status Flag ................................................................. 155
Block Diagrams
A/D Converter .......................................................... 183
Analog Input Model .................................................. 184
Baud Rate Generator .............................................. 151
Capture Mode Operation ......................................... 119
Compare Mode Operation ....................................... 120
Low Voltage Detect
External Reference Source ............................. 190
Internal Reference Source ............................... 190
MSSP
I
2C Mode ......................................................... 134
MSSP (SPI Mode) ................................................... 125
On-Chip Reset Circuit ................................................ 25
Parallel Slave Port (PORTD and PORTE) ............... 100
PIC18F2X2 .................................................................. 8
PIC18F4X2 .................................................................. 9
PLL ............................................................................ 19
PORTC (Peripheral Output Override) ........................ 93
PORTD (I/O Mode) .................................................... 95
PORTE (I/O Mode) .................................................... 97
PWM Operation (Simplified) .................................... 122
RA3:RA0 and RA5 Port Pins ..................................... 87
RA4/T0CKI Pin .......................................................... 88
RA6 Pin ..................................................................... 88
RB2:RB0 Port Pins .................................................... 91
RB3 Pin ..................................................................... 91
RB7:RB4 Port Pins .................................................... 90
Table Read Operation ............................................... 55
Table Write Operation ................................................ 56
Table Writes to FLASH Program Memory ................. 61
Timer0 in 16-bit Mode .............................................. 104
Timer0 in 8-bit Mode ................................................ 104
Timer1 ..................................................................... 108
Timer1 (16-bit R/W Mode) ....................................... 108
Timer2 ..................................................................... 112
Timer3 ..................................................................... 114
Timer3 (16-bit R/W Mode) ....................................... 114
USART
Asynchronous Receive .................................... 174
Asynchronous Transmit ................................... 172
Watchdog Timer ...................................................... 204
BN .................................................................................... 220
BNC ................................................................................. 221
BNN ................................................................................. 221
BNOV ............................................................................... 222
BNZ .................................................................................. 222
BOR. See Brown-out Reset
BOV ................................................................................. 225
BRA ................................................................................. 223
BRG. See Baud Rate Generator
Brown-out Reset (BOR) ..................................................... 26
BSF .................................................................................. 223
BTFSC ............................................................................. 224
BTFSS ............................................................................. 224
BTG ................................................................................. 225
Bus Collision During a STOP Condition .......................... 163
BZ .................................................................................... 226PIC18FXX2
DS39564C-page 318 © 2006 Microchip Technology Inc.
C
CALL ................................................................................ 226
Capture (CCP Module) ..................................................... 119
Associated Registers ...............................................121
CCP Pin Configuration ............................................. 119
CCPR1H:CCPR1L Registers ................................... 119
Software Interrupt ..................................................... 119
Timer1/Timer3 Mode Selection ................................ 119
Capture/Compare/PWM (CCP) ........................................ 117
Capture Mode. See Capture
CCP1 ........................................................................118
CCPR1H Register ............................................ 118
CCPR1L Register ............................................ 118
CCP2 ........................................................................118
CCPR2H Register ............................................ 118
CCPR2L Register ............................................ 118
Compare Mode. See Compare
Interaction of Two CCP Modules ............................. 118
PWM Mode. See PWM
Timer Resources ...................................................... 118
Clocking Scheme/Instruction Cycle .................................... 39
CLRF ................................................................................ 227
CLRWDT .......................................................................... 227
Code Examples
16 x 16 Signed Multiply Routine ................................. 72
16 x 16 Unsigned Multiply Routine ............................. 72
8 x 8 Signed Multiply Routine ..................................... 71
8 x 8 Unsigned Multiply Routine ................................. 71
Changing Between Capture Prescalers ................... 119
Data EEPROM Read .................................................67
Data EEPROM Refresh Routine ................................68
Data EEPROM Write .................................................. 67
Erasing a FLASH Program Memory Row .................. 60
Fast Register Stack .................................................... 39
How to Clear RAM (Bank1) Using
Indirect Addressing ............................................ 50
Initializing PORTA ...................................................... 87
Initializing PORTB ...................................................... 90
Initializing PORTC ...................................................... 93
Initializing PORTD ...................................................... 95
Initializing PORTE ...................................................... 97
Loading the SSPBUF (SSPSR) Register ................. 128
Reading a FLASH Program Memory Word ................ 59
Saving STATUS, WREG and BSR
Registers in RAM ............................................... 85
Writing to FLASH Program Memory ..................... 62–63
Code Protection ............................................................... 195
COMF ............................................................................... 228
Compare (CCP Module) ...................................................120
Associated Registers ...............................................121
CCP Pin Configuration ............................................. 120
CCPR1 Register ....................................................... 120
Software Interrupt ..................................................... 120
Special Event Trigger ........................109, 115, 120, 188
Timer1/Timer3 Mode Selection ................................ 120
Configuration Bits ............................................................. 195
Context Saving During Interrupts ....................................... 85
Conversion Considerations .............................................. 314
CPFSEQ .......................................................................... 228
CPFSGT ........................................................................... 229
CPFSLT ........................................................................... 229
D
Data EEPROM Memory
Associated Registers ................................................. 69
EEADR Register ........................................................ 65
EECON1 Register ...................................................... 65
EECON2 Register ...................................................... 65
Operation During Code Protect ................................. 68
Protection Against Spurious Write ............................. 68
Reading ..................................................................... 67
Using .......................................................................... 68
Write Verify ................................................................ 68
Writing ........................................................................ 67
Data Memory ..................................................................... 42
General Purpose Registers ....................................... 42
Map for PIC18F242/442 ............................................ 43
Map for PIC18F252/452 ............................................ 44
Special Function Registers ........................................ 42
DAW ................................................................................ 230
DC and AC Characteristics
Graphs and Tables .................................................. 289
DC Characteristics ....................................................261, 265
DCFSNZ .......................................................................... 231
DECF ............................................................................... 230
DECFSZ .......................................................................... 231
Development Support ...................................................... 253
Device Differences ........................................................... 313
Device Overview .................................................................. 7
Features ....................................................................... 7
Direct Addressing ............................................................... 51
Example ..................................................................... 49
E
Electrical Characteristics .................................................. 259
Errata ................................................................................... 5
F
Firmware Instructions ....................................................... 211
FLASH Program Memory ................................................... 55
Associated Registers ................................................. 63
Control Registers ....................................................... 56
Erase Sequence ........................................................ 60
Erasing ....................................................................... 60
Operation During Code Protect ................................. 63
Reading ..................................................................... 59
TABLAT Register ....................................................... 58
Table Pointer ............................................................. 58
Boundaries Based on Operation ........................ 58
Table Pointer Boundaries .......................................... 58
Table Reads and Table Writes .................................. 55
Block Diagrams
Reads from FLASH Program Memory ....... 59
Writing to .................................................................... 61
Protection Against Spurious Writes ................... 63
Unexpected Termination .................................... 63
Write Verify ........................................................ 63
G
General Call Address Support ......................................... 148
GOTO .............................................................................. 232© 2006 Microchip Technology Inc. DS39564C-page 319
PIC18FXX2
I
I/O Ports ............................................................................. 87
I
2C (MSSP Module)
ACK Pulse ................................................................ 139
Read/Write Bit Information (R/W Bit) ....................... 139
I
2C (SSP Module)
ACK Pulse ................................................................ 138
I
2C Master Mode Reception ............................................. 155
I
2C Mode
Clock Stretching ....................................................... 144
I
2C Mode (MSSP Module) ................................................ 134
Registers .................................................................. 134
I
2C Module
ACK Pulse ........................................................ 138, 139
Acknowledge Sequence Timing ............................... 158
Baud Rate Generator ............................................... 151
Bus Collision
Repeated START Condition ............................ 162
START Condition ............................................. 160
Clock Arbitration ....................................................... 152
Effect of a RESET .................................................... 159
General Call Address Support ................................. 148
Master Mode ............................................................ 149
Operation ......................................................... 150
Repeated START Condition Timing ................. 154
Master Mode START Condition ............................... 153
Master Mode Transmission ...................................... 155
Multi-Master Communication, Bus Collision
and Arbitration .................................................. 159
Multi-Master Mode ................................................... 159
Operation ................................................................. 138
Read/Write Bit Information (R/W Bit) ............... 138, 139
Serial Clock (RC3/SCK/SCL) ................................... 139
Slave Mode .............................................................. 138
Addressing ....................................................... 138
Reception ......................................................... 139
Transmission .................................................... 139
Slave Mode Timing (10-bit Reception,
SEN = 0) .......................................................... 142
Slave Mode Timing (10-bit Reception,
SEN = 1) .......................................................... 147
Slave Mode Timing (10-bit Transmission) ................ 143
Slave Mode Timing (7-bit Reception,
SEN = 0) .......................................................... 140
Slave Mode Timing (7-bit Reception,
SEN = 1) .......................................................... 146
Slave Mode Timing (7-bit Transmission) .................. 141
SLEEP Operation ..................................................... 159
STOP Condition Timing ........................................... 158
ICEPIC In-Circuit Emulator .............................................. 254
ID Locations ............................................................. 195, 210
INCF ................................................................................. 232
INCFSZ ............................................................................ 233
In-Circuit Debugger .......................................................... 210
In-Circuit Serial Programming (ICSP) ...................... 195, 210
Indirect Addressing ............................................................ 51
INDF and FSR Registers ........................................... 50
Indirect Addressing Operation ............................................ 51
Indirect File Operand .......................................................... 42
INFSNZ ............................................................................ 233
Instruction Cycle ................................................................. 39
Instruction Flow/Pipelining ................................................. 40
Instruction Format ............................................................ 213
Instruction Set .................................................................. 211
ADDLW .................................................................... 217
ADDWF .................................................................... 217
ADDWFC ................................................................. 218
ANDLW .................................................................... 218
ANDWF .................................................................... 219
BC ............................................................................ 219
BCF ......................................................................... 220
BN ............................................................................ 220
BNC ......................................................................... 221
BNN ......................................................................... 221
BNOV ...................................................................... 222
BNZ ......................................................................... 222
BOV ......................................................................... 225
BRA ......................................................................... 223
BSF .......................................................................... 223
BTFSC ..................................................................... 224
BTFSS ..................................................................... 224
BTG ......................................................................... 225
BZ ............................................................................ 226
CALL ........................................................................ 226
CLRF ....................................................................... 227
CLRWDT ................................................................. 227
COMF ...................................................................... 228
CPFSEQ .................................................................. 228
CPFSGT .................................................................. 229
CPFSLT ................................................................... 229
DAW ........................................................................ 230
DCFSNZ .................................................................. 231
DECF ....................................................................... 230
DECFSZ .................................................................. 231
GOTO ...................................................................... 232
INCF ........................................................................ 232
INCFSZ .................................................................... 233
INFSNZ .................................................................... 233
IORLW ..................................................................... 234
IORWF ..................................................................... 234
LFSR ....................................................................... 235
MOVF ...................................................................... 235
MOVFF .................................................................... 236
MOVLB .................................................................... 236
MOVLW ................................................................... 237
MOVWF ................................................................... 237
MULLW .................................................................... 238
MULWF .................................................................... 238
NEGF ....................................................................... 239
NOP ......................................................................... 239
POP ......................................................................... 240
PUSH ....................................................................... 240
RCALL ..................................................................... 241
RESET ..................................................................... 241
RETFIE .................................................................... 242
RETLW .................................................................... 242
RETURN .................................................................. 243
RLCF ....................................................................... 243
RLNCF ..................................................................... 244
RRCF ....................................................................... 244
RRNCF .................................................................... 245
SETF ....................................................................... 245
SLEEP ..................................................................... 246
SUBFWB ................................................................. 246
SUBLW .................................................................... 247
SUBWF .................................................................... 247
SUBWFB ................................................................. 248
SWAPF .................................................................... 248PIC18FXX2
DS39564C-page 320 © 2006 Microchip Technology Inc.
TBLRD ..................................................................... 249
TBLWT ..................................................................... 250
TSTFSZ ....................................................................251
XORLW ....................................................................251
XORWF ....................................................................252
Summary Table ........................................................ 214
Instructions in Program Memory ........................................ 40
Two-Word Instructions ............................................... 41
INT Interrupt (RB0/INT). See Interrupt Sources
INTCON Register
RBIF Bit ......................................................................90
INTCON Registers ....................................................... 75–77
Inter-Integrated Circuit. See I2C
Interrupt Sources .............................................................. 195
A/D Conversion Complete ........................................ 184
Capture Complete (CCP) ......................................... 119
Compare Complete (CCP) ....................................... 120
INT0 ........................................................................... 85
Interrupt-on-Change (RB7:RB4 ) ............................... 90
PORTB, Interrupt-on-Change .................................... 85
RB0/INT Pin, External ................................................ 85
TMR0 ......................................................................... 85
TMR0 Overflow ........................................................ 105
TMR1 Overflow ................................................ 107, 109
TMR2 to PR2 Match .................................................112
TMR2 to PR2 Match (PWM) ............................ 111, 122
TMR3 Overflow ................................................ 113, 115
USART Receive/Transmit Complete ........................ 165
Interrupts ............................................................................ 73
Logic ........................................................................... 74
Interrupts, Enable Bits
CCP1 Enable (CCP1IE Bit) ...................................... 119
Interrupts, Flag Bits
A/D Converter Flag (ADIF Bit) .................................. 183
CCP1 Flag (CCP1IF Bit) .......................................... 119
CCP1IF Flag (CCP1IF Bit) ....................................... 120
Interrupt-on-Change (RB7:RB4) Flag
(RBIF Bit) ........................................................... 90
IORLW ............................................................................. 234
IORWF ............................................................................. 234
IPR Registers ............................................................... 82–83
K
KEELOQ Evaluation and Programming Tools ................... 256
L
LFSR ................................................................................ 235
Lookup Tables
Computed GOTO ....................................................... 41
Table Reads, Table Writes ......................................... 41
Low Voltage Detect .......................................................... 189
Converter Characteristics ......................................... 267
Effects of a RESET .................................................. 193
Operation ................................................................. 192
Current Consumption ....................................... 193
During SLEEP .................................................. 193
Reference Voltage Set Point ............................193
Typical Application ...................................................189
LVD. See Low Voltage Detect. ......................................... 189
M
Master SSP (MSSP) Module Overview ........................... 125
Master Synchronous Serial Port (MSSP). See MSSP.
Master Synchronous Serial Port. See MSSP
Memory Organization
Data Memory ............................................................. 42
Program Memory ....................................................... 35
Memory Programming Requirements .............................. 268
Migration from Baseline to Enhanced Devices ................ 314
Migration from High-End to Enhanced Devices ............... 315
Migration from Mid-Range to Enhanced Devices ............ 315
MOVF .............................................................................. 235
MOVFF ............................................................................ 236
MOVLB ............................................................................ 236
MOVLW ........................................................................... 237
MOVWF ........................................................................... 237
MPLAB C17 and MPLAB C18 C Compilers ..................... 253
MPLAB ICD In-Circuit Debugger ..................................... 255
MPLAB ICE High Performance Universal In-Circuit
Emulator with MPLAB IDE ....................................... 254
MPLAB Integrated Development
Environment Software ............................................. 253
MPLINK Object Linker/MPLIB Object Librarian ............... 254
MSSP ............................................................................... 125
Control Registers (general) ...................................... 125
Enabling SPI I/O ...................................................... 129
Operation ................................................................. 128
Typical Connection .................................................. 129
MSSP Module
SPI Master Mode ..................................................... 130
SPI Master./Slave Connection ................................. 129
SPI Slave Mode ....................................................... 131
MULLW ............................................................................ 238
MULWF ............................................................................ 238
N
NEGF ............................................................................... 239
NOP ................................................................................. 239
O
Opcode Field Descriptions ............................................... 212
OPTION_REG Register
PSA Bit .................................................................... 105
T0CS Bit .................................................................. 105
T0PS2:T0PS0 Bits ................................................... 105
T0SE Bit ................................................................... 105
Oscillator Configuration ...................................................... 17
EC .............................................................................. 17
ECIO .......................................................................... 17
HS .............................................................................. 17
HS + PLL ................................................................... 17
LP .............................................................................. 17
RC .............................................................................. 17
RCIO .......................................................................... 17
XT .............................................................................. 17
Oscillator Selection .......................................................... 195
Oscillator, Timer1 ..............................................107, 109, 115
Oscillator, Timer3 ............................................................. 113
Oscillator, WDT ................................................................ 203© 2006 Microchip Technology Inc. DS39564C-page 321
PIC18FXX2
P
Packaging ........................................................................ 305
Details ...................................................................... 307
Marking Information ................................................. 305
Parallel Slave Port
PORTD .................................................................... 100
Parallel Slave Port (PSP) ........................................... 95, 100
Associated Registers ............................................... 101
RE0/RD/AN5 Pin ................................................ 99, 100
RE1/WR/AN6 Pin ............................................... 99, 100
RE2/CS/AN7 Pin ................................................ 99, 100
Select (PSPMODE Bit) ...................................... 95, 100
PIC18F2X2 Pin Functions
MCLR/VPP .................................................................. 10
OSC1/CLKI ................................................................ 10
OSC2/CLKO/RA6 ...................................................... 10
RA0/AN0 .................................................................... 10
RA1/AN1 .................................................................... 10
RA2/AN2/VREF- .......................................................... 10
RA3/AN3/VREF+ ......................................................... 10
RA4/T0CKI ................................................................. 10
RA5/AN4/SS/LVDIN ................................................... 10
RB0/INT0 ................................................................... 11
RB1/INT1 ................................................................... 11
RB2/INT2 ................................................................... 11
RB3/CCP2 ................................................................. 11
RB4 ............................................................................ 11
RB5/PGM ................................................................... 11
RB6/PGC ................................................................... 11
RB7/PGD ................................................................... 11
RC0/T1OSO/T1CKI ................................................... 12
RC1/T1OSI/CCP2 ...................................................... 12
RC2/CCP1 ................................................................. 12
RC3/SCK/SCL ........................................................... 12
RC4/SDI/SDA ............................................................ 12
RC5/SDO ................................................................... 12
RC6/TX/CK ................................................................ 12
RC7/RX/DT ................................................................ 12
VDD ............................................................................. 12
VSS ............................................................................. 12
PIC18F4X2 Pin Functions
MCLR/VPP .................................................................. 13
OSC1/CLKI ................................................................ 13
OSC2/CLKO .............................................................. 13
RA0/AN0 .................................................................... 13
RA1/AN1 .................................................................... 13
RA2/AN2/VREF- .......................................................... 13
RA3/AN3/VREF+ ......................................................... 13
RA4/T0CKI ................................................................. 13
RA5/AN4/SS/LVDIN ................................................... 13
RB0/INT ..................................................................... 14
RB1 ............................................................................ 14
RB2 ............................................................................ 14
RB3 ............................................................................ 14
RB4 ............................................................................ 14
RB5/PGM ................................................................... 14
RB6/PGC ................................................................... 14
RB7/PGD ................................................................... 14
RC0/T1OSO/T1CKI ................................................... 15
RC1/T1OSI/CCP2 ...................................................... 15
RC2/CCP1 ................................................................. 15
RC3/SCK/SCL ........................................................... 15
RC4/SDI/SDA ............................................................ 15
RC5/SDO ................................................................... 15
RC6/TX/CK ................................................................ 15
RC7/RX/DT ................................................................ 15
RD0/PSP0 ................................................................. 16
RD1/PSP1 ................................................................. 16
RD2/PSP2 ................................................................. 16
RD3/PSP3 ................................................................. 16
RD4/PSP4 ................................................................. 16
RD5/PSP5 ................................................................. 16
RD6/PSP6 ................................................................. 16
RD7/PSP7 ................................................................. 16
RE0/RD/AN5 .............................................................. 16
RE1/WR/AN6 ............................................................. 16
RE2/CS/AN7 .............................................................. 16
VDD ............................................................................ 16
VSS ............................................................................ 16
PIC18FXX2 Voltage-Frequency Graph
(Industrial) ................................................................ 260
PIC18LFXX2 Voltage-Frequency Graph
(Industrial) ................................................................ 260
PICDEM 1 Low Cost PICmicro
Demonstration Board ............................................... 255
PICDEM 17 Demonstration Board ................................... 256
PICDEM 2 Low Cost PIC16CXX
Demonstration Board ............................................... 255
PICDEM 3 Low Cost PIC16CXXX
Demonstration Board ............................................... 256
PICSTART Plus Entry Level Development
Programmer ............................................................. 255
PIE Registers ................................................................80–81
Pinout I/O Descriptions
PIC18F2X2 ................................................................ 10
PIR Registers ................................................................78–79
PLL Lock Time-out ............................................................. 26
Pointer, FSR ...................................................................... 50
POP ................................................................................. 240
POR. See Power-on Reset
PORTA
Associated Registers ................................................. 89
LATA Register ........................................................... 87
PORTA Register ........................................................ 87
TRISA Register .......................................................... 87
PORTB
Associated Registers ................................................. 92
LATB Register ........................................................... 90
PORTB Register ........................................................ 90
RB0/INT Pin, External ................................................ 85
RB7:RB4 Interrupt-on-Change Flag (RBIF Bit) .......... 90
TRISB Register .......................................................... 90
PORTC
Associated Registers ................................................. 94
LATC Register ........................................................... 93
PORTC Register ........................................................ 93
RC3/SCK/SCL Pin ................................................... 139
RC7/RX/DT Pin ........................................................ 168
TRISC Register ...................................................93, 165
PORTD
Associated Registers ................................................. 96
LATD Register ........................................................... 95
Parallel Slave Port (PSP) Function ............................ 95
PORTD Register ........................................................ 95
TRISD Register .......................................................... 95PIC18FXX2
DS39564C-page 322 © 2006 Microchip Technology Inc.
PORTE
Analog Port Pins ................................................ 99, 100
Associated Registers .................................................99
LATE Register ............................................................ 97
PORTE Register ........................................................ 97
PSP Mode Select (PSPMODE Bit) .................... 95, 100
RE0/RD/AN5 Pin ................................................ 99, 100
RE1/WR/AN6 Pin ............................................... 99, 100
RE2/CS/AN7 Pin ................................................ 99, 100
TRISE Register .......................................................... 97
Postscaler, WDT
Assignment (PSA Bit) ...............................................105
Rate Select (T0PS2:T0PS0 Bits) ............................. 105
Switching Between Timer0 and WDT ...................... 105
Power-down Mode. See SLEEP
Power-on Reset (POR) ...................................................... 26
Oscillator Start-up Timer (OST) ................................. 26
Power-up Timer (PWRT) ............................................ 26
Prescaler, Capture ........................................................... 119
Prescaler, Timer0 ............................................................. 105
Assignment (PSA Bit) ...............................................105
Rate Select (T0PS2:T0PS0 Bits) ............................. 105
Switching Between Timer0 and WDT ...................... 105
Prescaler, Timer2 ............................................................. 122
PRO MATE II Universal Device Programmer ................... 255
Product Identification System ........................................... 327
Program Counter
PCL Register .............................................................. 39
PCLATH Register ....................................................... 39
PCLATU Register ....................................................... 39
Program Memory
Interrupt Vector .......................................................... 35
Map and Stack for PIC18F442/242 ............................36
Map and Stack for PIC18F452/252 ............................36
RESET Vector ............................................................ 35
Program Verification and Code Protection ....................... 207
Associated Registers ...............................................207
Programming, Device Instructions ................................... 211
PSP.See Parallel Slave Port.
Pulse Width Modulation. See PWM (CCP Module).
PUSH ............................................................................... 240
PWM (CCP Module) ......................................................... 122
Associated Registers ...............................................123
CCPR1H:CCPR1L Registers ................................... 122
Duty Cycle ................................................................ 122
Example Frequencies/Resolutions ........................... 123
Period ....................................................................... 122
Setup for PWM Operation ........................................ 123
TMR2 to PR2 Match ......................................... 111, 122
Q
Q Clock ............................................................................ 122
R
RAM. See Data Memory
RC Oscillator ......................................................................18
RCALL .............................................................................. 241
RCSTA Register
SPEN Bit .................................................................. 165
Register File ....................................................................... 42
Registers
ADCON0 (A/D Control 0) ......................................... 181
ADCON1 (A/D Control 1) ......................................... 182
CCP1CON and CCP2CON
(Capture/Compare/PWM Control) ................... 117
CONFIG1H (Configuration 1 High) .......................... 196
CONFIG2H (Configuration 2 High) .......................... 197
CONFIG2L (Configuration 2 Low) ........................... 197
CONFIG3H (Configuration 3 High) .......................... 198
CONFIG4L (Configuration 4 Low) ........................... 198
CONFIG5H (Configuration 5 High) .......................... 199
CONFIG5L (Configuration 5 Low) ........................... 199
CONFIG6H (Configuration 6 High) .......................... 200
CONFIG6L (Configuration 6 Low) ........................... 200
CONFIG7H (Configuration 7 High) .......................... 201
CONFIG7L (Configuration 7 Low) ........................... 201
DEVID1 (Device ID Register 1) ............................... 202
DEVID2 (Device ID Register 2) ............................... 202
EECON1 (Data EEPROM Control 1) ....................57, 66
File Summary ........................................................46–48
INTCON (Interrupt Control) ........................................ 75
INTCON2 (Interrupt Control 2) ................................... 76
INTCON3 (Interrupt Control 3) ................................... 77
IPR1 (Peripheral Interrupt Priority 1) ......................... 82
IPR2 (Peripheral Interrupt Priority 2) ......................... 83
LVDCON (LVD Control) ........................................... 191
OSCCON (Oscillator Control) .................................... 21
PIE1 (Peripheral Interrupt Enable 1) .......................... 80
PIE2 (Peripheral Interrupt Enable 2) .......................... 81
PIR1 (Peripheral Interrupt Request 1) ....................... 78
PIR2 (Peripheral Interrupt Request 2) ....................... 79
RCON (Register Control) ........................................... 84
RCON (RESET Control) ............................................ 53
RCSTA (Receive Status and Control) ..................... 167
SSPCON1 (MSSP Control 1)
I
2C Mode ......................................................... 136
SPI Mode ......................................................... 127
SSPCON2 (MSSP Control 2)
I
2C Mode ......................................................... 137
SSPSTAT (MSSP Status)
I
2C Mode ......................................................... 135
SPI Mode ......................................................... 126
STATUS ..................................................................... 52
STKPTR (Stack Pointer) ............................................ 38
T0CON (Timer0 Control) ......................................... 103
T1CON (Timer 1 Control) ........................................ 107
T2CON (Timer 2 Control) ........................................ 111
T3CON (Timer3 Control) ......................................... 113
TRISE ........................................................................ 98
TXSTA (Transmit Status and Control) ..................... 166
WDTCON (Watchdog Timer Control) ...................... 203
RESET ................................................................25, 195, 241
Brown-out Reset (BOR) ........................................... 195
MCLR Reset (During SLEEP) .................................... 25
MCLR Reset (Normal Operation) .............................. 25
Oscillator Start-up Timer (OST) ............................... 195
Power-on Reset (POR) .......................................25, 195
Power-up Timer (PWRT) ......................................... 195
Programmable Brown-out Reset (BOR) .................... 25
RESET Instruction ..................................................... 25
Stack Full Reset ......................................................... 25
Stack Underflow Reset .............................................. 25
Watchdog Timer (WDT) Reset .................................. 25© 2006 Microchip Technology Inc. DS39564C-page 323
PIC18FXX2
RETFIE ............................................................................ 242
RETLW ............................................................................. 242
RETURN .......................................................................... 243
Revision History ............................................................... 313
RLCF ................................................................................ 243
RLNCF ............................................................................. 244
RRCF ............................................................................... 244
RRNCF ............................................................................. 245
S
SCI. See USART
SCK .................................................................................. 125
SDI ................................................................................... 125
SDO ................................................................................. 125
Serial Clock, SCK ............................................................. 125
Serial Communication Interface. See USART
Serial Data In, SDI ........................................................... 125
Serial Data Out, SDO ....................................................... 125
Serial Peripheral Interface. See SPI
SETF ................................................................................ 245
Slave Select Synchronization ........................................... 131
Slave Select, SS .............................................................. 125
SLEEP ...............................................................195, 205, 246
Software Simulator (MPLAB SIM) .................................... 254
Special Event Trigger. See Compare
Special Features of the CPU ............................................ 195
Configuration Registers ................................... 196–201
Special Function Registers ................................................ 42
Map ............................................................................ 45
SPI
Master Mode ............................................................ 130
Serial Clock .............................................................. 125
Serial Data In ........................................................... 125
Serial Data Out ........................................................ 125
Slave Select ............................................................. 125
SPI Clock ................................................................. 130
SPI Mode ................................................................. 125
SPI Master/Slave Connection .......................................... 129
SPI Module
Associated Registers ............................................... 133
Bus Mode Compatibility ........................................... 133
Effects of a RESET .................................................. 133
Master/Slave Connection ......................................... 129
Slave Mode .............................................................. 131
Slave Select Synchronization .................................. 131
Slave Synch Timing ................................................. 131
SLEEP Operation ..................................................... 133
SS .................................................................................... 125
SSP
I
2C Mode. See I2C
SPI Mode ................................................................. 125
SPI Mode. See SPI
SSPBUF Register .................................................... 130
SSPSR Register ...................................................... 130
TMR2 Output for Clock Shift ............................ 111, 112
SSPOV Status Flag .......................................................... 155
SSPSTAT Register
R/W Bit ............................................................. 138, 139
Status Bits
Significance and the Initialization Condition
for RCON Register ............................................. 27
SUBFWB .......................................................................... 246
SUBLW ............................................................................ 247
SUBWF ............................................................................ 247
SUBWFB .......................................................................... 248
SWAPF ............................................................................ 248
T
TABLAT Register ............................................................... 58
Table Pointer Operations (table) ........................................ 58
TBLPTR Register ............................................................... 58
TBLRD ............................................................................. 249
TBLWT ............................................................................. 250
Time-out Sequence ........................................................... 26
Time-out in Various Situations ................................... 27
Timer0 .............................................................................. 103
16-bit Mode Timer Reads and Writes ...................... 105
Associated Registers ............................................... 105
Clock Source Edge Select (T0SE Bit) ..................... 105
Clock Source Select (T0CS Bit) ............................... 105
Operation ................................................................. 105
Overflow Interrupt .................................................... 105
Prescaler. See Prescaler, Timer0
Timer1 .............................................................................. 107
16-bit Read/Write Mode ........................................... 109
Associated Registers ............................................... 110
Operation ................................................................. 108
Oscillator ...........................................................107, 109
Overflow Interrupt .............................................107, 109
Special Event Trigger (CCP) ............................109, 120
TMR1H Register ...................................................... 107
TMR1L Register ....................................................... 107
Timer2 .............................................................................. 111
Associated Registers ............................................... 112
Operation ................................................................. 111
Postscaler. See Postscaler, Timer2
PR2 Register ....................................................111, 122
Prescaler. See Prescaler, Timer2
SSP Clock Shift ................................................111, 112
TMR2 Register ......................................................... 111
TMR2 to PR2 Match Interrupt ...................111, 112, 122
Timer3 .............................................................................. 113
Associated Registers ............................................... 115
Operation ................................................................. 114
Oscillator ...........................................................113, 115
Overflow Interrupt .............................................113, 115
Special Event Trigger (CCP) ................................... 115
TMR3H Register ...................................................... 113
TMR3L Register ....................................................... 113
Timing Diagrams
Bus Collision
Transmit and Acknowledge ..................... 159
A/D Conversion ........................................................ 287
Acknowledge Sequence .......................................... 158
Baud Rate Generator with Clock Arbitration ............ 152
BRG Reset Due to SDA Arbitration During
START Condition ............................................. 161
Brown-out Reset (BOR) ........................................... 274
Bus Collision
Start Condition (SDA Only) .............................. 160
Bus Collision During a Repeated
START Condition (Case 1) .............................. 162
Bus Collision During a Repeated
START Condition (Case 2) .............................. 162
Bus Collision During a START Condition
(SCL = 0) ......................................................... 161
Bus Collision During a STOP Condition
(Case 1) ........................................................... 163
Bus Collision During a STOP Condition
(Case 2) ........................................................... 163
Capture/Compare/PWM (CCP1 and CCP2) ............ 276
CLKO and I/O .......................................................... 272
Clock Synchronization ............................................. 145PIC18FXX2
DS39564C-page 324 © 2006 Microchip Technology Inc.
Example SPI Master Mode (CKE = 0) ..................... 278
Example SPI Master Mode (CKE = 1) ..................... 279
Example SPI Slave Mode (CKE = 0) ....................... 280
Example SPI Slave Mode (CKE = 1) ....................... 281
External Clock (All Modes except PLL) .................... 271
First START Bit Timing ............................................ 153
I
2C Bus Data ............................................................ 282
I
2C Bus START/STOP Bits ...................................... 282
I
2C Master Mode (Reception, 7-bit Address) ........... 157
I
2C Master Mode (Transmission,
7 or 10-bit Address) ......................................... 156
I
2C Slave Mode Timing (10-bit Reception,
SEN = 0) .......................................................... 142
I
2C Slave Mode Timing (10-bit Transmission) .........143
I
2C Slave Mode Timing (7-bit Reception,
SEN = 0) .......................................................... 140
I
2C Slave Mode Timing (7-bit Reception,
SEN = 1) .................................................. 146, 147
I
2C Slave Mode Timing (7-bit Transmission) ........... 141
Low Voltage Detect .................................................. 192
Master SSP I2C Bus Data ........................................ 284
Master SSP I2C Bus START/STOP Bits .................. 284
Parallel Slave Port (PIC18F4X2) ..............................277
Parallel Slave Port (Read) ........................................ 101
Parallel Slave Port (Write) ........................................ 100
PWM Output ............................................................. 122
Repeat START Condition ......................................... 154
RESET, Watchdog Timer (WDT),
Oscillator Start-up Timer (OST) and
Power-up Timer (PWRT) ................................. 273
Slave Synchronization .............................................. 131
Slaver Mode General Call Address Sequence
(7 or 10-bit Address Mode) ..............................148
Slow Rise Time (MCLR Tied to VDD) ......................... 33
SPI Mode (Master Mode) ......................................... 130
SPI Mode (Slave Mode with CKE = 0) ..................... 132
SPI Mode (Slave Mode with CKE = 1) ..................... 132
Stop Condition Receive or Transmit Mode .............. 158
Time-out Sequence on POR w/PLL Enabled
(MCLR Tied to VDD) ........................................... 33
Time-out Sequence on Power-up
(MCLR Not Tied to VDD)
Case 1 ................................................................ 32
Case 2 ................................................................ 32
Time-out Sequence on Power-up
(MCLR Tied to VDD) ........................................... 32
Timer0 and Timer1 External Clock ........................... 275
Timing for Transition Between Timer1 and
OSC1 (HS with PLL) .......................................... 23
Transition Between Timer1 and OSC1
(HS, XT, LP) ....................................................... 22
Transition Between Timer1 and OSC1
(RC, EC) ............................................................ 23
Transition from OSC1 to Timer1 Oscillator ................ 22
USART Asynchronous Master Transmission ........... 173
USART Asynchronous Master Transmission
(Back to Back) .................................................. 173
USART Asynchronous Reception ............................175
USART Synchronous Receive (Master/Slave) .........286
USART Synchronous Reception
(Master Mode, SREN) ...................................... 178
USART Synchronous Transmission ......................... 177
USART Synchronous Transmission
(Master/Slave) .................................................. 286
USART Synchronous Transmission
(Through TXEN) .............................................. 177
Wake-up from SLEEP via Interrupt .......................... 206
Timing Diagrams Requirements
Master SSP I2C Bus START/STOP Bits .................. 284
Timing Requirements
A/D Conversion ........................................................ 288
Capture/Compare/PWM (CCP1 and CCP2) ............ 276
CLKO and I/O .......................................................... 273
Example SPI Mode (Master Mode, CKE = 0) .......... 278
Example SPI Mode (Master Mode, CKE = 1) .......... 279
Example SPI Mode (Slave Mode, CKE = 0) ............ 280
Example SPI Slave Mode (CKE = 1) ....................... 281
External Clock .......................................................... 271
I
2C Bus Data (Slave Mode) ..................................... 283
Master SSP I2C Bus Data ........................................ 285
Parallel Slave Port (PIC18F4X2) ............................. 277
RESET, Watchdog Timer, Oscillator Start-up
Timer, Power-up Timer and
Brown-out Reset Requirements ....................... 274
Timer0 and Timer1 External Clock .......................... 275
USART Synchronous Receive ................................. 286
USART Synchronous Transmission ........................ 286
Timing Specifications
PLL Clock ................................................................ 272
TRISE Register
PSPMODE Bit .....................................................95, 100
TSTFSZ ........................................................................... 251
Two-Word Instructions
Example Cases .......................................................... 41
TXSTA Register
BRGH Bit ................................................................. 168
U
Universal Synchronous Asynchronous
Receiver Transmitter. See USART
USART ............................................................................. 165
Asynchronous Mode ................................................ 172
Associated Registers, Receive ........................ 175
Associated Registers, Transmit ....................... 173
Receiver .......................................................... 174
Transmitter ....................................................... 172
Baud Rate Generator (BRG) ................................... 168
Associated Registers ....................................... 168
Baud Rate Error, Calculating ........................... 168
Baud Rate Formula .......................................... 168
Baud Rates for Asynchronous Mode
(BRGH = 0) .............................................. 170
Baud Rates for Asynchronous Mode
(BRGH = 1) .............................................. 171
Baud Rates for Synchronous Mode ................. 169
High Baud Rate Select (BRGH Bit) ................. 168
Sampling .......................................................... 168
Serial Port Enable (SPEN Bit) ................................. 165
Synchronous Master Mode ...................................... 176
Associated Registers, Reception ..................... 178
Associated Registers, Transmit ....................... 176
Reception ........................................................ 178
Transmission ................................................... 176
Synchronous Slave Mode ........................................ 179
Associated Registers, Receive ........................ 180
Associated Registers, Transmit ....................... 179
Reception ........................................................ 180
Transmission ................................................... 179© 2006 Microchip Technology Inc. DS39564C-page 325
PIC18FXX2
W
Wake-up from SLEEP .............................................. 195, 205
Using Interrupts ........................................................ 205
Watchdog Timer (WDT) ........................................... 195, 203
Associated Registers ............................................... 204
Control Register ....................................................... 203
Postscaler ........................................................ 203, 204
Programming Considerations .................................. 203
RC Oscillator ............................................................ 203
Time-out Period ....................................................... 203
WCOL .............................................................................. 153
WCOL Status Flag ............................................153, 155, 158
WWW, On-Line Support ....................................................... 5
X
XORLW ............................................................................ 251
XORWF ........................................................................... 252PIC18FXX2
DS39564C-page 326 © 2006 Microchip Technology Inc.
NOTES:© 2006 Microchip Technology Inc. DS39564C-page 327
PIC18FXX2
THE MICROCHIP WEB SITE
Microchip provides online support via our WWW site at
www.microchip.com. This web site is used as a means
to make files and information easily available to
customers. Accessible by using your favorite Internet
browser, the web site contains the following
information:
• Product Support – Data sheets and errata,
application notes and sample programs, design
resources, user’s guides and hardware support
documents, latest software releases and archived
software
• General Technical Support – Frequently Asked
Questions (FAQ), technical support requests,
online discussion groups, Microchip consultant
program member listing
• Business of Microchip – Product selector and
ordering guides, latest Microchip press releases,
listing of seminars and events, listings of
Microchip sales offices, distributors and factory
representatives
CUSTOMER CHANGE NOTIFICATION
SERVICE
Microchip’s customer notification service helps keep
customers current on Microchip products. Subscribers
will receive e-mail notification whenever there are
changes, updates, revisions or errata related to a
specified product family or development tool of interest.
To register, access the Microchip web site at
www.microchip.com, click on Customer Change
Notification and follow the registration instructions.
CUSTOMER SUPPORT
Users of Microchip products can receive assistance
through several channels:
• Distributor or Representative
• Local Sales Office
• Field Application Engineer (FAE)
• Technical Support
• Development Systems Information Line
Customers should contact their distributor,
representative or field application engineer (FAE) for
support. Local sales offices are also available to help
customers. A listing of sales offices and locations is
included in the back of this document.
Technical support is available through the web site
at: http://support.microchip.comPIC18FXX2
DS39564C-page 328 Advance Information © 2006 Microchip Technology Inc.
READER RESPONSE
It is our intention to provide you with the best documentation possible to ensure successful use of your Microchip product.
If you wish to provide your comments on organization, clarity, subject matter, and ways in which our documentation
can better serve you, please FAX your comments to the Technical Publications Manager at (480) 792-4150.
Please list the following information, and use this outline to provide us with your comments about this document.
To: Technical Publications Manager
RE: Reader Response
Total Pages Sent ________
From: Name
Company
Address
City / State / ZIP / Country
Telephone: (_______) _________ - _________
Application (optional):
Would you like a reply? Y N
Device: Literature Number:
Questions:
FAX: (______) _________ - _________
PIC18FXX2 DS39564C
1. What are the best features of this document?
2. How does this document meet your hardware and software development needs?
3. Do you find the organization of this document easy to follow? If not, why?
4. What additions to the document do you think would enhance the structure and subject?
5. What deletions from the document could be made without affecting the overall usefulness?
6. Is there any incorrect or misleading information (what and where)?
7. How would you improve this document?© 2006 Microchip Technology Inc. DS39564C-page 329
PIC18FXX2
PIC18FXX2 PRODUCT IDENTIFICATION SYSTEM
To order or obtain information, e.g., on pricing or delivery, refer to the factory or the listed sales office.
PART NO. − X /XX XXX
Temperature Package Pattern
Range
Device
Device PIC18FXX2(1), PIC18FXX2T(2);
VDD range 4.2V to 5.5V
PIC18LFXX2(1), PIC18LFXX2T(2);
VDD range 2.5V to 5.5V
Temperature
Range
I = -40°C to +85°C (Industrial)
E = -40°C to +125°C (Extended)
Package PT = TQFP (Thin Quad Flatpack)
SO = SOIC
SP = Skinny Plastic DIP
P = PDIP
L = PLCC
Pattern QTP, SQTP, Code or Special Requirements
(blank otherwise)
Examples:
a) PIC18LF452 - I/P 301 = Industrial temp.,
PDIP package, Extended VDD limits,
QTP pattern #301.
b) PIC18LF242 - I/SO = Industrial temp.,
SOIC package, Extended VDD limits.
c) PIC18F442 - E/P = Extended temp.,
PDIP package, normal VDD limits.
Note 1: F = Standard Voltage range
LF = Wide Voltage Range
2: T = in tape and reel - SOIC,
PLCC, and TQFP
packages only.DS39564C-page 330 © 2006 Microchip Technology Inc.
AMERICAS
Corporate Office
2355 West Chandler Blvd.
Chandler, AZ 85224-6199
Tel: 480-792-7200
Fax: 480-792-7277
Technical Support:
http://support.microchip.com
Web Address:
www.microchip.com
Atlanta
Alpharetta, GA
Tel: 770-640-0034
Fax: 770-640-0307
Boston
Westborough, MA
Tel: 774-760-0087
Fax: 774-760-0088
Chicago
Itasca, IL
Tel: 630-285-0071
Fax: 630-285-0075
Dallas
Addison, TX
Tel: 972-818-7423
Fax: 972-818-2924
Detroit
Farmington Hills, MI
Tel: 248-538-2250
Fax: 248-538-2260
Kokomo
Kokomo, IN
Tel: 765-864-8360
Fax: 765-864-8387
Los Angeles
Mission Viejo, CA
Tel: 949-462-9523
Fax: 949-462-9608
Santa Clara
Santa Clara, CA
Tel: 408-961-6444
Fax: 408-961-6445
Toronto
Mississauga, Ontario,
Canada
Tel: 905-673-0699
Fax: 905-673-6509
ASIA/PACIFIC
Asia Pacific Office
Suites 3707-14, 37th Floor
Tower 6, The Gateway
Habour City, Kowloon
Hong Kong
Tel: 852-2401-1200
Fax: 852-2401-3431
Australia - Sydney
Tel: 61-2-9868-6733
Fax: 61-2-9868-6755
China - Beijing
Tel: 86-10-8528-2100
Fax: 86-10-8528-2104
China - Chengdu
Tel: 86-28-8665-5511
Fax: 86-28-8665-7889
China - Fuzhou
Tel: 86-591-8750-3506
Fax: 86-591-8750-3521
China - Hong Kong SAR
Tel: 852-2401-1200
Fax: 852-2401-3431
China - Qingdao
Tel: 86-532-8502-7355
Fax: 86-532-8502-7205
China - Shanghai
Tel: 86-21-5407-5533
Fax: 86-21-5407-5066
China - Shenyang
Tel: 86-24-2334-2829
Fax: 86-24-2334-2393
China - Shenzhen
Tel: 86-755-8203-2660
Fax: 86-755-8203-1760
China - Shunde
Tel: 86-757-2839-5507
Fax: 86-757-2839-5571
China - Wuhan
Tel: 86-27-5980-5300
Fax: 86-27-5980-5118
China - Xian
Tel: 86-29-8833-7250
Fax: 86-29-8833-7256
ASIA/PACIFIC
India - Bangalore
Tel: 91-80-4182-8400
Fax: 91-80-4182-8422
India - New Delhi
Tel: 91-11-4160-8631
Fax: 91-11-4160-8632
India - Pune
Tel: 91-20-2566-1512
Fax: 91-20-2566-1513
Japan - Yokohama
Tel: 81-45-471- 6166
Fax: 81-45-471-6122
Korea - Gumi
Tel: 82-54-473-4301
Fax: 82-54-473-4302
Korea - Seoul
Tel: 82-2-554-7200
Fax: 82-2-558-5932 or
82-2-558-5934
Malaysia - Penang
Tel: 60-4-646-8870
Fax: 60-4-646-5086
Philippines - Manila
Tel: 63-2-634-9065
Fax: 63-2-634-9069
Singapore
Tel: 65-6334-8870
Fax: 65-6334-8850
Taiwan - Hsin Chu
Tel: 886-3-572-9526
Fax: 886-3-572-6459
Taiwan - Kaohsiung
Tel: 886-7-536-4818
Fax: 886-7-536-4803
Taiwan - Taipei
Tel: 886-2-2500-6610
Fax: 886-2-2508-0102
Thailand - Bangkok
Tel: 66-2-694-1351
Fax: 66-2-694-1350
EUROPE
Austria - Wels
Tel: 43-7242-2244-3910
Fax: 43-7242-2244-393
Denmark - Copenhagen
Tel: 45-4450-2828
Fax: 45-4485-2829
France - Paris
Tel: 33-1-69-53-63-20
Fax: 33-1-69-30-90-79
Germany - Munich
Tel: 49-89-627-144-0
Fax: 49-89-627-144-44
Italy - Milan
Tel: 39-0331-742611
Fax: 39-0331-466781
Netherlands - Drunen
Tel: 31-416-690399
Fax: 31-416-690340
Spain - Madrid
Tel: 34-91-708-08-90
Fax: 34-91-708-08-91
UK - Wokingham
Tel: 44-118-921-5869
Fax: 44-118-921-5820
WORLDWIDE SALES AND SERVICE
08/29/06
9596C–AT42–05/2013
Features
Configurations:
Comms mode
Standalone mode
Number of Keys:
Comms mode: 1 – 7 keys (or 1 – 6 keys plus a Guard Channel)
Standalone mode: 1 – 4 keys plus a fixed Guard Channel on key 0
Number of I/O Lines:
Standalone mode: 5 outputs
Technology:
Patented spread-spectrum charge-transfer
Key Outline Sizes:
6 mm x 6 mm or larger (panel thickness dependent); widely different sizes and
shapes possible
Layers Required:
One
Electrode Materials:
Etched copper; Silver; Carbon; Indium Tin Oxide (ITO)
Panel Materials:
Plastic; Glass; Composites; Painted surfaces (low particle density metallic
paints possible
Panel Thickness:
Up to 10 mm glass; Up to 5 mm plastic (electrode size dependent)
Key Sensitivity:
Comms mode: individually settable via simple commands over I2
C-compatible
interface
Standalone mode: settings are fixed
Interface:
I
2
C-compatible slave mode (400 kHz). Discrete detection outputs
Signal Processing:
Self-calibration
Auto drift compensation
Noise filtering
Adjacent Key Suppression® (AKS®) – up to three groups possible
Power:
1.8 V – 5.5 V
Package:
14-pin SOIC RoHS compliant IC
20-pin VQFN RoHS compliant IC
Atmel AT42QT1070
Seven-channel QTouch® Touch Sensor IC
DATASHEETAT42QT1070 [DATASHEET] 2
9596C–AT42–05/2013
1. Pinouts and Schematics
1.1 Pinout Configuration – Comms Mode (14-pin SOIC)
1.2 Pinout Configuration – Standalone Mode (14-pin SOIC)
VDD
MODE (Vss)
RESET
SDA
CHANGE
KEY2
KEY1
KEY0
1
2
3
4
5
6
7 8
9
10
11
12
13
14
QT1070
SCL
KEY6
KEY3
VSS
KEY5
KEY4
VDD
MODE (Vdd)
RESET
OUT0
OUT4
KEY2
KEY1
KEY0
1
2
3
4
5
6
7 8
9
10
11
12
13
14
QT1070
OUT3
OUT2
KEY3
VSS
OUT1
KEY4AT42QT1070 [DATASHEET] 3 9596C–AT42–05/2013
1.3 Pinout Configuration – Comms Mode (20-pin VQFN)
1.4 Pinout Configuration – Standalone Mode (20-pin VQFN) NCNC VSS VDDNC
KEY4
KEY3
KEY2
KEY1
KEY0 MODE (Vss)
SDA
1
2
3
4
5 11
12
13
14
15
20 19 18 17 16
6 7 8 9 10
QT1070 RESET
CHANGE
SCL
NC
NC
NC
KEY5
KEY6
NC
NC
VSS
VDD
NC
KEY4
KEY3
KEY2
KEY1
KEY0 MODE (Vdd)
OUT0
1
2
3
4
5 11
12
13
14
15
20 19 18 17 16
6 7 8 9 10
QT1070 RESET
OUT4
OUT3
NC
NC
NC
OUT1
OUT2AT42QT1070 [DATASHEET] 4
9596C–AT42–05/2013
1.5 Pin Descriptions
I Input only O Output only, push-pull
OD Open drain output P Ground or power
Table 1-1. Pin Listings (14-pin SOIC)
Pin
Name
(Comms
Mode)
Name
(Standalone
Mode) Type Description
If Unused,
Connect
To...
1 VDD VDD P Power –
2 MODE MODE I
Mode selection pin
Comms Mode – connect to Vss
Standalone Mode – connect to Vdd
–
3 SDA OUT0 OD
Comms Mode – I2
C data line
Standalone Mode – open drain output for guard
channel
Open
4 RESET RESET I RESET – has internal pull-up 60 k resistor Open
5 CHANGE OUT4 OD
CHANGE line for controlling the communications
flow
Comms Mode – connect to CHANGE line
Standalone Mode – connect to output
Open
6 SCL OUT3 OD
Comms Mode – connect to I
2
C clock
Standalone Mode – connect to output Open
7 KEY6 OUT2 O/OD
Comms Mode – connect to Key 6
Standalone Mode – connect to output Open
8 KEY5 OUT1 O/OD
Comms Mode – connect to Key 5
Standalone Mode – connect to output Open
9 KEY4 KEY4 O Key 4 Open
10 KEY3 KEY3 O Key 3 Open
11 KEY2 KEY2 O Key 2 Open
12 KEY1 KEY1 O Key 1 Open
13 KEY0 KEY0 O Key 0 Open
14 VSS VSS P Ground –AT42QT1070 [DATASHEET] 5 9596C–AT42–05/2013
I Input only O Output only, push-pull
OD Open drain output P Ground or power
Table 1-2. Pin Listings (20-pin VQFN)
Pin
Name
(Comms
Mode)
Name
(Standalone
Mode) Type Description
If Unused,
Connect
To...
1 KEY4 KEY4 O Key 4 Open
2 KEY3 KEY3 O Key 3 Open
3 KEY2 KEY2 O Key 2 Open
4 KEY1 KEY1 O Key 1 Open
5 KEY0 KEY0 O Key 0 Open
6 NC NC – Not connected –
7 NC NC – Not connected –
8 VSS VSS P Ground –
9 VDD VDD P Power –
10 NC NC – Not connected –
11 MODE MODE I
Mode selection pin
Comms Mode – connect to Vss
Standalone Mode – connect to Vdd
–
12 SDA OUT0 OD
Comms Mode – I2
C data line
Standalone Mode – open drain output for
guard channel
Open
13 RESET RESET I RESET – has internal pull-up 60 k resistor Open
14 CHANGE OUT4 OD
CHANGE line for controlling the communications
flow
Comms Mode – connect to CHANGE line
Standalone Mode – connects to output
Open
15 SCL OUT3 OD
Comms Mode – connect to I
2
C clock
Standalone Mode – connect to output Open
16 KEY6 OUT2 O/OD
Comms Mode – connect to Key 6
Standalone Mode – connect to output Open
17 KEY5 OUT1 O/OD
Comms Mode – connect to Key 5
Standalone Mode – connect to output Open
18 NC NC – Not connected –
19 NC NC – Not connected –
20 NC NC – Not connected –AT42QT1070 [DATASHEET] 6
9596C–AT42–05/2013
1.6 Schematics
Figure 1-1. Typical Circuit – Comms (14-pin SOIC)
Figure 1-2. Typical Circuit – Standalone (14-pin SOIC)
Rs6
C1
K4
RSCL
Rs5
Rs4
Rs3
Rs2
Rs1
K3
K2
K1
1
QT1070
MODE (Vss)
2
SDA 3
RESET 4
CHANGE 5
SCL 6
KEY6 7
KEY5 8
KEY4 9
KEY3 10
KEY2 11
KEY1 12
KEY0 13
14
Vss
Rs0 K0
Vss
Vdd
CHANGE
SDA
RESET
K5
K6
Vdd
SCL
Vdd
Vss
RSDA
Vdd
RCHG RRST
ROUT2
C1
K4
ROUT3
ROUT1
Rs4
Rs3
Rs2
Rs1
K3
K2
K1
1
OUT0 3
RESET 4
OUT4 5
OUT3 6
OUT2 7
OUT1 8
KEY4 9
KEY3 10
KEY2 11
KEY1 12
KEY0 13
Vss
Rs0 K0
Vss
ROUT4
Vdd
RESET
COUT1
COUT2
COUT3
Vss
COUT4
COUT0
14
Vss
QT1070
Vdd
Vss
OUTPUTS
OUTPUTS
ROUT0
MODE (Vdd)
2
COUT1, 2 3 and are optional
COUT0 4 and are optional
R1
VddAT42QT1070 [DATASHEET] 7 9596C–AT42–05/2013
Figure 1-3. Typical Circuit – Comms (20-pin VQFN)
Figure 1-4. Typical Circuit – Standalone (20-pin VQFN)
For component values in Figure 1-1, 1-2, 1-3, and 1-4, check the following sections:
Section 3.1 on page 12: Series resistors (Rs0 – Rs6 for comms mode and Rs0 – Rs4 for standalone mode)
Section 3.2 on page 12: LED traces
Section 3.4 on page 12: Power Supply (voltage levels)
Section 4.4 on page 14: SDA, SCL pull-up resistors
Rs6
C1
K4
Rs5
Rs4
Rs3
Rs2
Rs1
K3
K2
K1
9
QT1070
SCL 15
SDA 12
RESET 13
CHANGE 14 KEY6 16
KEY5 17
KEY4 1
KEY3 2
KEY2 3
KEY1 4
KEY0 5
8
Vss
Rs0 K0
Vss
Vdd
K5
K6
RSCL
Vdd Vdd
Vss
11
MODE (Vss)
N/C
N/C 18
N/C 19
N/C 20
N/C 7
N/C 6
10
CHANGE
SDA
RESET
RSDA
Vdd
RCHG RRST
RsOUT2
K4
RsOUT3
RLOUT1
Rs4
Rs3
Rs2
Rs1
K3
K2
K1
OUT0 12
RESET 13
OUT4 14
OUT3 15
OUT2 16
OUT1 17
KEY4 1
KEY3 2
KEY2 3
KEY1
KEY0 5
Vss
Rs0 K0
ROUT4
RESET
COUT1
COUT2
COUT3
Vss
COUT4
COUT0
8
QT1070
Vss
OUTPUTS
OUTPUTS
N/C
N/C 18
N/C 19
N/C 20
N/C 7
N/C 6
10
4
ROUT0
Vss
C1
9 Vss
Vdd
MODE (Vdd) Vdd
11
COUT1, 2 3 and are optional
COUT0 4 and are optional
R1
VddAT42QT1070 [DATASHEET] 8
9596C–AT42–05/2013
2. Overview
2.1 Introduction
The AT42QT1070 (QT1070) is a digital burst mode charge-transfer (QT™) capacitive sensor driver. The device can
sense from one to seven keys, dependent on mode.
The QT1070 includes all signal processing functions necessary to provide stable sensing under a wide variety of
changing conditions, and the outputs are fully debounced. Only a few external parts are required for operation and
no external Cs capacitors are required.
The QT1070 modulates its bursts in a spread-spectrum fashion in order to heavily suppress the effects of external
noise, and to suppress RF emissions. The QT1070 uses a dual-pulse method of acquisition. This provides greater
noise immunity and eliminates the need for external sampling capacitors, allowing touch sensing using a single pin.
2.2 Modes
2.2.1 Comms Mode
The QT1070 can operate in comms mode where a host can communicate with the device via an I2
C bus. This allows
the user to configure settings for Threshold, Adjacent Key Suppression (AKS), Detect Integrator, Low Power (LP)
Mode, Guard Channel and Max Time On for keys.
2.2.2 Standalone Mode
The QT1070 can operate in a standalone mode where an I2
C interface is not required. To enter standalone mode,
connect the Mode pin to Vdd before powering up the QT1070.
In standalone mode, the start-up values are hard coded in firmware and cannot be changed. The default start-up
values are used. This means that key detection is reported via their respective IOs. The Guard channel feature is
automatically implemented on key 0 in standalone mode. This means that this channel gets priority over all other
keys going into touch.
2.3 Keys
Dependent on mode, the QT1070 can have a minimum of one key and a maximum of seven keys. These can be
constructed in different shapes and sizes. See “Features” on page 1 for the recommended dimensions.
Comms mode – 1 to 7 keys (or 1 to 6 keys plus Guard Channel)
Standalone mode – 1 to 4 keys plus a Guard Channel
Unused keys should be disabled by setting the averaging factor to zero (see Section 5.9 on page 18).
The status register can be read to determine the touch status of the corresponding key. It is recommended using the
open-drain CHANGE line to detect when a change of status has occurred.
2.4 Input/Output (IO) Lines
There are no IO lines in comms mode.
In Standalone mode pins OUT0 – OUT4 can be used as open drain outputs for driving LEDs.
2.5 Acquisition/Low Power Mode (LP)
There are 255 different acquisition times possible. These are controlled via the LP mode byte (see Section 5.11 on
page 19) which can be written to via I2
C communication.
LP mode controls the intervals between acquisition measurements. Longer intervals consume lower power but have
an increased response time. During calibration, touch and during the detect integrator (DI) period, the LP mode is
temporarily set to LP mode 1 for a faster response.AT42QT1070 [DATASHEET] 9 9596C–AT42–05/2013
The QT1070 operation is based on a fixed cycle time of approximately 8 ms. The LP mode setting indicates how
many of these periods exist per measurement cycle. For example, If LP mode = 1, there is an acquisition every cycle
(8 ms). If LP mode = 3, there is an acquisition every 3 cycles (24 ms). If a high Averaging Factor (see Section 5.9 on
page 18) setting is selected then the acquisition time may exceed 8 ms.
LP settings above mode 32 (256 ms) result in slower thermal drift compensation and should be avoided in
applications where fast thermal transients occur.
2.6 Adjacent Key Suppression (AKS) Technology
The device includes the Atmel-patented Adjacent Key Suppression (AKS) technology, to allow the use of tightly
spaced keys on a keypad with no loss of selectability by the user.
There can be up to three AKS groups, implemented so that only one key in the group may be reported as being
touched at any one time. Once a key in a particular AKS group is in detect no other key in that group can go into
detect. Only when the key in detect goes out of detection can another key go into detect state.
The keys which are members of the AKS groups can be set (see Section 5.9 on page 18). Keys outside the group
may be in detect simultaneously.
2.7 CHANGE Line (Comms Mode Only)
The CHANGE line is active low and signals when there is a change of state in the Detection or Input key status
bytes. It is cleared (allowed to float high) when the host reads the status bytes.
If the status bytes change back to their original state before the host has read the status bytes (for example, a touch
followed by a release), the CHANGE line will be held low. In this case, a read to any memory location will clear the
CHANGE line.
The CHANGE line is open-drain and should be connected via a 47 k resistor to Vdd. It is necessary for minimum
power operation as it ensures that the QT1070 can sleep for as long as possible. Communications wake up the
QT1070 from sleep causing a higher power consumption if the part is randomly polled.
Note: The CHANGE line is pulled low 100 ms after power-up or reset.
2.8 Types of Reset
2.8.1 External Reset
An external reset logic line can be used if desired, fed into the RESET pin. However, under most conditions it is
acceptable to tie RESET to Vdd.
2.8.2 Soft Reset
The host can cause a device reset by writing a nonzero value to the RESET byte. This soft reset triggers the internal
watchdog timer on a 125 ms interval. After 125 ms the device resets and wakes again.
The device NACKs any attempts to communicate with it during the first 30 ms of its initialization period.
2.9 Calibration
Writing a non-zero value to the calibration byte can force a recalibration at any time. This can be useful to clear out a
stuck key condition after a prolonged period of uninterrupted detection.
Note: A calibrate command clears all key status bits and the overflow bit (until it is checked on the next cycle).AT42QT1070 [DATASHEET] 10
9596C–AT42–05/2013
2.10 Guard Channel
A guard channel to help prevent false detection is available in both modes. This is fixed on key 0 for standalone
mode and programmable for comms mode.
Guard channel keys should be more sensitive than the other keys (physically bigger). Because the guard channel
key is physically bigger it becomes more susceptible to noise so it has a higher Averaging Factor (see Section 5.9 on
page 18) and a lower Threshold (see Section 5.8 on page 18) than the other keys. In standalone mode it has an
Averaging Factor of 16 and a Threshold of 10 counts.
A channel set as the guard channel (there can only be one) is prioritised when the filtering of keys going into detect
is taking place. So if a normal key is filtering into touch (touch present but DI has not been reached) and the key set
as the guard key begins filtering in, then the normal key’s filter is reset and the guard key filters in first.
The guard channel is connected to a sensor pad which detects the presence of touch and overrides any output from
the other keys.
Figure 2-1. Guard Channel Example
2.11 Signal Processing
2.11.1 Detect Threshold
The device detects a touch when the signal has crossed a threshold level and remained there for a specified number
of counts (see Section 5.10 on page 19). This can be altered on a key-by-key basis using the key threshold I2C
commands.
In standalone mode the detect threshold is set to a fixed value of 10 counts of change with respect to the internal
reference level for the guard channel and 20 counts for the other four keys. The reference level has the ability to
adjust itself slowly in accordance with the drift compensation mechanism.
The drift mechanism will drift toward touch at a rate of 160 ms × 18 = 2.88 seconds and away from touch at a rate of
160 ms × 6 = 0.96 seconds. The 160 ms is based on 20 × 8 ms cycles. If the cycle time exceeds 8 ms then the
overall times will be extended to match.
2.11.2 Detect Integrator
The device features a fast detection integrator counter (DI filter), which acts to filter out noise at the small expense of
a slower response time. The DI filter requires a programmable number of consecutive samples confirmed in
detection before the key is declared to be touched. The minimum number for the DI filter is 2. Settings of 0 and 1 for
the DI also default to 2.
The DI is also implemented when a touch is removed. This uses the Fast Out DI option. When bit 5 of Address 53 is
set the a key filters out with an integrator of 4.
Guard channelAT42QT1070 [DATASHEET] 11 9596C–AT42–05/2013
2.11.3 Cx Limitations
The recommended range for key capacitance Cx is 1 pF – 30 pF. Larger values of Cx will give reduced sensitivity.
2.11.4 Max On Duration
If an object or material obstructs the sense pad the signal may rise enough to create a detection, preventing further
operation. To prevent this, the sensor includes a timer which monitors detections. If a detection exceeds the timer
setting the sensor performs a key recalibration. This is known as the Max On duration feature and is set to
approximately 30 s in standalone mode.
In comms mode this feature can be changed by setting a value in the range 1 – 255
(160 ms – 40,800 ms) in steps of 160 ms. A setting of 0 disables the Max On Duration recalibration feature.
Note: If bit 4 of address 53 is clear then a recalibration of all keys occurs on Max On Duration, otherwise individual
key recalibration occurs.
2.11.5 Positive Recalibration
If a keys signal jumps in the negative direction (with respect to its reference) by more than the Positive Recalibration
setting (4 counts), then a recalibration of that key takes place.
2.11.6 Drift Hold Time
Drift Hold Time (DHT) is used to restrict drift on all keys while one or more keys are activated. DHT restricts the
drifting on all keys until approximately four seconds after all touches have been removed.
This feature is particularly useful in cases of high-density keypads where touching a key or hovering a finger over the
keypad would cause untouched keys to drift, and therefore create a sensitivity shift, and ultimately inhibit touch
detection.
2.11.7 Hysteresis
Hysteresis is fixed at 12.5% of the Detect Threshold. When a key enters a detect state once the DI count has been
reached, the NTHR value is changed by a small amount (12.5% of NTHR) in the direction away from touch. This is
done to affect hysteresis and so makes it less likely a key will dither in and out of detect. NTHR is restored once the
key drops out of detect.+AT42QT1070 [DATASHEET] 12
9596C–AT42–05/2013
3. Wiring and Parts
3.1 Rs Resistors
Series resistors Rs (Rs0 – Rs6 for comms mode and Rs0 – Rs4 for standalone mode) are in line with the electrode
connections and should be used to limit electrostatic discharge (ESD) currents and to suppress radio frequency
interference (RFI). Series resistors are recommended for noise reduction. They should be approximately 4.7 k to
20 k each.
3.2 LED Traces and Other Switching Signals
Digital switching signals near the sense lines induce transients into the acquired signals, deteriorating the signal-tonoise
(SNR) performance of the device. Such signals should be routed away from the sensing traces and electrodes,
or the design should be such that these lines are not switched during the course of signal acquisition (bursts).
LED terminals which are multiplexed or switched into a floating state, and which are within, or physically very near, a
key (even if on another nearby PCB) should be bypassed to either Vss or Vdd with at least a 10 nF capacitor. This is
to suppress capacitive coupling effects which can induce false signal shifts. The bypass capacitor does not need to
be next to the LED, in fact it can be quite distant. The bypass capacitor is noncritical and can be of any type.
LED terminals which are constantly connected to Vss or Vdd do not need further bypassing.
3.3 PCB Cleanliness
Modern no-clean flux is generally compatible with capacitive sensing circuits.
If a PCB is reworked in any way, clean it thoroughly to remove all traces of the flux residue around the capacitive
sensor components. Dry it thoroughly before any further testing is conducted.
3.4 Power Supply
See Section 6.2 on page 22 for the power supply range. If the power supply fluctuates slowly with temperature, the
device tracks and compensates for these changes automatically with only minor changes in sensitivity. If the supply
voltage drifts or shifts quickly, the drift compensation mechanism is not able to keep up, causing sensitivity
anomalies or false detections.
The usual power supply considerations with QT parts apply to the device. The power should be clean and come from
a separate regulator if possible. However, this device is designed to minimize the effects of unstable power, and
except in extreme conditions should not require a separate Low Dropout (LDO) regulator.
It is assumed that a larger bypass capacitor (such as1 µF) is somewhere else in the power circuit; for example, near
the regulator.
CAUTION: If a PCB is reworked in any way, it is highly likely that the behavior of the
no-clean flux will change. This can mean that the flux changes from an inert material
to one that can absorb moisture and dramatically affect capacitive measurements
due to additional leakage currents. If so, the circuit can become erratic and exhibit
poor environmental stability.
CAUTION: A regulator IC shared with other logic can result in erratic operation and is
not advised.
A single ceramic 0.1 µF bypass capacitor, with short traces, should be placed very
close to the power pins of the IC. Failure to do so can result in device oscillation, high
current consumption and erratic operation.AT42QT1070 [DATASHEET] 13 9596C–AT42–05/2013
4. I2
C Communications (Comms Mode Only)
4.1 I2
C Protocol
4.1.1 Protocol
The I2C protocol is based around access to an address table (see Table 5-1 on page 15) and supports multibyte
reads and writes. The maximum clock rate is 400 kHz.
See Section A. on page 29 for an overview of I2
C bus operation.
4.1.2 Signals
The I2
C interface requires two signals to operate:
SDA - Serial Data
SCL - Serial Clock
A third line, CHANGE, is used to signal when the device has seen a change in the status byte:
CHANGE: Open-drain, active low when any capacitive key has changed state since the last I2
C read. After reading
the two status bytes, this pin floats (high) again if it is pulled up with an external resistor. If the status bytes change
back to their original state before the host has read the status bytes (for example, a touch followed by a release), the
CHANGE line is held low. In this case, a read to any memory location clears the CHANGE line.
4.2 I2
C Address
There is one preset I2
C address of 0x1B. This is not changeable.
4.3 Data Read/Write
4.3.1 Writing Data to the Device
The sequence of events required to write data to the device is shown next.
1. The host initiates the transfer by sending the START condition
2. The host follows this by sending the slave address of the device together with the WRITE bit.
3. The device sends an ACK.
Table 4-1. Description of Write Data Bits
Key Description
S START condition
SLA+W Slave address plus write bit
A Acknowledge bit
MemAddress Target memory address within device
Data Data to be written
P Stop condition
S SLA+W A A MemAddress Data A P
Host to Device Device Tx to HostAT42QT1070 [DATASHEET] 14
9596C–AT42–05/2013
4. The host then sends the memory address within the device it wishes to write to.
5. The device sends an ACK if the write address is in the range 0x00 – 0x7F, otherwise it sends a NACK.
6. The host transmits one or more data bytes; each is acknowledged by the device (unless trying to write to an
invalid address).
7. If the host sends more than one data byte, they are written to consecutive memory addresses.
8. The device automatically increments the target memory address after writing each data byte.
9. After writing the last data byte, the host should send the STOP condition.
Note: the host should not try to write to addresses outside the range 0x20 to 0x39 because this is the limit of the
device internal memory address.
4.3.2 Reading Data From the Device
The sequence of events required to read data from the device is shown next.
1. The host initiates the transfer by sending the START condition
2. The host follows this by sending the slave address of the device together with the WRITE bit.
3. The device sends an ACK.
4. The host then sends the memory address within the device it wishes to read from.
5. The device sends an ACK if the address to be read from is less than 0x80 otherwise it sends a NACK).
6. The host must then send a STOP and a START condition followed by the slave address again but this time
accompanied by the READ bit.
Note: Alternatively, instead of step 6 a repeated START can be sent so the host does not need to
relinquish control of the bus.
7. The device returns an ACK, followed by a data byte.
8. The host must return either an ACK or NACK.
1. If the host returns an ACK, the device subsequently transmits the data byte from the next address. Each
time a data byte is transmitted, the device automatically increments the internal address. The device
continues to return data bytes until the host responds with a NACK.
2. If the host returns a NACK, it should then terminate the transfer by issuing the STOP condition.
9. The device resets the internal address to the location indicated by the memory address sent to it previously.
Therefore, there is no need to send the memory address again when reading from the same location.
Note: Reading the 16-bit reference and signal values is not an automatic operation; reading the first byte of a 16-
bit value does not lock the other byte. As a result glitches in the reported value may be seen as values
increase from 255 to 256, or decrease from 256 to 255.
4.4 SDA, SCL
The I2
C bus transmits data and clock with SDA and SCL respectively. They are open-drain; that is I2
C master and
slave devices can only drive these lines low or leave them open. The termination resistors pull the line up to Vdd if no
I
2
C device is pulling it down.
The termination resistors commonly range from 1 k to 10 k and should be chosen so that the rise times on SDA
and SCL meet the I2
C specifications (1 µs maximum).
Standalone mode: if I2
C communications are not required, then standalone mode can be enabled by connecting the
MODE pin to Vdd. See Section 2.4 on page 8 for more information.
S SLA+W A A MemAddress S SLA+R A
A P
Host to Device Device Tx to Host
P
Data 1 Data 2 A Data n AAT42QT1070 [DATASHEET] 15 9596C–AT42–05/2013
5. Setups
5.1 Introduction
The device calibrates and processes signals using a number of algorithms specifically designed to provide for high
survivability in the face of adverse environmental challenges. User-defined Setups are employed to alter these
algorithms to suit each application. These Setups are loaded into the device over the I2C serial interfaces. In
standalone mode these settings are fixed to predetermined values.
Table 5-1. Internal Register Address Allocation
Address Use Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 R/W
0 Chip ID Major ID (= 2) Minor ID (= E) R
1 Firmware Version Firmware version number R
2 Detection status CALIBRATE OVERFLOW – – – – – TOUCH R
3 Key status Reserved Key 6 Key 5 Key 4 Key 3 Key 2 Key 1 Key 0 R
4 – 5 Key signal 0 Key signal 0 (MSByte) – Key signal 0 (LSByte) R
6 – 7 Key signal 1 Key signal 1 (MSByte) – Key signal 1 (LSByte) R
8 – 9 Key signal 2 Key signal 2 (MSByte) – Key signal 2 (LSByte) R
10 – 11 Key signal 3 Key signal 3 (MSByte) – Key signal 3 (LSByte) R
12 – 13 Key signal 4 Key signal 4 (MSByte) – Key signal 4 (LSByte) R
14 – 15 Key signal 5 Key signal 5 (MSByte) – Key signal 5 (LSByte) R
16 – 17 Key signal 6 Key signal 6 (MSByte) – Key signal 6 (LSByte) R
18 – 19 Reference data 0 Reference data 0 (MSByte) – Reference data 0 (LSByte) R
20 – 21 Reference data 1 Reference data 1 (MSByte) – Reference data 1 (LSByte) R
22 – 23 Reference data 2 Reference data 2 (MSByte) – Reference data 2 (LSByte) R
24 – 25 Reference data 3 Reference data 3 (MSByte) – Reference data 3 (LSByte) R
26 – 27 Reference data 4 Reference data 4 (MSByte) – Reference data 4 (LSByte) R
28 – 29 Reference data 5 Reference data 5 (MSByte) – Reference data 5 (LSByte) R
30 – 31 Reference data 6 Reference data 6 (MSByte) – Reference data 6 (LSByte) R
32 NTHR key 0 Negative Threshold level for key 0 R/W
33 NTHR key 1 Negative Threshold level for key 1 R/W
34 NTHR key 2 Negative Threshold level for key 2 R/W
35 NTHR key 3 Negative Threshold level for key 3 R/W
36 NTHR key 4 Negative Threshold level for key 4 R/W
37 NTHR key 5 Negative Threshold level for key 5 R/W
38 NTHR key 6 Negative Threshold level for key 6 R/W
39 AVE/AKS key 0 Adjacent key suppression level for key 0 R/W
40 AVE/AKS key 1 Adjacent key suppression level for key 1 R/WAT42QT1070 [DATASHEET] 16
9596C–AT42–05/2013
5.2 Address 0: Chip ID
MAJOR ID: Reads back as 2
MINOR ID: Reads back as E
5.3 Address 1: Firmware Version
FIRMWARE VERSION: this shows the 8-bit firmware version 1.5 (0x15).
41 AVE/AKS key 2 Adjacent key suppression level for key 2 R/W
42 AVE/AKS key 3 Adjacent key suppression level for key 3 R/W
43 AVE/AKS key 4 Adjacent key suppression level for key 4 R/W
44 AVE/AKS key 5 Adjacent key suppression level for key 5 R/W
45 AVE/AKS key 6 Adjacent key suppression level for key 6 R/W
46 DI key 0 Detection integrator counter for key 0 R/W
47 DI key 1 Detection integrator counter for key 1 R/W
48 DI key 2 Detection integrator counter for key 2 R/W
49 DI key 3 Detection integrator counter for key 3 R/W
50 DI key 4 Detection integrator counter for key 4 R/W
51 DI key 5 Detection integrator counter for key 5 R/W
52 DI key 6 Detection integrator counter for key 6 R/W
53 FO/MO/Guard No FastOutDI/ Max Cal/Guard Channel R/W
54 LP Low Power (LP) Mode R/W
55 Max On Duration Maximum On Duration R/W
56 Calibrate Calibrate R/W
57 RESET RESET R/W
Table 5-1. Internal Register Address Allocation (Continued)
Address Use Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 R/W
Table 5-2. Chip ID
Address b7 b6 b5 b4 b3 b2 b1 b0
0 MAJOR ID MINOR ID
Table 5-3. Firmware Version
Address b7 b6 b5 b4 b3 b2 b1 b0
1 FIRMWARE VERSION AT42QT1070 [DATASHEET] 17 9596C–AT42–05/2013
5.4 Address 2: Detection Status
CALIBRATE: This bit is set during a calibration sequence.
OVERFLOW: This bit is set if the time to acquire all key signals exceeds 8 ms.
TOUCH: This bit is set if any keys are in detect.
5.5 Address 3: Key Status
KEY0 – 6: bits 0 to 6 indicate which keys are in detection, if any. Touched keys report as 1, untouched or disabled
keys report as 0.
5.6 Address 4 – 17: Key Signal
KEY SIGNAL: addresses 4 – 17 allow key signals to be read for each key, starting with key 0. There are two bytes of
data for each key. These are the key’s 16-bit key signals which are accessed as two 8-bit bytes, stored MSByte first.
These addresses are read-only.
Table 5-4. Detection Status
Address b7 b6 b5 b4 b3 b2 b1 b0
2 CALIBRATE OVERFLO
W – – – – – TOUCH
Table 5-5. Key Status
Address b7 b6 b5 b4 b3 b2 b1 b0
3 Reserved KEY6 KEY5 KEY4 KEY3 KEY2 KEY1 KEY0
Table 5-6. Key Signal
Address b7 b6 b5 b4 b3 b2 b1 b0
4 MSByte OF KEY SIGNAL FOR KEY 0
5 LSByte OF KEY SIGNAL FOR KEY 0
6 – 17 MSByte/LSByte OF KEY SIGNAL FOR KEYS 1 – 6AT42QT1070 [DATASHEET] 18
9596C–AT42–05/2013
5.7 Address 18 – 31: Reference Data
REFERENCE DATA: addresses 18 – 31 allow reference data to be read for each key, starting with key 0. There are
two bytes of data for each key. These are the key’s 16-bit reference data which is accessed as two 8-bit bytes, stored
MSByte first. These addresses are read-only.
5.8 Address 32 – 38: Negative Threshold (NTHR)
NTHR Keys 0 – 6: these 8-bit values set the threshold value for each key to register a detection.
Default: 20 counts
Note: Do not use a setting of 0 as this causes a key to go into detection when its signal is equal to its reference.
5.9 Address 39 – 45: Averaging Factor/Adjacent Key Suppression (AVE/AKS)
AVE 0 – 5: The Averaging Factor (AVE) is the number of pulses which are added together and averaged to get the
final signal value for that channel.
For example, if AVE = 8 then 8 ADC samples are taken and added together. The result is divided by the original
number of pulses (8). If sixteen pulses are used then the result is divided by sixteen.
This provides a better signal-to-noise ratio but requires longer acquire times. Values for AVE are restricted internally
to 1, 2, 4, 8, 16 or 32.
Default: 8 (In standalone mode key 0 is 16)
AKS 0 – 1: these bits control which keys are included in an AKS group. There can be up to three groups, each
containing any number of keys (up to the maximum allowed for the mode).
Each key can have a value between 0 and 3, which assigns it to an AKS group of that number. A key may only go
into detect when it has the largest signal change of any key in its group. A value of 0 means the key is not in any AKS
group.
Default: 0x01
Table 5-7. Reference Data
Address b7 b6 b5 b4 b3 b2 b1 b0
18 MSByte OF REFERENCE DATA FOR KEY 0
19 LSByte OF REFERENCE DATA FOR KEY 0
20 – 31 MSByte/LSByte OF REFERENCE DATA FOR KEYS 1 – 6
Table 5-8. NTHR
Address b7 b6 b5 b4 b3 b2 b1 b0
32 – 38 NEGATIVE THRESHOLD FOR KEYS 0 – 6
Table 5-9. AVE/AKS
Address b7 b6 b5 b4 b3 b2 b1 b0
39 – 45 AVE5 AVE4 AVE3 AVE2 AVE1 AVE0 AKS1 AKS0AT42QT1070 [DATASHEET] 19 9596C–AT42–05/2013
5.10 Address 46 – 52: Detection Integrator (DI)
DETECTION INTEGRATOR: addresses 46 – 52 allow the DI level to be set for each key. This 8-bit value controls
the number of consecutive measurements that must be confirmed as having passed the key threshold before that
key is registered as being in detect. The minimum value for the DI filter is 2. Settings of 0 and 1 for the DI also default
to 2 because a minimum of two consecutive measurements must be confirmed.
Default: 4
5.11 Address 53: FastOutDI/Max Cal/Guard Channel
FO: Fast Out DI – when bit 5 is set then a key filters out with an integrator of 4. Could have a DI in of 100 but filter out
with DI of 4 (global setting for all keys).
MAX CAL: if this bit is clear then all keys recalibrate after a Max On Duration timeout, otherwise only the key with the
incorrect timing gets recalibrated.
GUARD CHANNEL: bits 0 – 3 are used to set a key as the guard channel (which gets priority filtering). Valid values
are 0 – 6, with any larger value disabling the guard key feature.
5.12 Address 54: Low Power (LP) Mode
Table 5-10. Detection Integrator
Address b7 b6 b5 b4 b3 b2 b1 b0
46 – 52 DETECTION INTEGRATOR
Table 5-11. Max Cal/Guard Channel
Address b7 b6 b5 b4 b3 b2 b1 b0
53 – FO MAX CAL GUARD CHANNEL
Table 5-12. LP Mode
Address b7 b6 b5 b4 b3 b2 b1 b0
54 LOW POWER MODEAT42QT1070 [DATASHEET] 20
9596C–AT42–05/2013
LP MODE: this 8-bit value determines the number of 8 ms intervals between key measurements. Longer intervals
between measurements yield a lower power consumption but at the expense of a slower response to touch.
Default: 2 (16 ms between key acquisitions)
5.13 Address 55: Max On Duration
MAX ON DURATION: this is a 8-bit value which determines how long any key can be in touch before it recalibrates
itself.
A value of 0 turns Max On Duration off.
Default: 180 (160 ms × 180 = 28.8s)
Setting Time
0 8 ms
1 8 ms
2 16 ms
3 24 ms
4 32 ms
254 2.032s
255 2.040s
Table 5-13. Max Time On
Address b7 b6 b5 b4 b3 b2 b1 b0
55 MAX ON DURATION
Setting Time
0 Off
1 160 ms
2 320 ms
3 480 ms
4 640 ms
255 40.8sAT42QT1070 [DATASHEET] 21 9596C–AT42–05/2013
5.14 Address 56: Calibrate
Writing any nonzero value into this address triggers the device to start a calibration cycle. The CALIBRATE flag in
the detection status register is set when the calibration begins and clears when the calibration has finished.
5.15 Address 57: RESET
Writing any nonzero value to this address triggers the device to reset.
Table 5-14. Calibrate
Address b7 b6 b5 b4 b3 b2 b1 b0
56 Writing a nonzero value forces a calibration
Table 5-15. RESET
Address b7 b6 b5 b4 b3 b2 b1 b0
57 Writing a nonzero value forces a resetAT42QT1070 [DATASHEET] 22
9596C–AT42–05/2013
6. Specifications
6.1 Absolute Maximum Specifications
6.2 Recommended Operating Conditions
6.3 DC Specifications
Vdd –0.5 to +6 V
Max continuous pin current, any control or drive pin ±10 mA
Short circuit duration to ground, any pin infinite
Short circuit duration to Vdd, any pin infinite
Voltage forced onto any pin –0.5 V to (Vdd + 0.5) V
CAUTION: Stresses beyond those listed under Absolute Maximum Specifications may cause permanent damage to
the device. This is a stress rating only and functional operation of the device at these or other conditions beyond
those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum
specification conditions for extended periods may affect device reliability.
Operating temperature –40o
C to +85o
C
Storage temperature –55o
C to +125o
C
Vdd +1.8 V to 5.5 V
Supply ripple+noise ±25 mV
Cx load capacitance per key 1 to 30 pF
Vdd = 3.3 V, Cs = 10 nF, load = 5 pF, 32 ms default sleep, Ta = recommended range, unless otherwise noted
Parameter Description Minimum Typical Maximum Units Notes
Vil Low input logic level – – 0.2 × Vdd V
Vih High input logic level 0.7 × Vdd – Vdd + 0.5 V
Vol Low output voltage – – 0.6 V
Voh High output voltage Vdd –
0.7V – – V
Iil Input leakage current – – ±1 µAAT42QT1070 [DATASHEET] 23 9596C–AT42–05/2013
6.4 Power Consumption Measurements
6.5 Timing Specifications
Cx = 5 pF, Rs = 4.7 k
LP Mode
Idd (µA) at Vdd =
5 V 3.3 V 1.8 V
0 (8 ms) 1744 906 442
1 (16 ms) 1375 615 305
2 (24 ms) 1263 525 261
4 (32 ms) 1168 486 234
5 (40 ms) 1119 445 221
6 (48 ms) 1089 434 211
Paramete
r Description Minimum
Typica
l Maximum Units Notes
TR Response time DI
setting × 8 ms – LP mode +
(DI setting × 8 ms) ms Under host control
FQT Sample frequency 162 180 198 kHz
Modulated
spread-spectrum
(chirp)
TD
Power-up delay to
operate/calibration
time
– <230 – ms Can be longer if burst
is very long.
FI2C I
2
C clock rate – – 400 kHz –
Fm Burst modulation,
percentage ±8 % –
RESET pulse width 5 – – µs –AT42QT1070 [DATASHEET] 24
9596C–AT42–05/2013
6.6 Mechanical Dimensions
6.7 AT42QT1070-SSU – 14-pin SOIC
42077B-MCU-10/2013
USER GUIDE
Atmel OLED1 Xplained Pro
Preface
Atmel® OLED1 Xplained Pro is an extension board to the Atmel Xplained
Pro evaluation platform. The board enables the user to experiment with user
interface applications with buttons, LEDs and a display.Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
2
Table of Contents
Preface .......................................................................................... 1
1. Introduction .............................................................................. 3
1.1. Features .............................................................................. 3
1.2. Kit overview ......................................................................... 3
2. Getting started ......................................................................... 4
2.1. 3 Steps to start exploring the Atmel Xplained Pro platform ............. 4
2.2. Connecting OLED1 Xplained Pro to the Xplained Pro MCU
board. ................................................................................. 4
2.3. Design documentation and related links ..................................... 4
3. Xplained Pro ............................................................................ 5
3.1. Hardware identification system ................................................. 5
3.2. Standard headers and connectors ............................................ 5
3.2.1. Xplained Pro Standard Extension Header ...................... 5
4. Hardware user guide .............................................................. 7
4.1. Headers and connectors ......................................................... 7
4.1.1. OLED1 Xplained Pro extension header ......................... 7
4.2. Peripherals ........................................................................... 7
4.2.1. LEDs ...................................................................... 7
4.2.2. Push buttons ............................................................ 7
4.2.3. OLED display ........................................................... 8
5. Hardware revision history and known issues .......................... 9
5.1. Identifying product ID and revision ............................................ 9
5.2. Revision 3 ........................................................................... 9
6. Document revision history ..................................................... 10
7. Evaluation board/kit important notice .................................... 11Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
3
1. Introduction
1.1 Features
● UG-2832HSWEG04 monochrome OLED display
● 128 x 32 Pixels
● Controlled by 4-wire SPI interface, up to 100MHz
● Three LEDs
● Three Mechanical push buttons
● Xplained Pro hardware identification system
1.2 Kit overview
OLED1 Xplained Pro is a basic extension board for the Xplained Pro platform with three LEDs, three push
buttons and an OLED display. The OLED display is controlled via a SPI interface up to 100MHz. OLED1
Xplained Pro connects to any Xplained Pro standard extension header on any Xplained Pro MCU board.
Figure 1-1. OLED1 Xplained Pro top overview.Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
4
2. Getting started
2.1 3 Steps to start exploring the Atmel Xplained Pro platform
1. Download and install Atmel Studio.
2. Launch Atmel Studio.
3. Connect OLED1 Xplained Pro to an Xplained Pro MCU board and connect a USB cable to DEBUG USB
port on the Xplained Pro MCU board.
2.2 Connecting OLED1 Xplained Pro to the Xplained Pro MCU board.
Atmel OLED1 Xplained Pro has been designed to be connected to the Xplained Pro header marked EXT3.
However it is compatible with all Xplained Pro EXT headers. Please refer to the pin-out of your Xplained Pro
evaluation kit to find out which Xplained Pro EXT headers that can be used.
Once the Xplained Pro MCU board is powered the green power LED will be lit and Atmel Studio will auto
detect which Xplained Pro MCU- and extension board(s) that is connected. You will be presented with
relevant information like datasheets and kit documentation. You also have the option to launch Atmel Software
Framework (ASF) example applications. The target device is programmed and debugged by the on-board
Embedded Debugger. No external programmer or debugger tool is needed.
2.3 Design documentation and related links
The following list contains links to the most relevant documents and software for OLED1 Xplained Pro.
1. Xplained Pro products 1
- Atmel Xplained Pro is a series of small-sized and easy-to-use evaluation kits
for 8- and 32-bit Atmel microcontrollers. It consists of a series of low cost MCU boards for evaluation and
demonstration of features and capabilities of different MCU families.
2. OLED1 Xplained Pro User Guide 2
- PDF version of this User Guide.
3. OLED1 Xplained Pro Design Documentation 3
- Package containing schematics, BOM, assembly
drawings, 3D plots, layer plots etc.
4. Atmel Studio 4
- Free Atmel IDE for development of C/C++ and assembler code for Atmel
microcontrollers.
1
http://www.atmel.com/XplainedPro
2
http://www.atmel.com/Images/Atmel-42077-OLED1-Xplained-Pro_User-Guide.pdf
3
http://www.atmel.com/Images/Atmel-42077-OLED1-Xplained-Pro_User-Guide.zip
4
http://www.atmel.com/atmelstudioAtmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
5
3. Xplained Pro
Xplained Pro is an evaluation platform that provides the full Atmel microcontroller experience. The platform
consists of a series of Microcontroller (MCU) boards and extension boards that are integrated with Atmel
Studio, have Atmel Software Framework (ASF) drivers and demo code, support data streaming and more.
Xplained Pro MCU boards support a wide range of Xplained Pro extension boards that are connected through
a set of standardized headers and connectors. Each extension board has an identification (ID) chip to uniquely
identify which boards are mounted on a Xplained Pro MCU board. This information is used to present relevant
user guides, application notes, datasheets and example code through Atmel Studio. Available Xplained Pro
MCU and extension boards can be purchased in the Atmel Web Store
1
.
3.1 Hardware identification system
All Xplained Pro compatible extension boards have an Atmel ATSHA204 CryptoAuthentication™ chip mounted.
This chip contains information that identifies the extension with its name and some extra data. When an
Xplained Pro extension board is connected to an Xplained Pro MCU board the information is read and sent
to Atmel Studio. The Atmel Kits extension, installed with Atmel Studio, will give relevant information, code
examples and links to relevant documents. Table 3-1, “Xplained Pro ID Chip Content” on page 5 shows the
data fields stored in the ID chip with example content.
Table 3-1. Xplained Pro ID Chip Content
Data Field Data Type Example Content
Manufacturer ASCII string Atmel’\0’
Product Name ASCII string Segment LCD1 Xplained Pro’\0’
Product Revision ASCII string 02’\0’
Product Serial Number ASCII string 1774020200000010’\0’
Minimum Voltage [mV] uint16_t 3000
Maximum Voltage [mV] uint16_t 3600
Maximum Current [mA] uint16_t 30
3.2 Standard headers and connectors
3.2.1 Xplained Pro Standard Extension Header
All Xplained Pro kits have one or more dual row, 20 pin, 100mil extension headers. Xplained Pro MCU boards
have male headers while Xplained Pro extensions have their female counterparts. Note that all pins are not
always connected. However, all the connected pins follow the defined pin-out described in Table 3-2, “Xplained
Pro Extension Header” on page 5. The extension headers can be used to connect a wide variety of
Xplained Pro extensions to Xplained Pro MCU boards and to access the pins of the target MCU on Xplained
Pro MCU board directly.
Table 3-2. Xplained Pro Extension Header
Pin number Name Description
1 ID Communication line to the ID chip on extension board.
2 GND Ground.
3 ADC(+) Analog to digital converter , alternatively positive part of
differential ADC.
4 ADC(-) Analog to digital converter , alternatively negative part of
differential ADC.
5 GPIO1 General purpose I/O.
6 GPIO2 General purpose I/O.
7 PWM(+) Pulse width modulation , alternatively positive part of
differential PWM.
8 PWM(-) Pulse width modulation , alternatively positive part of
differential PWM.
1
http://store.atmel.com/Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
6
Pin number Name Description
9 IRQ/GPIO Interrupt request line and/or general purpose I/O.
10 SPI_SS_B/GPIO Slave select for SPI and/or general purpose I/O.
11 TWI_SDA Data line for two wire interface. Always implemented, bus
type.
12 TWI_SCL Clock line for two wire interface. Always implemented, bus
type.
13 USART_RX Receiver line of Universal Synchronous and Asynchronous
serial Receiver and Transmitter.
14 USART_TX Transmitter line of Universal Synchronous and
Asynchronous serial Receiver and Transmitter.
15 SPI_SS_A Slave select for SPI. Should be unique if possible.
16 SPI_MOSI Master out slave in line of Serial peripheral interface. Always
implemented, bus type.
17 SPI_MISO Master in slave out line of Serial peripheral interface. Always
implemented, bus type.
18 SPI_SCK Clock for Serial peripheral interface. Always implemented,
bus type.
19 GND Ground.
20 VCC Power for extension board.Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
7
4. Hardware user guide
4.1 Headers and connectors
4.1.1 OLED1 Xplained Pro extension header
OLED1 Xplained Pro implements one Xplained Pro Standard Extension Header on page 5 marked with
EXT in silkscreen. This header makes it possible to connect the board to any Xplained Pro MCU board.
The pin-out definition for the extension header can be seen in Table 4-1, “OLED1 Xplained Pro extension
header” on page 7.
Table 4-1. OLED1 Xplained Pro extension header
Pin Number Function Description
1 ID Communication line to ID chip
2 GND Ground
3 BUTTON2 Push button 2, active low
4 BUTTON3 Push button 3, active low
5 DATA_CMD_SEL Data / command select for OLED display. High = data, low =
command.
6 LED3 LED3, active low
7 LED1 LED1, active low
8 LED2 LED2, active low
9 BUTTON1 Push button 1, active low
10 DISPLAY_RESET Reset line for OLED display, active low
11 NC
12 NC
13 NC
14 NC
15 DISPLAY_SS OLED display slave select, active low
16 SPI MOSI MOSI signal SPI connected to OLED display
17 NC
18 SPI SCK Clock signal for SPI connected to OLED display
19 GND Ground
20 VCC Target supply voltage
4.2 Peripherals
4.2.1 LEDs
There are three yellow LEDs available on OLED1 Xplained Pro. The LEDs can be activated by driving the
connected I/O line low.
Table 4-2. LED connections
Pin on EXT connector Silk screen marking
7 LED1
8 LED2
6 LED3
4.2.2 Push buttons
There are three push buttons available on OLED1 Xplained Pro. When a button is pushed the corresponding
IO pin is connected to ground. There are no external pull-up resistors on OLED1 Xplained Pro, so internal pullup
resistors have to be enabled in the target microcontroller.Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
8
Note Remember to enable internal pull-up resistors in the target device to get a defined electrical level
on the IO lines connected to the buttons.
Table 4-3. Push button connections
Pin on EXT connector Silk screen marking
9 BUTTON1
3 BUTTON2
4 BUTTON3
4.2.3 OLED display
OLED1 Xplained Pro features a 128 x 32 pixel white monochrome OLED display, UG-2832HSWEG041
from
WiseChip Semiconductor Inc. The display has a SSD1306 display controller by Solomon Systech built in
and is controlled via a 4-wire SPI interface + reset with the signals described in Table 4-4, “OLED display
connections” on page 8. The datasheets for the display module or the display controller is not publicly
available and has to be acquired from the respective manufacturers.
Note Note that the OLED display does not have a SPI MISO signal. That means that data can only be
written to the display, not read.
Table 4-4. OLED display connections
Pin on EXT connector Signal Name Description
16 SPI_MOSI SPI master out, slave in signal.
Used to write data to the display
18 SPI_SCK SPI clock signal, generated by
the master.
5 DATA_CMD_SEL Data/command select.
Used to choose whether the
communication is data to the
display memory or a command to
the LCD controller.
15 DISPLAY_SS SPI slave select signal,
must be held low during SPI
communication.
10 DISPLAY_RESET Reset signal to the OLED
display, active low. Used during
initialization of the display.
1
http://www.wisechip.com.tw/english/Products_02-04.aspAtmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
9
5. Hardware revision history and known issues
5.1 Identifying product ID and revision
The revision and product identifier of Xplained Pro boards can be found in two ways, through Atmel Studio or
by looking at the sticker on the bottom side of the PCB.
By connecting a Xplained Pro MCU board to a computer with Atmel Studio running, an information window will
pop up. The first 6 digits of the serial number, which is listed under kit details, contain the product identifier and
revision. Information about connected Xplained Pro extension boards will also appear in the Atmel Kits window.
The same information can be found on the sticker on the bottom side of the PCB. Most kits will print the
identifier and revision in plain text as A09-nnnn\rr where nnnn is the identifier and rr is the revision. Boards with
limited space have a sticker with only a QR-code which contains a serial number string.
The serial number string has the following format:
"nnnnrrssssssssss"
n = product identifier
r = revision
s = serial number
The kit identifier for OLED1 Xplained Pro is 1769.
5.2 Revision 3
Revision 3 of OLED1 Xplained Pro is the initial released version.
OLED1 Xplained Pro boards with a serial number that ends with a number lower than 11148 may have a wrong
revision programmed into the Xplained Pro ID chip. This will only affect the information displayed by the Atmel
Kits extension in Atmel Studio. It will not affect the operation of the board.Atmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
10
6. Document revision history
Document
revision
Date Comment
42077B 09/2013 Added errata about revision 3 of the board.
42077A 25/02/2013 First releaseAtmel OLED1 Xplained Pro [USER GUIDE]
42077B-MCU-10/2013
11
7. Evaluation board/kit important notice
This evaluation board/kit is intended for use for FURTHER ENGINEERING, DEVELOPMENT,
DEMONSTRATION, OR EVALUATION PURPOSES ONLY. It is not a finished product and may not (yet)
comply with some or any technical or legal requirements that are applicable to finished products, including,
without limitation, directives regarding electromagnetic compatibility, recycling (WEEE), FCC, CE or UL
(except as may be otherwise noted on the board/kit). Atmel supplied this board/kit "AS IS," without any
warranties, with all faults, at the buyer's and further users' sole risk. The user assumes all responsibility
and liability for proper and safe handling of the goods. Further, the user indemnifies Atmel from all claims
arising from the handling or use of the goods. Due to the open construction of the product, it is the user's
responsibility to take any and all appropriate precautions with regard to electrostatic discharge and any other
technical or legal concerns.
EXCEPT TO THE EXTENT OF THE INDEMNITY SET FORTH ABOVE, NEITHER USER NOR
ATMEL SHALL BE LIABLE TO EACH OTHER FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES.
No license is granted under any patent right or other intellectual property right of Atmel covering or relating
to any machine, process, or combination in which such Atmel products or services might be or are used.Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com
© 2013 Atmel Corporation. All rights reserved. / Rev.: 42077B-MCU-10/2013
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel
Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted
by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE,
ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR
ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to
specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise,
Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended
to support or sustain life.
Atmel-8303H-AVR-ATtiny1634-Datasheet–02/2014
Features
• High Performance, Low Power AVR® 8-bit Microcontroller
• Advanced RISC Architecture
– 125 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
• High Endurance, Non-volatile Memory Segments
– 16K Bytes of In-System, Self-Programmable Flash Program Memory
• Endurance: 10,000 Write/Erase Cycles
– 256 Bytes of In-System Programmable EEPROM
• Endurance: 100,000 Write/Erase Cycles
– 1K Byte of Internal SRAM
– Data retention: 20 years at 85C / 100 years at 25C
– Programming Lock for Self-Programming Flash & EEPROM Data Security
• Peripheral Features
– Dedicated Hardware and QTouch® Library Support for Capacitive Touch Sensing
– One 8-bit and One 16-bit Timer/Counter with Two PWM Channels, Each
– 12-channel, 10-bit ADC
– Programmable Ultra Low Power Watchdog Timer
– On-chip Analog Comparator
– Two Full Duplex USARTs with Start Frame Detection
– Universal Serial Interface
– Slave I2
C Serial Interface
• Special Microcontroller Features
– debugWIRE On-chip Debug System
– In-System Programmable via SPI Port
– Internal and External Interrupt Sources
• Pin Change Interrupt on 18 Pins
– Low Power Idle, ADC Noise Reduction, Standby and Power-down Modes
– Enhanced Power-on Reset Circuit
– Programmable Brown-out Detection Circuit with Supply Voltage Sampling
– Calibrated 8MHz Oscillator with Temperature Calibration Option
– Calibrated 32kHz Ultra Low Power Oscillator
– On-chip Temperature Sensor
• I/O and Packages
– 18 Programmable I/O Lines
– 20-pad QFN/MLF, and 20-pin SOIC
• Operating Voltage:
– 1.8 – 5.5V
• Speed Grade:
– 0 – 2MHz @ 1.8 – 5.5V
– 0 – 8MHz @ 2.7 – 5.5V
– 0 – 12MHz @ 4.5 – 5.5V
• Temperature Range: -40C to +105C
• Low Power Consumption
– Active Mode: 0.2mA at 1.8V and 1MHz
– Idle Mode: 30µA at 1.8V and 1MHz
– Power-Down Mode (WDT Enabled): 1µA at 1.8V
– Power-Down Mode (WDT Disabled): 100nA at 1.8V
8-bit Atmel tinyAVR Microcontroller with
16K Bytes In-System Programmable Flash
ATtiny1634ATtiny1634 [DATASHEET] 2
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
1. Pin Configurations
Figure 1-1. Pinout of ATtiny1634
1
2
3
4
5
QFN/MLF
15
14
13
12
11
20
19
18
17
16
6
7
8
9
10
NOTE
Bottom pad should be
soldered to ground.
(PCINT1/AIN0) PA1
(PCINT0/AREF) PA0
GND
VCC
PC5 (XTAL1/CLKI/PCINT17)
PC0 (ADC9/OC0A/XCK0/PCINT12)
PC1 (ADC10/ICP1/SCL/USCK/XCK1/PCINT13)
PC2 (ADC11/CLKO/INT0/PCINT14)
PC3 (RESET/dW/PCINT15)
PC4 (XTAL2/PCINT16)
PA7 (PCINT7/RXD0/ADC4)
PB0 (PCINT8/TXD0/ADC5)
PB1 (ADC6/DI/SDA/RXD1/PCINT9)
PB2 (ADC7/DO/TXD1/PCINT10)
PB3 (ADC8/OC1A/PCINT11)
(PCINT6/OC1B/ADC3) PA6
(PCINT5/OC0B/ADC2) PA5
(PCINT4/T0/ADC1) PA4
(PCINT3/T1/SNS/ADC0) PA3
(PCINT2/AIN1) PA2
1
2
3
4
5
6
7
8
9
10
20
19
18
17
16
15
14
13
12
11
(PCINT8/TXD0/ADC5) PB0
(PCINT7/RXD0/ADC4) PA7
(PCINT6/OC1B/ADC3) PA6
(PCINT5/OC0B/ADC2) PA5
(PCINT4/T0/ADC1) PA4
(PCINT3/T1/SNS/ADC0) PA3
(PCINT2/AIN1) PA2
(PCINT1/AIN0) PA1
(PCINT0/AREF) PA0
GND
PB1 (ADC6/DI/SDA/RXD1/PCINT9)
PB2 (ADC7/DO/TXD1/PCINT10)
PB3 (ADC8/OC1A/PCINT11)
PC0 (ADC9/OC0A/XCK0/PCINT12)
PC1 (ADC10/ICP1/SCL/USCK/XCK1/PCINT13)
PC2 (ADC11/CLKO/INT0/PCINT14)
PC3 (RESET/dW/PCINT15)
PC4 (XTAL2/PCINT16)
PC5 (XTAL1/CLKI/PCINT17)
VCC
SOICATtiny1634 [DATASHEET] 3
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
1.1 Pin Descriptions
1.1.1 VCC
Supply voltage.
1.1.2 GND
Ground.
1.1.3 XTAL1
Input to the inverting amplifier of the oscillator and the internal clock circuit. This is an alternative pin configuration
of PC5.
1.1.4 XTAL2
Output from the inverting amplifier of the oscillator. Alternative pin configuration of PC4.
1.1.5 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock
is not running and provided the reset pin has not been disabled. The minimum pulse length is given in Table 24-5
on page 231. Shorter pulses are not guaranteed to generate a reset.
The reset pin can also be used as a (weak) I/O pin.
1.1.6 Port A (PA7:PA0)
This is an 8-bit, bi-directional I/O port with internal pull-up resistors (selected for each bit). Output buffers have the
following drive characteristics:
• PA7, PA4:PA0: Symmetrical, with standard sink and source capability
• PA6, PA5: Asymmetrical, with high sink and standard source capability
As inputs, port pins that are externally pulled low will source current provided that pull-up resistors are activated.
Port pins are tri-stated when a reset condition becomes active, even if the clock is not running.
This port has alternate pin functions to serve special features of the device. See “Alternate Functions of Port A” on
page 62.
1.1.7 Port B (PB3:PB0)
This is a 4-bit, bi-directional I/O port with internal pull-up resistors (selected for each bit).Output buffers have the
following drive characteristics:
• PB3: Asymmetrical, with high sink and standard source capability
• PB2:PB0: Symmetrical, with standard sink and source capability
As inputs, port pins that are externally pulled low will source current provided that pull-up resistors are activated.
Port pins are tri-stated when a reset condition becomes active, even if the clock is not running.
This port has alternate pin functions to serve special features of the device. See “Alternate Functions of Port B” on
page 65.
1.1.8 Port C (PC5:PC0)
This is a 6-bit, bi-directional I/O port with internal pull-up resistors (selected for each bit). Output buffers have the
following drive characteristics:ATtiny1634 [DATASHEET] 4
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
• PC5:PC1: Symmetrical, with standard sink and source capability
• PC0: Asymmetrical, with high sink and standard source capability
As inputs, port pins that are externally pulled low will source current provided that pull-up resistors are activated.
Port pins are tri-stated when a reset condition becomes active, even if the clock is not running.
This port has alternate pin functions to serve special features of the device. See “Alternate Functions of Port C” on
page 67.
2. Overview
ATtiny1634 is a low-power CMOS 8-bit microcontrollers based on the AVR enhanced RISC architecture. By executing
powerful instructions in a single clock cycle, the ATtiny1634 achieves throughputs approaching 1 MIPS per
MHz allowing the system designer to optimize power consumption versus processing speed.
Figure 2-1. Block Diagram
DEBUG
INTERFACE
CALIBRATED ULP
OSCILLATOR
WATCHDOG
TIMER
CALIBRATED
OSCILLATOR
TIMING AND
CONTROL
VCC RESET GND
8-BIT DATA BUS
CPU CORE
PROGRAM
MEMORY
(FLASH)
DATA
MEMORY
(SRAM)
POWER
SUPERVISION:
POR
BOD
RESET
ISP
INTERFACE
PORT A PORT B PORT C
VOLTAGE
REFERENCE
MULTIPLEXER ANALOG
COMPARATOR
ADC
TEMPERATURE
SENSOR
TWO-WIRE
INTERFACE
USART0
TOUCH
SENSING
EEPROM
ON-CHIP
DEBUGGER
PA[7:0] PB[3:0] PC[5:0]
8-BIT
TIMER/COUNTER
16-BIT
TIMER/COUNTER
USI
USART1ATtiny1634 [DATASHEET] 5
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
The AVR core combines a rich instruction set with 32 general purpose working registers. All 32 registers are
directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in a single
instruction, executed in one clock cycle. The resulting architecture is compact and code efficient while achieving
throughputs up to ten times faster than conventional CISC microcontrollers.
ATtiny1634 provides the following features:
• 16K bytes of in-system programmable Flash
• 1K bytes of SRAM data memory
• 256 bytes of EEPROM data memory
• 18 general purpose I/O lines
• 32 general purpose working registers
• An 8-bit timer/counter with two PWM channels
• A16-bit timer/counter with two PWM channels
• Internal and external interrupts
• A 10-bit ADC with 5 internal and 12 external channels
• An ultra-low power, programmable watchdog timer with internal oscillator
• Two programmable USART’s with start frame detection
• A slave Two-Wire Interface (TWI)
• A Universal Serial Interface (USI) with start condition detector
• A calibrated 8MHz oscillator
• A calibrated 32kHz, ultra low power oscillator
• Four software selectable power saving modes.
The device includes the following modes for saving power:
• Idle mode: stops the CPU while allowing the timer/counter, ADC, analog comparator, SPI, TWI, and interrupt
system to continue functioning
• ADC Noise Reduction mode: minimizes switching noise during ADC conversions by stopping the CPU and all
I/O modules except the ADC
• Power-down mode: registers keep their contents and all chip functions are disabled until the next interrupt or
hardware reset
• Standby mode: the oscillator is running while the rest of the device is sleeping, allowing very fast start-up
combined with low power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The Flash program memory
can be re-programmed in-system through a serial interface, by a conventional non-volatile memory
programmer or by an on-chip boot code, running on the AVR core.
The ATtiny1634 AVR is supported by a full suite of program and system development tools including: C compilers,
macro assemblers, program debugger/simulators and evaluation kits.ATtiny1634 [DATASHEET] 6
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
3. General Information
3.1 Resources
A comprehensive set of drivers, application notes, data sheets and descriptions on development tools are available
for download at http://www.atmel.com/avr.
3.2 Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These
code examples assume that the part specific header file is included before compilation. Be aware that not all C
compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent.
Please confirm with the C compiler documentation for more details.
For I/O Registers located in the extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI” instructions must
be replaced with instructions that allow access to extended I/O. Typically, this means “LDS” and “STS” combined
with “SBRS”, “SBRC”, “SBR”, and “CBR”. Note that not all AVR devices include an extended I/O map.
3.3 Capacitive Touch Sensing
Atmel QTouch Library provides a simple to use solution for touch sensitive interfaces on Atmel AVR microcontrollers.
The QTouch Library includes support for QTouch® and QMatrix® acquisition methods.
Touch sensing is easily added to any application by linking the QTouch Library and using the Application Programming
Interface (API) of the library to define the touch channels and sensors. The application then calls the API to
retrieve channel information and determine the state of the touch sensor.
The QTouch Library is free and can be downloaded from the Atmel website. For more information and details of
implementation, refer to the QTouch Library User Guide – also available from the Atmel website.
3.4 Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20
years at 85°C or 100 years at 25°C.
4. CPU Core
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct
program execution. The CPU must therefore be able to access memories, perform calculations, control
peripherals, and handle interrupts.ATtiny1634 [DATASHEET] 7
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
4.1 Architectural Overview
Figure 4-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with separate memories
and buses for program and data. Instructions in the Program memory are executed with a single level pipelining.
While one instruction is being executed, the next instruction is pre-fetched from the Program memory. This concept
enables instructions to be executed in every clock cycle. The Program memory is In-System Reprogrammable
Flash memory.
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle
access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands
are output from the Register File, the operation is executed, and the result is stored back in the Register File
– in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing –
enabling efficient address calculations. One of the these address pointers can also be used as an address pointer
for look up tables in Flash Program memory. These added function registers are the 16-bit X-, Y-, and Z-register,
described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single
register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated
to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, capable of directly addressing
the whole address space. Most AVR instructions have a single 16-bit word format but 32-bit wide instructions also
exist. The actual instruction set varies, as some devices only implement a part of the instruction set.
INTERRUPT
UNIT
STATUS AND
CONTROL
PROGRAM
MEMORY
(FLASH)
DATA
MEMORY
(SRAM)
PROGRAM
COUNTER
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
CONTROL
LINES
GENERAL
PURPOSE
REGISTERS
X
Y
Z
ALU
DIRECT ADDRESSING
INDIRECT ADDRESSING
8-BIT DATA BUSATtiny1634 [DATASHEET] 8
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack
is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total
SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines
or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data
SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in
the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have
priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the
priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other
I/O functions. The I/O memory can be accessed directly, or as the Data Space locations following those of the Register
File, 0x20 - 0x5F. In addition, the ATtiny1634 has Extended I/O Space from 0x60 - 0xFF in SRAM where only
the ST/STS/STD and LD/LDS/LDD instructions can be used.
4.2 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers.
Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an
immediate are executed. The ALU operations are divided into three main categories – arithmetic, logical, and bitfunctions.
Some implementations of the architecture also provide a powerful multiplier supporting both
signed/unsigned multiplication and fractional format. See external document “AVR Instruction Set” and “Instruction
Set Summary” on page 278 section for more information.
4.3 Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This
information can be used for altering program flow in order to perform conditional operations. Note that the Status
Register is updated after all ALU operations. This will in many cases remove the need for using the dedicated compare
instructions, resulting in faster and more compact code. See external document “AVR Instruction Set” and
“Instruction Set Summary” on page 278 section for more information.
The Status Register is neither automatically stored when entering an interrupt routine, nor restored when returning
from an interrupt. This must be handled by software.
4.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance
and flexibility, the following input/output schemes are supported by the Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 4-2 below shows the structure of the 32 general purpose working registers in the CPU.ATtiny1634 [DATASHEET] 9
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 4-2. General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single
cycle instructions.
As shown in Figure 4-2, each register is also assigned a Data memory address, mapping them directly into the first
32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory
organization provides great flexibility in access of the registers, as the X-, Y- and Z-pointer registers can be set to
index any register in the file.
4.4.1 The X-register, Y-register, and Z-register
The registers R26..R31 have added functions to their general purpose usage. These registers are 16-bit address
pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as
described in Figure 4-3 below.
7 0 Addr. Special Function
R0 0x00
R1 0x01
R2 0x02
R3 0x03
… ...
R12 0x0C
R13 0x0D
R14 0x0E
R15 0x0F
R16 0x10
R17 0x11
… ...
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High ByteATtiny1634 [DATASHEET] 10
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 4-3. The X-, Y-, and Z-registers
In the different addressing modes these address registers have functions as fixed displacement, automatic increment,
and automatic decrement (see the instruction set reference for details).
4.5 Stack Pointer
The stack is mainly used for storing temporary data, local variables and return addresses after interrupts and subroutine
calls. The Stack Pointer registers (SPH and SPL) always point to the top of the stack. Note that the stack
grows from higher memory locations to lower memory locations. This means that the PUSH instructions decreases
and the POP instruction increases the stack pointer value.
The stack pointer points to the area of data memory where subroutine and interrupt stacks are located. This stack
space must be defined by the program before any subroutine calls are executed or interrupts are enabled.
The pointer is decremented by one when data is put on the stack with the PUSH instruction, and incremented by
one when data is fetched with the POP instruction. It is decremented by two when the return address is put on the
stack by a subroutine call or a jump to an interrupt service routine, and incremented by two when data is fetched by
a return from subroutine (the RET instruction) or a return from interrupt service routine (the RETI instruction).
The AVR stack pointer is typically implemented as two 8-bit registers in the I/O register file. The width of the stack
pointer and the number of bits implemented is device dependent. In some AVR devices all data memory can be
addressed using SPL, only. In this case, the SPH register is not implemented.
The stack pointer must be set to point above the I/O register areas, the minimum value being the lowest address of
SRAM. See Table 5-2 on page 16.
4.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the
CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used.
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture
and the fast access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with
the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit.
15 0
X-register 7 XH 0 7 XL 0
R27 R26
15 0
Y-register 7 YH 0 7 YL 0
R29 R28
15 0
Z-register 7 ZH 0 7 ZL 0
R31 R30ATtiny1634 [DATASHEET] 11
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 4-4. The Parallel Instruction Fetches and Instruction Executions
Figure 4-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using
two register operands is executed, and the result is stored back to the destination register.
Figure 4-5. Single Cycle ALU Operation
4.7 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a
separate Program Vector in the Program memory space. All interrupts are assigned individual enable bits which
must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the
interrupt.
The lowest addresses in the Program memory space are by default defined as the Reset and Interrupt Vectors.
The complete list of vectors is shown in “Interrupts” on page 47. The list also determines the priority levels of the
different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next
is INT0 – the External Interrupt Request 0.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software
can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current
interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. For
these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt
handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing
a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding
interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the
flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit
is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is
set, and will then be executed by order of priority.
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPUATtiny1634 [DATASHEET] 12
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily
have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will
not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction
before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when
returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be
executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example
shows how this can be used to avoid interrupts during the timed EEPROM write sequence.
Note: See “Code Examples” on page 6.
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending
interrupts, as shown in the following example.
Note: See “Code Examples” on page 6.
4.7.1 Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock
cycles the Program Vector address for the actual interrupt handling routine is executed. During this four clock cycle
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1< 1MHz 12 – 22 pF
XTAL2
XTAL1
GND
C2
C1ATtiny1634 [DATASHEET] 29
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
The ripple counter that implements the prescaler runs at the frequency of the undivided clock, which may be faster
than the CPU's clock frequency. Hence, it is not possible to determine the state of the prescaler - even if it were
readable, and the exact time it takes to switch from one clock division to another cannot be exactly predicted.
From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2*T2 before the new clock frequency
is active. In this interval, 2 active clock edges are produced. Here, T1 is the previous clock period, and T2
is the period corresponding to the new prescaler setting.
6.4 Clock Output Buffer
The device can output the system clock on the CLKO pin. To enable the output, the CKOUT_IO bit has to be programmed.
The CKOUT fuse determines the initial value of the CKOUT_IO bit that is loaded to the CLKSR register
when the device is powered up or has been reset. The clock output can be switched at run-time by setting the
CKOUT_IO bit in CLKSR as described in chapter “CLKSR – Clock Setting Register” on page 29.
This mode is suitable when the chip clock is used to drive other circuits on the system. Note that the clock will not
be output during reset and that the normal operation of the I/O pin will be overridden when the fuse is programmed.
Any clock source, including the internal oscillators, can be selected when the clock is output on CLKO. If the System
Clock Prescaler is used, it is the divided system clock that is output.
6.5 Register Description
6.5.1 CLKSR – Clock Setting Register
• Bit 7 – OSCRDY: Oscillator Ready
This bit is set when oscillator time-out is complete. When OSCRDY is set the oscillator is stable and the clock
source can be changed safely.
• Bit 6 – CSTR: Clock Select Trigger
This bit triggers the clock selection. It can be used to enable the oscillator in advance and select the clock source,
before the oscillator is stable.
If CSTR is set at the same time as the CKSEL bits are written, the contents are directly copied to the CKSEL register
and the system clock is immediately switched.
If CKSEL bits are written without setting CSTR, the oscillator selected by the CKSEL bits is enabled, but the system
clock is not switched yet.
• Bit 5 – CKOUT_IO: Clock Output
This bit enables the clock output buffer. The CKOUT fuse determines the initial value of the CKOUT_IO bit that is
loaded to the CLKSR register when the device is powered up or has been reset
• Bit 4 – SUT: Start-Up Time
The SUT and CKSEL bits define the start-up time of the device, as shown in Table 6-2, below. The initial value of
the SUT bit is determined by the SUT fuse. The SUT fuse is loaded to the SUT bit when the device is powered up
or has been reset.
Bit 7 6 5 4 3 2 1 0
0x32 (0x52) OSCRDY CSTR CKOUT_IO SUT CKSEL3 CKSEL2 CKSEL1 CKSEL0 CLKSR
Read/Write R W R R R/W R/W R/W R/W
Initial Value 0 0 0 See Bit DescriptionATtiny1634 [DATASHEET] 30
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note: 1. Device start-up time from power-down sleep mode.
2. When BOD has been disabled by software, the wake-up time from sleep mode will be approximately 60µs to
ensure the BOD is working correctly before MCU continues executing code.
3. Device start-up time after reset.
4. The device is shipped with this option selected.
5. This option is not suitable for use with crystals.
6. This option should not be used when operating close to the maximum frequency of the device, and only if frequency
stability at start-up is not important for the application.
7. This option is intended for use with ceramic resonators and will ensure frequency stability at start-up. It can also be
used with crystals when not operating close to the maximum frequency of the device, and if frequency stability at
start-up is not important for the application.
• Bits 3:0 – CKSEL[3:0]: Clock Select Bits
These bits select the clock source of the system clock and can be written at run-time. The clock system ensures
glitch free switching of the clock source. CKSEL fuses determine the initial value of the CKSEL bits when the
device is powered up or reset.
The clock alternatives are shown in Table 6-3 below.
Table 6-2. Device Start-up Times
SUT CKSEL Clock From Power-Down (1)(2) From Reset (3)
0 (4)
0000 External 6 CK 22 CK + 16ms
0010 (4) Internal 8MHz 6 CK 20 CK + 16ms
0100 Internal 32kHz 6 CK 22 CK + 16ms
0001
0011
0101 ... 0111
Reserved
1XX0 Ceramic resonator (5) 258 CK (6) 274 CK + 16ms
1XX1 Crystal oscillator 16K CK 16K CK + 16 ms
1
0000 ... 0111
1XX1 Reserved
1XX0 Ceramic resonator 1K CK (7) 1K CK +16ms
Table 6-3. Device Clocking Options
CKSEL[3:0] (1) Frequency Device Clocking Option
0000 Any External Clock (see page 26)
0010 8MHz Calibrated Internal 8MHz Oscillator (see page 27) (2)
0100 32kHz Internal 32kHz Ultra Low Power (ULP) Oscillator (see page 27)
00X1
0101 ... 0111 — Reserved
100X 0.4...0.9MHz
Crystal Oscillator / Ceramic Resonator (see page 27)
101X 0.9...3MHz
110X 3...8MHz
111X > 8MHzATtiny1634 [DATASHEET] 31
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note: 1. For all fuses “1” means unprogrammed and “0” means programmed.
2. This is the default setting. The device is shipped with this fuse combination.
To avoid unintentional switching of clock source, a protected change sequence must be followed to change the
CKSEL bits, as follows:
1. Write the signature for change enable of protected I/O register to register CCP.
2. Within four instruction cycles, write the CKSEL bits with the desired value.
6.5.2 CLKPR – Clock Prescale Register
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 3:0 – CLKPS[3:0]: Clock Prescaler Select Bits 3 - 0
These bits define the division factor between the selected clock source and the internal system clock. These bits
can be written run-time to vary the clock frequency to suit the application requirements. As the divider divides the
master clock input to the MCU, the speed of all synchronous peripherals is reduced when a division factor is used.
The division factors are given in Table 6-4 on page 31.
To avoid unintentional changes of clock frequency, a protected change sequence must be followed to change the
CLKPS bits:
1. Write the signature for change enable of protected I/O register to register CCP.
2. Within four instruction cycles, write the desired value to CLKPS bits.
Interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted.
Bit 7 6 5 4 3 2 1 0
0x33 (0x53) – – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 CLKPR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 See Bit Description
Table 6-4. Clock Prescaler Select
CLKPS3 CLKPS2 CLKPS1 CLKPS0 Clock Division Factor
0 0 0 0 1 (1)
0001 2
0010 4
0 0 1 1 8 (2)
0 1 0 0 16
0 1 0 1 32
0 1 1 0 64
0 1 1 1 128
1 0 0 0 256ATtiny1634 [DATASHEET] 32
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note: 1. This is the initial value when CKDIV8 fuse has been unprogrammed.
2. This is the initial value when CKDIV8 fuse has been programmed. The device is shipped with the CKDIV8 Fuse
programmed.
The initial value of clock prescaler bits is determined by the CKDIV8 fuse (see Table 22-5 on page 210). When
CKDIV8 is unprogrammed, the system clock prescaler is set to one and, when programmed, to eight. Any value
can be written to the CLKPS bits regardless of the CKDIV8 fuse bit setting.
When CKDIV8 is programmed the initial value of CLKPS bits give a clock division factor of eight at start up. This is
useful when the selected clock source has a higher frequency than allowed under present operating conditions.
See “Speed” on page 229.
6.5.3 OSCCAL0 – Oscillator Calibration Register
Although temperature slope and frequency are in part controlled by registers OSCTCAL0A and OSCTCAL0B it is
possible to replace factory calibration by simply writing to this register alone. Optimal accuracy is achieved when
OSCCAL0, OSCTAL0A and OSCTCAL0B are calibrated together.
• Bits 7:0 – CAL0[7:0]: Oscillator Calibration Value
The oscillator calibration register is used to trim the internal 8MHz oscillator and to remove process variations from
the oscillator frequency. A pre-programmed calibration value is automatically written to this register during chip
reset, giving the factory calibrated frequency specified in Table 24-2 on page 230.
The application software can write this register to change the oscillator frequency. The oscillator can be calibrated
to frequencies specified in Table 24-2 on page 230. Calibration outside that range is not guaranteed.
The lowest oscillator frequency is reached by programming these bits to zero. Increasing the register value
increases the oscillator frequency. A typical frequency response curve is shown in “Calibrated Oscillator Frequency
(Nominal = 8MHz) vs. OSCCAL Value” on page 273.
Note that this oscillator is used to time EEPROM and Flash write accesses, and write times will be affected accordingly.
Do not calibrate to more than 8.8MHz if EEPROM or Flash is to be written. Otherwise, the EEPROM or Flash
write may fail.
To ensure stable operation of the MCU the calibration value should be changed in small steps. A step change in
frequency of more than 2% from one cycle to the next can lead to unpredictable behavior. Also, the difference
between two consecutive register values should not exceed 0x20. If these limits are exceeded the MCU must be
kept in reset during changes to clock frequency.
1001
Reserved
1010
1011
1100
1101
1110
1111
Table 6-4. Clock Prescaler Select (Continued)
CLKPS3 CLKPS2 CLKPS1 CLKPS0 Clock Division Factor
Bit 7 6 5 4 3 2 1 0
(0x63) CAL07 CAL06 CAL05 CAL04 CAL03 CAL02 CAL01 CAL00 OSCCAL0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value Device Specific Calibration ValueATtiny1634 [DATASHEET] 33
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
6.5.4 OSCTCAL0A – Oscillator Temperature Calibration Register A
This register is used for changing the temperature slope and frequency of the internal 8MHz oscillator. A pre-programmed
calibration value is automatically written to this register during chip reset, giving the factory calibrated
frequency specified in Table 24-2 on page 230.
This register need not be updated if factory defaults in OSCCAL0 are overwritten although optimal accuracy is
achieved when OSCCAL0, OSCTAL0A and OSCTCAL0B are calibrated together.
• Bit 7 – Sign of Oscillator Temperature Calibration Value
This is the sign bit of the calibration data.
• Bits 6:0 – Oscillator Temperature Calibration Value
These bits contain the numerical value of the calibration data.
6.5.5 OSCTCAL0B – Oscillator Temperature Calibration Register B
A pre-programmed calibration value is automatically written to this register during chip reset, giving the factory calibrated
frequency specified in Table 24-2 on page 230.
This register need not be updated if factory defaults in OSCCAL0 are overwritten although optimal accuracy is
achieved when OSCCAL0, OSCTAL0A and OSCTCAL0B are calibrated together.
• Bit 7 – Temperature Compensation Enable
When this bit is set the contents of registers OSCTCAL0A and OSCTCAL0B are used for calibration. When this bit
is cleared the temperature compensation hardware is disabled and registers OSCTCAL0A and OSCTCAL0B have
no effect on the frequency of the internal 8MHz oscillator.
Note that temperature compensation has a large effect on oscillator frequency and, hence, when enabled or disabled
the OSCCAL0 register must also be adjusted to compensate for this effect.
• Bits 6:0 – Temperature Compensation Step Adjust
These bits control the step size of the calibration data in OSCTCAL0A. The largest step size is achieved for 0x00
and smallest step size for 0x7F.
6.5.6 OSCCAL1 – Oscillator Calibration Register
• Bits 7:2 – Res: Reserved Bits
These bits are reserved and will always read zero.
Bit 7 6 5 4 3 2 1 0
(0x64) Oscillator Temperature Calibration Data OSCTCAL0A
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value Device Specific Calibration Value
Bit 7 6 5 4 3 2 1 0
(0x65) Oscillator Temperature Calibration Data OSCTCAL0B
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value Device Specific Calibration Value
Bit 7 6 5 4 3 2 1 0
(0x66) – – – – – – CAL11 CAL10 OSCCAL1
Read/Write R R R R R R R/W R/W
Initial Value Device Specific Calibration ValueATtiny1634 [DATASHEET] 34
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
• Bits 1:0 – CAL1[1:0]: Oscillator Calibration Value
The oscillator calibration register is used to trim the internal 32kHz oscillator and to remove process variations from
the oscillator frequency. A pre-programmed calibration value is automatically written to this register during chip
reset, giving the factory calibrated frequency as specified in Table 24-3 on page 231.
The application software can write this register to change the oscillator frequency. The oscillator can be calibrated
to frequencies as specified in Table 24-3 on page 231. Calibration outside that range is not guaranteed.
The lowest oscillator frequency is reached by programming these bits to zero. Increasing the register value
increases the oscillator frequency.
7. Power Management and Sleep Modes
The high performance and industry leading code efficiency makes the AVR microcontrollers an ideal choise for low
power applications. In addition, sleep modes enable the application to shut down unused modules in the MCU,
thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to
the application’s requirements.
7.1 Sleep Modes
Figure 6-1 on page 25 presents the different clock systems and their distribution in ATtiny1634. The figure is helpful
in selecting an appropriate sleep mode. Table 7-1 shows the different sleep modes and the sources that may be
used for wake up.
Note: 1. Start frame detection, only.
2. Start condition, only.
3. Address match interrupt, only.
4. For INT0 level interrupt, only.
To enter a sleep mode, the SE bit in MCUCR must be set and a SLEEP instruction must be executed. The SMn
bits in MCUCR select which sleep mode will be activated by the SLEEP instruction. See Table 7-2 on page 37 for
a summary.
If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for
four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction
following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from
sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector.
Table 7-1. Active Clock Domains and Wake-up Sources in Different Sleep Modes
Sleep Mode
Oscillators Active Clock Domains Wake-up Sources Main Clock Source Enabled clkCPU clkFLASH clkIO clkADC Watchdog Interrupt INT0 and Pin Change SPM/EEPROM Ready Interrupt ADC Interrupt USART USI
TWI Slave
Other I/O
Idle X X X X X X X X X X X
ADC Noise
Reduction X X X X (4) X X X (1) X (2) X (3)
Standby X X X (4) X (1) X (2) X (3)
Power-down X X (4) X (1) X (2) X (3)ATtiny1634 [DATASHEET] 35
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note that if a level triggered interrupt is used for wake-up the changed level must be held for some time to wake up
the MCU (and for the MCU to enter the interrupt service routine). See “External Interrupts” on page 48 for details.
7.1.1 Idle Mode
This sleep mode basically halts clkCPU and clkFLASH, while allowing other clocks to run. In Idle Mode, the CPU is
stopped but the following peripherals continue to operate:
• Watchdog and interrupt system
• Analog comparator, and ADC
• USART, TWI, and timer/counters
Idle mode allows the MCU to wake up from external triggered interrupts as well as internal ones, such as Timer
Overflow. If wake-up from the analog comparator interrupt is not required, the analog comparator can be powered
down by setting the ACD bit in ACSRA. See “ACSRA – Analog Comparator Control and Status Register” on page
182. This will reduce power consumption in Idle mode.
If the ADC is enabled, a conversion starts automatically when this mode is entered.
7.1.2 ADC Noise Reduction Mode
This sleep mode halts clkI/O, clkCPU, and clkFLASH, while allowing other clocks to run. In ADC Noise Reduction
mode, the CPU is stopped but the following peripherals continue to operate:
• Watchdog (if enabled), and external interrupts
• ADC
• USART start frame detector, and TWI
This improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is
enabled, a conversion starts automatically when this mode is entered.
The following events can wake up the MCU:
• Watchdog reset, external reset, and brown-out reset
• External level interrupt on INT0, and pin change interrupt
• ADC conversion complete interrupt, and SPM/EEPROM ready interrupt
• USI start condition, USART start frame detection, and TWI address match
7.1.3 Power-Down Mode
This sleep mode halts all generated clocks, allowing operation of asynchronous modules, only. In Power-down
Mode the oscillator is stopped, while the following peripherals continue to operate:
• Watchdog (if enabled), external interrupts
The following events can wake up the MCU:
• Watchdog reset, external reset, and brown-out reset
• External level interrupt on INT0, and pin change interrupt
• USI start condition, USART start frame detection, and TWI address matchATtiny1634 [DATASHEET] 36
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
7.1.4 Standby Mode
Standby Mode is identical to power-down, with the exception that the oscillator is kept running. From Standby
mode, the device wakes up in six clock cycles.
7.2 Power Reduction Register
The Power Reduction Register (PRR), see “PRR – Power Reduction Register” on page 38, provides a method to
reduce power consumption by stopping the clock to individual peripherals. When the clock for a peripheral is
stopped then:
• The current state of the peripheral is frozen.
• The associated registers can not be read or written.
• Resources used by the peripheral will remain occupied.
The peripheral should in most cases be disabled before stopping the clock. Clearing the PRR bit wakes up the
peripheral and puts it in the same state as before shutdown.
Peripheral shutdown can be used in Idle mode and Active mode to significantly reduce the overall power consumption.
In all other sleep modes, the clock is already stopped.
7.3 Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR controlled system.
In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as
few as possible of the device’s functions are operating. All functions not needed should be disabled. In particular,
the following modules may need special consideration when trying to achieve the lowest possible power
consumption.
7.3.1 Analog to Digital Converter
If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be disabled before entering
any sleep mode. When the ADC is turned off and on again, the next conversion will be an extended conversion.
See “Analog to Digital Converter” on page 185 for details on ADC operation.
7.3.2 Analog Comparator
When entering Idle mode, the Analog Comparator should be disabled if not used. When entering ADC Noise
Reduction mode, the Analog Comparator should be disabled. In the other sleep modes, the Analog Comparator is
automatically disabled. However, if the Analog Comparator is set up to use the Internal Voltage Reference as
input, the Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will
be enabled, independent of sleep mode. See “Analog Comparator” on page 181 for details on how to configure the
Analog Comparator.
7.3.3 Brown-out Detector
If the Brown-out Detector is not needed in the application, this module should be turned off. If the Brown-out Detector
is enabled by the BODPD Fuses, it will be enabled in all sleep modes, and hence, always consume power. In
the deeper sleep modes, this will contribute significantly to the total current consumption. If the Brown-out Detector
is needed in the application, this module can also be set to Sampled BOD mode to save power. See “Brown-Out
Detection” on page 41 for details on how to configure the Brown-out Detector.
7.3.4 Internal Voltage Reference
The Internal Voltage Reference will be enabled when needed by the Brown-out Detection, the Analog Comparator
or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be
disabled and it will not be consuming power. When turned on again, the user must allow the reference to start upATtiny1634 [DATASHEET] 37
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
before the output is used. If the reference is kept on in sleep mode, the output can be used immediately. See Internal
Bandgap Reference in Table 24-5 on page 231 for details on the start-up time.
7.3.5 Watchdog Timer
If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is
enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this
will contribute to the total current consumption. See “Watchdog Timer” on page 43 for details on how to configure
the Watchdog Timer.
7.3.6 Port Pins
When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing
is then to ensure that no pins drive resistive loads. In sleep modes where both the I/O clock (clkI/O) and the ADC
clock (clkADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed
by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and
it will then be enabled. See the section “Digital Input Enable and Sleep Modes” on page 58 for details on which pins
are enabled. If the input buffer is enabled and the input signal is left floating or has an analog signal level close to
VCC/2, the input buffer will use excessive power.
For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VCC/2
on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to
the Digital Input Disable Register (DIDR0). See “DIDR0 – Digital Input Disable Register 0” on page 200 for details.
7.3.7 On-chip Debug System
If the On-chip debug system is enabled by the DWEN Fuse and the chip enters sleep mode, the main clock source
is enabled and hence always consumes power. In the deeper sleep modes, this will contribute significantly to the
total current consumption.
7.4 Register Description
7.4.1 MCUCR – MCU Control Register
The MCU Control Register contains control bits for power management.
• Bits 7, 3:2 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 6:5 – SM[1:0]: Sleep Mode Select Bits 1 and 0
These bits select between available sleep modes, as shown in Table 7-2.
Bit 7 6 5 4 3 2 1 0
0x36 (0x56) – SM1 SM0 SE – – ISC01 ISC00 MCUCR
Read/Write R R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 7-2. Sleep Mode Select
SM1 SM0 Sleep Mode
0 0 Idle
0 1 ADC Noise Reduction
1 0 Power-down
1 1 Standby(1)ATtiny1634 [DATASHEET] 38
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note: 1. Only recommended with external crystal or resonator selected as clock source
• Bit 4 – SE: Sleep Enable
The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed.
To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to
write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately
after waking up.
7.4.2 PRR – Power Reduction Register
The Power Reduction Register provides a method to reduce power consumption by allowing peripheral clock signals
to be disabled.
• Bit 7 – Res: Reserved Bit
This bit is a reserved bit and will always read zero.
• Bit 6 – PRTWI: Power Reduction Two-Wire Interface
Writing a logic one to this bit shuts down the Two-Wire Interface module.
• Bit 5 – PRTIM1: Power Reduction Timer/Counter1
Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1 is enabled, operation
will continue like before the shutdown.
• Bit 4 – PRTIM0: Power Reduction Timer/Counter0
Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation
will continue like before the shutdown.
• Bit 3 – PRUSI: Power Reduction USI
Writing a logic one to this bit shuts down the USI by stopping the clock to the module. When waking up the USI
again, the USI should be re initialized to ensure proper operation.
• Bit 2 – PRUSART1: Power Reduction USART1
Writing a logic one to this bit shuts down the USART1 module. When the USART1 is enabled, operation will continue
like before the shutdown.
• Bit 1 – PRUSART0: Power Reduction USART0
Writing a logic one to this bit shuts down the USART0 module. When the USART0 is enabled, operation will continue
like before the shutdown.
• Bit 0 – PRADC: Power Reduction ADC
Writing a logic one to this bit shuts down the ADC. The ADC must be disabled before shut down. The analog comparator
cannot be used when the ADC is shut down.
Bit 7 6 5 4 3 2 1 0
0x34 (0x54) – PRTWI PRTIM1 PRTIM0 PRUSI PRUSART1 PRUSART0 PRADC PRR
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny1634 [DATASHEET] 39
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
8. System Control and Reset
8.1 Resetting the AVR
During reset, all I/O registers are set to their initial values, and the program starts execution from the Reset Vector.
The instruction placed at the Reset Vector should be a JMP (two-word, direct jump) instruction to the reset handling
routine, although other one- or two-word jump instructions can be used. If the program never enables an
interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations.
The circuit diagram in Figure 8-1 shows the reset logic. Electrical parameters of the reset circuitry are defined in
section “System and Reset” on page 231.
Figure 8-1. Reset Logic
The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not
require any clock source to be running.
After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the
power to reach a stable level before normal operation starts.
8.2 Reset Sources
The ATtiny1634 has four sources of reset:
• Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset threshold (VPOT)
• External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum
pulse length when RESET function is enabled
• Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled
• Brown-out Reset. The MCU is reset when the supply voltage VCC is below the Brown-out Reset threshold (VBOT)
and the Brown-out Detector is enabled
8.2.1 Power-on Reset
A Power-on Reset (POR) pulse is generated by an on-chip detection circuit. The detection level is defined in “System
and Reset” on page 231. The POR is activated whenever VCC is below the detection level. The POR circuit can
be used to trigger the Start-up Reset, as well as to detect a failure in supply voltage.
A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the Power-on Reset
threshold voltage invokes the delay counter, which determines how long the device is kept in reset after VCC rise.
The reset signal is activated again, without any delay, when VCC decreases below the detection level.
DATA BUS
RESET FLAG REGISTER RESET FLAG REGISTER
(RSTFLR) (RSTFLR)
POWER-ON POWER-ON RESET CIRCUIT RESET CIRCUIT
PULL-UP PULL-UP
RESISTOR RESISTOR
BODLEVEL2...0 BODLEVEL2...0
VCC
SPIKE
FILTER RESET
EXTERNAL EXTERNAL
RESET CIRCUIT RESET CIRCUIT
BROWN OUT BROWN OUT RESET CIRCUIT RESET CIRCUIT
RSTDISBL RSTDISBL
WATCHDOG WATCHDOG
TIMER
DELAY
COUNTERS COUNTERS
S
R
Q
WATCHDOG WATCHDOG OSCILLATOR OSCILLATOR
CLOCK GENERATOR GENERATOR
BORF
PORF
EXTRF
WDRF
INTERNAL INTERNAL
RESET
CK
TIMEOUT TIMEOUT
COUNTER RESET COUNTER RESETATtiny1634 [DATASHEET] 40
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 8-2. MCU Start-up, RESET Tied to VCC
Figure 8-3. MCU Start-up, RESET Extended Externally
8.2.2 External Reset
An External Reset is generated by a low level on the RESET pin if enabled. Reset pulses longer than the minimum
pulse width (see section “System and Reset” on page 231) will generate a reset, even if the clock is not running.
Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage
– VRST – on its positive edge, the delay counter starts the MCU after the time-out period – tTOUT – has expired.
External reset is ignored during Power-on start-up count. After Power-on reset the internal reset is extended only if
RESET pin is low when the initial Power-on delay count is complete. See Figure 8-2 and Figure 8-3.
Figure 8-4. External Reset During Operation
V
TIME-OUT
RESET
RESET
TOUT
INTERNAL
t
VPOT
VRST
CC
V
TIME-OUT
TOUT
TOUT
INTERNAL
CC
t
VPOT
VRST
> t
RESET
RESET
CCATtiny1634 [DATASHEET] 41
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
8.2.3 Watchdog Reset
When the Watchdog times out, it will generate a short reset pulse. On the falling edge of this pulse, the delay timer
starts counting the time-out period tTOUT. See page 43 for details on operation of the Watchdog Timer and Table
24-5 on page 231 for details on reset time-out.
Figure 8-5. Watchdog Reset During Operation
8.2.4 Brown-Out Detection
The Brown-Out Detection (BOD) circuit monitors that the VCC level is kept above a configurable trigger level, VBOT.
When the BOD is enabled, a BOD reset will be given when VCC falls and remains below the trigger level for the
length of the detection time, tBOD. The reset is kept active until VCC again rises above the trigger level.
Figure 8-6. Brown-out Detection reset.
The BOD circuit will not detect a drop in VCC unless the voltage stays below the trigger level for the detection time,
tBOD (see “System and Reset” on page 231).
The BOD circuit has three modes of operation:
• Disabled: In this mode of operation VCC is not monitored and, hence, it is recommended only for applications
where the power supply remains stable.
CK
CC
VCC
TIME-OUT
INTERNAL
RESET
VBOTVBOT+
t
TOUT
t
BODATtiny1634 [DATASHEET] 42
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
• Enabled: In this mode the VCC level is continuously monitored. If VCC drops below VBOT for at least tBOD a
brown-out reset will be generated.
• Sampled: In this mode the VCC level is sampled on each negative edge of a 1kHz clock that has been derived
from the 32kHz ULP oscillator. Between each sample the BOD is turned off. Compared to the mode where BOD
is constantly enabled this mode of operation reduces power consumption but fails to detect drops in VCC
between two positive edges of the 1kHz clock. When a brown-out is detected in this mode, the BOD circuit is set
to enabled mode to ensure that the device is kept in reset until VCC has risen above VBOT . The BOD will return
to sampled mode after reset has been released and the fuses have been read in.
The BOD mode of operation is selected using BODACT and BODPD fuse bits. The BODACT fuse bits determine
how the BOD operates in active and idle mode, as shown in Table 8-1.
The BODPD fuse bits determine the mode of operation in all sleep modes except idle mode, as shown in Table 8-
2.
See “Fuse Bits” on page 209.
8.3 Internal Voltage Reference
ATtiny1634 features an internal bandgap reference. This reference is used for Brown-out Detection, and it can be
used as an input to the Analog Comparator or the ADC. The bandgap voltage varies with supply voltage and
temperature.
8.3.1 Voltage Reference Enable Signals and Start-up Time
The voltage reference has a start-up time that may influence the way it should be used. The start-up time is given
in “System and Reset” on page 231. To save power, the reference is not always turned on. The reference is on
during the following situations:
1. When the BOD is enabled (see “Brown-Out Detection” on page 41).
2. When the internal reference is connected to the Analog Comparator (by setting the ACBG bit in ACSRA).
3. When the ADC is enabled.
Thus, when the BOD is not enabled, after setting the ACBG bit or enabling the ADC, the user must always allow
the reference to start up before the output from the Analog Comparator or ADC is used. To reduce power conTable
8-1. Setting BOD Mode of Operation in Active and Idle Modes
BODACT1 BODACT0 Mode of Operation
0 0 Reserved
0 1 Sampled
1 0 Enabled
1 1 Disabled
Table 8-2. Setting BOD Mode of Operation in Sleep Modes Other Than Idle
BODPD1 BODPD0 Mode of Operation
0 0 Reserved
0 1 Sampled
1 0 Enabled
1 1 DisabledATtiny1634 [DATASHEET] 43
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
sumption in Power-down mode, the user can avoid the three conditions above to ensure that the reference is
turned off before entering Power-down mode.
8.4 Watchdog Timer
The Watchdog Timer is clocked from the internal 32kHz ultra low power oscillator (see page 27). By controlling the
Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as shown in Table 8-5 on page 46. The
WDR – Watchdog Reset – instruction resets the Watchdog Timer. The Watchdog Timer is also reset when it is disabled
and when a Chip Reset occurs. Ten different clock cycle periods can be selected to determine the reset
period. If the reset period expires without another Watchdog Reset, the ATtiny1634 resets and executes from the
Reset Vector. For timing details on the Watchdog Reset, refer to Table 8-5 on page 46.
The Wathdog Timer can also be configured to generate an interrupt instead of a reset. This can be very helpful
when using the Watchdog to wake-up from Power-down.
To prevent unintentional disabling of the Watchdog or unintentional change of time-out period, two different safety
levels are selected by the fuse WDTON as shown in Table 8-3 See “Timed Sequences for Changing the Configuration
of the Watchdog Timer” on page 43 for details.
Figure 8-7. Watchdog Timer
8.4.1 Timed Sequences for Changing the Configuration of the Watchdog Timer
The sequence for changing configuration differs slightly between the two safety levels. Separate procedures are
described for each level.
• Safety Level 1
In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the WDE bit to one without
any restriction. A timed sequence is needed when disabling an enabled Watchdog Timer. To disable an
enabled Watchdog Timer, the following procedure must be followed:
Table 8-3. WDT Configuration as a Function of the Fuse Settings of WDTON
WDTON
Safety
Level
WDT Initial
State
How to Disable the
WDT
How to Change Timeout
Unprogrammed 1 Disabled Timed sequence No limitations
Programmed 2 Enabled Always enabled Timed sequence OSC/512 OSC/1K OSC/2K OSC/4K OSC/8K OSC/16K OSC/32K OSC/64K OSC/128K OSC/256K
MCU RESET
WATCHDOG
PRESCALER
32 kHz
ULP OSCILLATOR
WATCHDOG
RESET
WDP0
WDP1
WDP2
WDP3
WDE
MUXATtiny1634 [DATASHEET] 44
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
a. Write the signature for change enable of protected I/O registers to register CCP
b. Within four instruction cycles, in the same operation, write WDE and WDP bits
• Safety Level 2
In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read as one. A timed
sequence is needed when changing the Watchdog Time-out period. To change the Watchdog Time-out, the
following procedure must be followed:
a. Write the signature for change enable of protected I/O registers to register CCP
b. Within four instruction cycles, write the WDP bit. The value written to WDE is irrelevant
8.4.2 Code Examples
The following code example shows how to turn off the WDT. The example assumes that interrupts are controlled
(e.g., by disabling interrupts globally) so that no interrupts will occur during execution of these functions.
Note: See “Code Examples” on page 6.
8.5 Register Description
8.5.1 MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU Reset.
• Bits 7:4 – Res: Reserved Bits
These bits are reserved bits in the ATtiny1634 and will always read as zero.
• Bit 3 – WDRF: Watchdog Reset Flag
This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the
flag.
Assembly Code Example
WDT_off:
wdr
; Clear WDRF in RSTFLR
in r16, RSTFLR
andi r16, ~(1< ; Address 0x0038
...ATtiny1634 [DATASHEET] 49
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
The pin change interrupts trigger as follows:
• Pin Change Interrupt 0 (PCI0): triggers if any enabled PCINT[7:0] pin toggles
• Pin Change Interrupt 1 (PCI1): triggers if any enabled PCINT[11:8] pin toggles
• Pin Change Interrupt 2 (PCI2): triggers if any enabled PCINT[17:12] pin toggles
Registers PCMSK0, PCMSK1, and PCMSK2 control which pins contribute to the pin change interrupts.
Pin change interrupts on PCINT[17:0] are detected asynchronously, which means that these interrupts can be
used for waking the part also from sleep modes other than Idle mode.
External interrupt INT0 can be triggered by a falling or rising edge, or a low level. See “MCUCR – MCU Control
Register” on page 37. When INT0 is enabled and configured as level triggered, the interrupt will trigger as long as
the pin is held low.
Note that recognition of falling or rising edge interrupts on INT0 requires the presence of an I/O clock, as described
in “Clock System” on page 24.
9.2.1 Low Level Interrupt
A low level interrupt on INT0 is detected asynchronously. This means that the interrupt source can be used for
waking the part also from sleep modes other than Idle (the I/O clock is halted in all sleep modes except Idle).
Note that if a level triggered interrupt is used for wake-up from Power-down, the required level must be held long
enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of
the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined by the
SUT and CKSEL fuses, as described in “Clock System” on page 24.
If the low level on the interrupt pin is removed before the device has woken up then program execution will not be
diverted to the interrupt service routine but continue from the instruction following the SLEEP command.
9.2.2 Pin Change Interrupt Timing
A timing example of a pin change interrupt is shown in Figure 9-1.ATtiny1634 [DATASHEET] 50
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 9-1. Timing of pin change interrupts
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
PCINT(0)
pin_sync
pcint_syn pin_lat
D Q
LE
pcint_setflag
PCIF
clk
clk PCINT(0) in PCMSK(x)
pcint_in_(0) 0
xATtiny1634 [DATASHEET] 51
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
9.3 Register Description
9.3.1 MCUCR – MCU Control Register
• Bits 1:0 – ISC0[1:0]: Interrupt Sense Control 0 Bit 1 and Bit 0
External Interrupt 0 is triggered by activity on pin INT0, provided that the SREG I-flag and the corresponding interrupt
mask are set. The conditions required to trigger the interrupt are defined in Table 9-2.
Note: 1. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction
to generate an interrupt.
2. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last
longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt.
9.3.2 GIMSK – General Interrupt Mask Register
• Bits 7, 2:0 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 6 – INT0: External Interrupt Request 0 Enable
The external interrupt for pin INT0 is enabled when this bit and the I-bit in the Status Register (SREG) are set. The
trigger conditions are set with the ISC0n bits.
Activity on the pin will cause an interrupt request even if INT0 has been configured as an output.
• Bit 5 – PCIE2: Pin Change Interrupt Enable 2
When this bit and the I-bit of SREG are set the Pin Change Interrupt 2 is enabled. Any change on an enabled
PCINT[17:12] pin will cause a PCINT2 interrupt. See Table 9-1 on page 47.
Each pin can be individually enabled. See “PCMSK2 – Pin Change Mask Register 2” on page 52.
• Bit 4 – PCIE1: Pin Change Interrupt Enable 1
When this bit and the I-bit of SREG are set the Pin Change Interrupt 1 is enabled. Any change on an enabled
PCINT[11:8] pin will cause a PCINT1 interrupt. See Table 9-1 on page 47.
Each pin can be individually enabled. See “PCMSK1 – Pin Change Mask Register 1” on page 53.
Bit 7 6 5 4 3 2 1 0
0x36 (0x56) – SM1 SM0 SE – – ISC01 ISC00 MCUCR
Read/Write R R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 9-2. External Interrupt 0 Sense Control
ISC01 ISC00 Description
0 0 The low level of INT0 generates an interrupt request (1)
0 1 Any logical change on INT0 generates an interrupt request (2)
1 0 The falling edge of INT0 generates an interrupt request (2)
1 1 The rising edge of INT0 generates an interrupt request (2)
Bit 7 6 5 4 3 2 1 0
0x3C (0x5C) – INT0 PCIE2 PCIE1 PCIE0 – – – GIMSK
Read/Write R R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 0ATtiny1634 [DATASHEET] 52
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
• Bit 3 – PCIE0: Pin Change Interrupt Enable 0
When this bit and the I-bit of SREG are set the Pin Change Interrupt 0 is enabled. Any change on an enabled
PCINT[7:0] pin will cause a PCINT0 interrupt. See Table 9-1 on page 47.
Each pin can be individually enabled. See “PCMSK0 – Pin Change Mask Register 0” on page 53.
9.3.3 GIFR – General Interrupt Flag Register
• Bits 7, 2:0 – Res: Reserved Bits
These bits are reserved and will always read as zero.
• Bit 6 – INTF0: External Interrupt Flag 0
This bit is set when activity on INT0 has triggered an interrupt request. Provided that the I-bit in SREG and the
INT0 bit in GIMSK are set, the MCU will jump to the corresponding interrupt vector.
The flag is cleared when the interrupt service routine is executed. Alternatively, the flag can be cleared by writing a
logical one to it.
This flag is always cleared when INT0 is configured as a level interrupt.
• Bit 5 – PCIF2: Pin Change Interrupt Flag 2
This bit is set when a logic change on any PCINT[17:12] pin has triggered an interrupt request. Provided that the Ibit
in SREG and the PCIE2 bit in GIMSK are set, the MCU will jump to the corresponding interrupt vector.
The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical
one to it.
• Bit 4 – PCIF1: Pin Change Interrupt Flag 1
This bit is set when a logic change on any PCINT[11:8] pin has triggered an interrupt request. Provided that the Ibit
in SREG and the PCIE1 bit in GIMSK are set, the MCU will jump to the corresponding interrupt vector.
The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical
one to it.
• Bit 3 – PCIF0: Pin Change Interrupt Flag 0
This bit is set when a logic change on any PCINT[7:0] pin has triggered an interrupt request. Provided that the I-bit
in SREG and the PCIE0 bit in GIMSK are set, the MCU will jump to the corresponding interrupt vector.
The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical
one to it.
9.3.4 PCMSK2 – Pin Change Mask Register 2
• Bits 7:6 – Res: Reserved Bits
These bits are reserved and will always read zero.
Bit 7 6 5 4 3 2 1 0
0x3B (0x5B) – INTF0 PCIF2 PCIF1 PCIF0 – – – GIFR
Read/Write R R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x29 (0x49) – – PCINT17 PCINT16 PCINT15 PCINT14 PCINT13 PCINT12 PCMSK2
Read/Write R R R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny1634 [DATASHEET] 53
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
• Bits 5:0 – PCINT[17:12]: Pin Change Enable Mask 17:12
Each PCINTn bit selects if the pin change interrupt of the corresponding I/O pin is enabled. Pin change interrupt on
a pin is enabled by setting the mask bit for the pin (PCINTn) and the corresponding group bit (PCIEn) in GIMSK.
When this bit is cleared the pin change interrupt on the corresponding pin is disabled.
9.3.5 PCMSK1 – Pin Change Mask Register 1
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 3:0 – PCINT[11:8]: Pin Change Enable Mask 11:8
Each PCINTn bit selects if the pin change interrupt of the corresponding I/O pin is enabled. Pin change interrupt on
a pin is enabled by setting the mask bit for the pin (PCINTn) and the corresponding group bit (PCIEn) in GIMSK.
When this bit is cleared the pin change interrupt on the corresponding pin is disabled.
9.3.6 PCMSK0 – Pin Change Mask Register 0
• Bits 7:0 – PCINT[7:0]: Pin Change Enable Mask 7:0
Each PCINTn bit selects if the pin change interrupt of the corresponding I/O pin is enabled. Pin change interrupt on
a pin is enabled by setting the mask bit for the pin (PCINTn) and the corresponding group bit (PCIEn) in GIMSK.
When this bit is cleared the pin change interrupt on the corresponding pin is disabled.
Bit 7 6 5 4 3 2 1 0
0x28 (0x48) – – – – PCINT11 PCINT10 PCINT9 PCINT8 PCMSK1
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x27 (0x47) PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 PCMSK0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny1634 [DATASHEET] 54
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
10. I/O Ports
10.1 Overview
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that
the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the
SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling
of pull-up resistors (if configured as input). Most output buffers have symmetrical drive characteristics with
both high sink and source capability, while some are asymmetrical and have high sink and standard source capability.
The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable pull-up
resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VCC and Ground as
indicated in Figure 10-1 on page 54. See “Electrical Characteristics” on page 228 for a complete list of parameters.
Figure 10-1. I/O Pin Equivalent Schematic
All registers and bit references in this section are written in general form. A lower case “x” represents the numbering
letter for the port, and a lower case “n” represents the bit number. However, when using the register or bit
defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented
generally as PORTxn. The physical I/O Registers and bit locations are listed in “” on page 70.
Four I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data
Direction Register – DDRx, Pull-up Enable Register – PUEx, and the Port Input Pins – PINx. The Port Input Pins
I/O location is read only, while the Data Register, the Data Direction Register, and the Pull-Up Enable Register are
read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit
in the Data Register.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page 54. Most port pins
are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes
with the port pin is described in “Alternate Port Functions” on page 59. Refer to the individual module sections
for a full description of the alternate functions.
Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port
as general digital I/O.
10.2 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional description of
one I/O-port pin, here generically called Pxn.
Cpin
Logic
Rpu
See Figure
"General Digital I/O" for
Details
PxnATtiny1634 [DATASHEET] 55
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 10-2. General Digital I/O(1)
Note: 1. WEx, WRx, WPx, WDx, REx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, and SLEEP
are common to all ports.
10.2.1 Configuring the Pin
Each port pin consists of four register bits: DDxn, PORTxn, PUExn, and PINxn. As shown in “Register Description”
on page 71, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, the
PUExn bits at the PUEx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured
as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If
PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero).
clk
RPx
RRx
RDx
WDx
SYNCHRONIZER
clkI/O: I/O CLOCK
D
L
Q
Q
RESET
RESET
Q
D Q
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BUS
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
WPx
0
1
WRx
WEx
REx
RESET
Q
Q D
CLR
PUExn
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
RDx: READ DDRx
WEx: WRITE PUEx
REx: READ PUEx
WPx: WRITE PINx REGISTERATtiny1634 [DATASHEET] 56
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
The pull-up resistor is activated, if the PUExn is written logic one. To switch the pull-up resistor off, PUExn has to
be written logic zero.
Table 10-1 summarizes the control signals for the pin value.
Port pins are tri-stated when a reset condition becomes active, even when no clocks are running.
10.2.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.
10.2.3 Break-Before-Make Switching
In Break-Before-Make mode, switching the DDRxn bit from input to output introduces an immediate tri-state period
lasting one system clock cycle, as indicated in Figure 10-3. For example, if the system clock is 4MHz and the
DDRxn is written to make an output, an immediate tri-state period of 250 ns is introduced before the value of
PORTxn is seen on the port pin.
To avoid glitches it is recommended that the maximum DDRxn toggle frequency is two system clock cycles. The
Break-Before-Make mode applies to the entire port and it is activated by the BBMx bit. For more details, see
“PORTCR – Port Control Register” on page 71.
When switching the DDRxn bit from output to input no immediate tri-state period is introduced.
Table 10-1. Port Pin Configurations
DDxn PORTxn PUExn I/O Pull-up Comment
0 X 0 Input No Tri-state (hi-Z)
0 X 1 Input Yes Sources current if pulled low externally
1 0 0 Output No Output low (sink)
1 0 1 Output Yes
NOT RECOMMENDED.
Output low (sink) and internal pull-up active.
Sources current through the internal pull-up
resistor and consumes power constantly
1 1 0 Output No Output high (source)
1 1 1 Output Yes Output high (source) and internal pull-up activeATtiny1634 [DATASHEET] 57
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 10-3. Switching Between Input and Output in Break-Before-Make-Mode
10.2.4 Reading the Pin Value
Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As
shown in Figure 10-2 on page 55, the PINxn Register bit and the preceding latch constitute a synchronizer. This is
needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces
a delay. Figure 10-4 shows a timing diagram of the synchronization when reading an externally applied pin
value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
Figure 10-4. Synchronization when Reading an Externally Applied Pin value
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when
the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC
LATCH” signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at
the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition
on the pin will be delayed between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 10-5
on page 58. The out instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the
delay tpd through the synchronizer is one system clock period.
out DDRx, r16 nop
0x02 0x01
SYSTEM CLK
INSTRUCTIONS
DDRx
intermediate tri-state cycle
out DDRx, r17
PORTx 0x55
0x01
intermediate tri-state cycle
Px0
Px1
tri-state
tri-state tri-state
r17 0x01
r16 0x02
XXX in r17, PINx
0x00 0xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
tpd, max
tpd, minATtiny1634 [DATASHEET] 58
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 10-5. Synchronization when Reading a Software Assigned Pin Value
10.2.5 Digital Input Enable and Sleep Modes
As shown in Figure 10-2 on page 55, the digital input signal can be clamped to ground at the input of the schmitttrigger.
The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down and Standby
modes to avoid high power consumption if some input signals are left floating, or have an analog signal level close
to VCC/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled,
SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in
“Alternate Port Functions” on page 59.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as “Interrupt on Rising
Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt is not enabled, the corresponding
External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these
sleep mode produces the requested logic change.
10.2.6 Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of
the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to
reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle
mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the
pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use
an external pull-up or pulldown. Connecting unused pins directly to VCC or GND is not recommended, since this
may cause excessive currents if the pin is accidentally configured as an output.
out PORTx, r16 nop in r17, PINx
0xFF
0x00 0xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t pdATtiny1634 [DATASHEET] 59
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
10.2.7 Program Examples
The following code example shows how to set port A pins 0 and 1 high, 2 and 3 low, and define the port pins from
4 to 5 as input with a pull-up assigned to port pin 4. The resulting pin values are read back again, but as previously
discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins.
Note: Two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1 and 4, until the direction bits
are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers.
Note: See “Code Examples” on page 6.
10.3 Alternate Port Functions
Most port pins have alternate functions in addition to being general digital I/Os. In Figure 10-6 below is shown how
the port pin control signals from the simplified Figure 10-2 on page 55 can be overridden by alternate functions.
Assembly Code Example
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1<>8);
UBRRnL = (unsigned char)baud;
/* Enable receiver and transmitter */
UCSRnB = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}ATtiny1634 [DATASHEET] 157
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
16.8.3 Receive Compete Flag and Interrupt
The USART receiver has one flag that indicates the receiver state.
The Receive Complete flag (RXCn) indicates if there are unread data present in the receive buffer. This flag is set
when unread data exist in the receive buffer, and cleared when the receive buffer is empty (i.e., it does not contain
any unread data). If the receiver is disabled (RXENn = 0), the receive buffer will be flushed and, consequently, the
RXCn bit will become zero.
When the Receive Complete Interrupt Enable (RXCIEn) is set, the USART Receive Complete interrupt will be executed
as long as the RXCn flag is set (and provided that global interrupts are enabled). When interrupt-driven data
reception is used, the receive complete routine must read the received data from UDRn in order to clear the RXCn
flag, otherwise a new interrupt will occur once the interrupt routine terminates.
16.8.4 Receiver Error Flags
The USART Receiver has three Error Flags: Frame Error (FEn), Data OverRun (DORn) and Parity Error (UPEn).
All can be accessed by reading UCSRnA. Common for the Error Flags is that they are located in the receive buffer
together with the frame for which they indicate the error status. Due to the buffering of the Error Flags, the UCSRnA
must be read before the receive buffer (UDRn), since reading the UDRn I/O location changes the buffer read
location. Another equality for the Error Flags is that they can not be altered by software doing a write to the flag
location. However, all flags must be set to zero when the UCSRnA is written for upward compatibility of future
USART implementations. None of the Error Flags can generate interrupts.
The Frame Error (FEn) Flag indicates the state of the first stop bit of the next readable frame stored in the receive
buffer. The FEn Flag is zero when the stop bit was correctly read (as one), and the FEn Flag will be one when the
stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions
and protocol handling. The FEn Flag is not affected by the setting of the USBSn bit in UCSRnC since the Receiver
ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing
to UCSRnA.
The Data OverRun (DORn) Flag indicates data loss due to a receiver buffer full condition. A Data OverRun occurs
when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a
new start bit is detected. If the DORn Flag is set there was one or more serial frame lost between the frame last
read from UDRn, and the next frame read from UDRn. For compatibility with future devices, always write this bit to
zero when writing to UCSRnA. The DORn Flag is cleared when the frame received was successfully moved from
the Shift Register to the receive buffer.
The Parity Error (UPEn) Flag indicates that the next frame in the receive buffer had a Parity Error when received. If
Parity Check is not enabled the UPEn bit will always be read zero. For compatibility with future devices, always set
this bit to zero when writing to UCSRnA. For more details see “Parity Bit Calculation” on page 150 and “Parity
Checker” on page 157.
16.8.5 Parity Checker
The parity checker is active when the high USART Parity Mode bit (UPMn1) is set. The type of parity check to be
performed (odd or even) is selected by the UPMn0 bit. When enabled, the parity checker calculates the parity of
the data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the
check is stored in the receive buffer together with the received data and stop bits. The Parity Error flag (UPEn) can
then be read by software to check if the frame had a parity error.
If parity checking is enabled, the UPEn bit is set if the next character that can be read from the receive buffer had a
parity error when received. This bit is valid until the receive buffer (UDRn) is read.ATtiny1634 [DATASHEET] 158
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
16.8.6 Disabling the Receiver
Unlike the transmitter, the receiver is disabled immediately and any data from ongoing receptions will be lost.
When disabled (RXENn = 0), the receiver will no longer override the normal function of the RxDn port pin and the
FIFO buffer is flushed, with any remaining data in the buffer lost.
16.8.7 Flushing the Receive Buffer
The receiver buffer FIFO will be flushed when the receiver is disabled, i.e., the buffer will be emptied of its contents.
Unread data will be lost. To flush the buffer during normal operation, due to for instance an error condition, read the
UDRn until the RXCn flag is cleared.
The following code example shows how to flush the receive buffer.
Note: 1. See “Code Examples” on page 6.
16.9 Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The
clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous
serial frames at the RxDn pin. The data recovery logic samples and low pass filters each incoming bit,
thereby improving the noise immunity of the receiver. The asynchronous reception operational range depends on
the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
16.9.1 Asynchronous Clock Recovery
The clock recovery logic synchronizes the internal clock to the incoming serial frames. Figure 16-5 illustrates the
sampling process of the start bit of an incoming frame. In normal mode the sample rate is 16 times the baud rate,
in double speed mode eight times. The horizontal arrows illustrate the synchronization variation due to the sampling
process. Note the larger time variation when using the double speed mode of operation (U2Xn = 1). Samples
denoted zero are samples done when the RxDn line is idle (i.e., no communication activity).
Assembly Code Example(1)
USART_Flush:
sbis UCSRnA, RXCn
ret
in r16, UDRn
rjmp USART_Flush
C Code Example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRnA & (1< max(16fSCL, 250kHz) 0 400 kHz
tHD:STA Hold time (repeated) START Condition 0.6 – µs
tLOW Low period of SCL clock 1.3 – µs
tHIGH High period of SCL clock 0.6 – µs
tSU:STA Set-up time for repeated START condition 0.6 – µs
tHD:DAT Data hold time 0 0.9 µs
tSU:DAT Data setup time 100 – ns
tSU:STO Setup time for STOP condition 0.6 – µs
tBUF Bus free time between STOP and START condition 1.3 – µs
t
SU:STA
t
LOW
t
HIGH
t
LOW
t
OF
t
HD:STA t
HD:DAT t
SU:DAT
t
SU:STO
t
BUF
SCL
SDA
t
RATtiny1634 [DATASHEET] 234
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
24.7 Analog to Digital Converter
Table 24-9. ADC Characteristics, Single Ended Channels. T = -40C to +85C
Symbol Parameter Condition Min Typ Max Units
Resolution 10 Bits
Absolute accuracy
(Including INL, DNL, and
Quantization, Gain and Offset
Errors)
VREF = 4V, VCC = 4V,
ADC clock = 200kHz 2.0 LSB
VREF = 4V, VCC = 4V,
ADC clock = 1MHz 2.5 LSB
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
Noise Reduction Mode
1.5 LSB
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
Noise Reduction Mode
2.0 LSB
Integral Non-Linearity (INL)
(Accuracy after Offset and
Gain Calibration)
VREF = 4V, VCC = 4V,
ADC clock = 200kHz 1.0 LSB
Differential Non-linearity
(DNL)
VREF = 4V, VCC = 4V,
ADC clock = 200kHz 0.5 LSB
Gain Error VREF = 4V, VCC = 4V,
ADC clock = 200kHz 2.0 LSB
Offset Error (Absolute) VREF = 4V, VCC = 4V,
ADC clock = 200kHz 1.5 LSB
Conversion Time Free Running Conversion 14 280 µs
Clock Frequency 50 1000 kHz
VIN Input Voltage GND VREF V
Input Bandwidth 38.5 kHz
AREF External Voltage Reference 2.0 VCC V
VINT Internal Voltage Reference 1.0 1.1 1.2 V
RREF Reference Input Resistance 32 k
RAIN Analog Input Resistance 100 M
ADC Conversion Output 0 1023 LSBATtiny1634 [DATASHEET] 235
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
24.8 Analog Comparator
24.9 Temperature Sensor
Note: 1. Firmware calculates temperature based on factory calibration value.
2. Min and max values are not guaranteed. Contact your local Atmel sales office if higher accuracy is required.
24.10 Parallel Programming
Figure 24-4. Parallel Programming Timing, Including some General Timing Requirements
Table 24-10. Analog Comparator Characteristics, TA = -40C to +85C
Symbol Parameter Condition Min Typ Max Units
VAIO Input Offset Voltage VCC = 5V, VIN = VCC / 2 < 10 40 mV
ILAC Input Leakage Current VCC = 5V, VIN = VCC / 2 -50 50 nA
tAPD
Analog Propagation Delay
(from saturation to slight overdrive)
VCC = 2.7V 750
ns
VCC = 4.0V 500
Analog Propagation Delay
(large step change)
VCC = 2.7V 100
VCC = 4.0V 75
tDPD Digital Propagation Delay VCC = 1.8 - 5.5V 1 2 CLK
Table 24-11. Accuracy of Temperature Sensor at Factory Calibration
Symbol Parameter Condition Min Typ Max Units
ATS Accuracy VCC = 4.0, TA = 25C – 85C 10 C
Data & Contol
(DATA, XA0/1, BS1, BS2)
CLKI t
XHXL
t
WLWH
t
DVXH t
XLDX
t
PLWL
t
WLRH
WR
RDY/BSY
PAGEL t
PHPL
t t
BVPH PLBX
t
XLWL
t
WLBX
tBVWL
WLRLATtiny1634 [DATASHEET] 236
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 24-5. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
Note: 1. The timing requirements shown in Figure 24-4 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
Figure 24-6. Parallel Programming Timing, Reading Sequence (within the Same Page) with Timing
Requirements(1)
Note: 1. The timing requirements shown in Figure 24-4 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
CLKI
PAGEL
t XLXH PLXH t t
XLPH
z
DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
LOAD DATA
(LOW BYTE)
LOAD DATA
(HIGH BYTE)
LOAD DATA LOAD ADDRESS
(LOW BYTE)
CLKI
OE
DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
READ DATA
(LOW BYTE)
READ DATA
(HIGH BYTE)
LOAD ADDRESS
(LOW BYTE)
t
BVDV
t
OLDV
t
XLOL
t
OHDZATtiny1634 [DATASHEET] 237
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Notes: 1. tWLRH is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits commands.
2. tWLRH_CE is valid for the Chip Erase command.
Table 24-12. Parallel Programming Characteristics, TA = 25C, VCC = 5V
Symbol Parameter Min Typ Max Units
VPP Programming Enable Voltage 11.5 12.5 V
IPP Programming Enable Current 250 A
tDVXH Data and Control Valid before CLKI High 67 ns
tXLXH CLKI Low to CLKI High 200 ns
tXHXL CLKI Pulse Width High 150 ns
tXLDX Data and Control Hold after CLKI Low 67 ns
tXLWL CLKI Low to WR Low 0 ns
tXLPH CLKI Low to PAGEL high 0 ns
tPLXH PAGEL low to CLKI high 150 ns
tBVPH BS1 Valid before PAGEL High 67 ns
tPHPL PAGEL Pulse Width High 150 ns
tPLBX BS1 Hold after PAGEL Low 67 ns
tWLBX BS2/1 Hold after WR Low 67 ns
tPLWL PAGEL Low to WR Low 67 ns
tBVWL BS1 Valid to WR Low 67 ns
tWLWH WR Pulse Width Low 150 ns
tWLRL WR Low to RDY/BSY Low 0 1 s
tWLRH WR Low to RDY/BSY High(1) 3.7 4.5 ms
tWLRH_CE WR Low to RDY/BSY High for Chip Erase(2) 3.7 9 ms
tXLOL CLKI Low to OE Low 0 ns
tBVDV BS1 Valid to DATA valid 0 250 ns
tOLDV OE Low to DATA Valid 250 ns
tOHDZ OE High to DATA Tri-stated 250 nsATtiny1634 [DATASHEET] 238
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
24.11 Serial Programming
Figure 24-7. Serial Programming Timing
Figure 24-8. Serial Programming Waveform
Table 24-13. Serial Programming Characteristics, TA = -40C to +85C
Symbol Parameter Min Typ Max Units
1/tCLCL Oscillator Frequency @ VCC = 1.8V - 5.5V 0 1 MHz
tCLCL Oscillator Period @ VCC = 1.8V - 5.5V 1000 ns
1/tCLCL Oscillator Frequency @ VCC = 4.5V - 5.5V 0 6 MHz
tCLCL Oscillator Period @ VCC = 4.5V - 5.5V 167 ns
tSHSL SCK Pulse Width High 2 tCLCL ns
tSLSH SCK Pulse Width Low 2 tCLCL ns
tOVSH MOSI Setup to SCK High tCLCL ns
tSHOX MOSI Hold after SCK High 2 tCLCL ns
MOSI
MISO
SCK
t
OVSH
t
SHSL
t t
SHOX SLSH
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUTATtiny1634 [DATASHEET] 239
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
25. Electrical Characteristics @ 105C
25.1 Absolute Maximum Ratings*
25.2 DC Characteristics
Table 25-1. DC Characteristics. TA = -40 to +105C
Operating Temperature . . . . . . . . . . . -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only
and functional operation of the device at these
or other conditions beyond those indicated in
the operational sections of this specification is
not implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature . . . . . . . . . . . . . -65C to +150C
Voltage on any Pin except RESET
with respect to Ground. . . . . . . . . . -0.5V to VCC+0.5V
Voltage on RESET with respect to Ground-0.5V to +13.0V
Maximum Operating Voltage . . . . . . . . . . . . . . . . 6.0V
DC Current per I/O Pin. . . . . . . . . . . . . . . . . . 40.0 mA
DC Current VCC and GND Pins . . . . . . . . . . 200.0 mA
Symbol Parameter Condition Min Typ (1) Max Units
VIL
Input Low Voltage
VCC = 1.8 - 2.4V -0.5 0.2VCC (2) V
VCC = 2.4 - 5.5V -0.5 0.3VCC (2) V
Input Low Voltage,
RESET Pin as Reset (4) VCC = 1.8 - 5.5V -0.5 0.2VCC (2)
VIH
Input High-voltage
Except RESET pin
VCC = 1.8 - 2.4V 0.7VCC(3) VCC +0.5 V
VCC = 2.4 - 5.5V 0.6VCC(3) VCC +0.5 V
Input High-voltage
RESET pin as Reset (4) VCC = 1.8 - 5.5V 0.9VCC(3) VCC +0.5 V
VOL
Output Low Voltage(5)
Except RESET pin(7)
Standard I/O: IOL = 10 mA, VCC = 5V
0.6 V
High-sink I/O: IOL = 20 mA, VCC = 5V
Standard I/O: IOL = 5 mA, VCC = 3V
0.5 V
High-sink I/O: IOL = 10 mA, VCC = 3V
VOH
Output High-voltage(6)
Except RESET pin(7)
IOH = -10 mA, VCC = 5V 4.3 V
IOH = -5 mA, VCC = 3V 2.5 V
ILIL
Input Leakage Current
I/O Pin VCC = 5.5V, pin low (absolute value) < 0.05 1 (8) µA
ILIH
Input Leakage Current
I/O Pin VCC = 5.5V, pin high (absolute value) < 0.05 1 (8) µAATtiny1634 [DATASHEET] 240
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Notes: 1. Typical values at +25C.
2. “Max” means the highest value where the pin is guaranteed to be read as low.
3. “Min” means the lowest value where the pin is guaranteed to be read as high.
4. Not tested in production.
5. Although each I/O port can sink more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state conditions (non-transient), the sum of
all IOL (for all ports) should not exceed 100 mA. If IOL exceeds the test conditions, VOL may exceed the related specification. Pins are not guaranteed to sink current
greater than the listed test condition.
6. Although each I/O port can source more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state conditions (non-transient), the sum
of all IOH (for all ports) should not exceed 100 mA. If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source
current greater than the listed test condition.
7. The RESET pin must tolerate high voltages when entering and operating in programming modes and, as a consequence, has a weak drive strength as compared
to regular I/O pins. See “Output Driver Strength” on page 259.
8. These are test limits, which account for leakage currents of the test environment. Actual device leakage currents are lower.
9. Values are with external clock using methods described in “Minimizing Power Consumption” on page 39. Power Reduction is enabled (PRR = 0xFF) and there
is no I/O drive.
10. Bod Disabled.
25.3 Clock
Table 25-2. Accuracy of Calibrated 8MHz Oscillator
Notes: 1. See device ordering codes on page 280 for alternatives.
2. Accuracy of oscillator frequency at calibration point (fixed temperature and fixed voltage).
RPU
Pull-up Resistor, I/O Pin VCC = 5.5V, input low 20 50 k
Pull-up Resistor, Reset
Pin VCC = 5.5V, input low 30 60 k
ICC
Supply Current,
Active Mode (9)
f = 1MHz, VCC = 2V 0.23 0.4 mA
f = 4MHz, VCC = 3V 1.3 1.7 mA
f = 8MHz, VCC = 5V 4.3 6 mA
Supply Current,
Idle Mode (9)
f = 1MHz, VCC = 2V 0.04 0.1 mA
f = 4MHz, VCC = 3V 0.26 0.4 mA
f = 8MHz, VCC = 5V 1.1 1.7 mA
Supply Current,
Power-Down Mode(10)
WDT enabled, VCC = 3V 1.7 6 µA
WDT disabled, VCC = 3V 0.1 4 µA
Symbol Parameter Condition Min Typ (1) Max Units
Calibration
Method Target Frequency VCC Temperature Accuracy
Factory
Calibration 8.0MHz 2.7 – 4V 25C to +105C ±10% (1)
User
Calibration
Within:
7.3 – 8.1MHz
Within:
1.8 – 5.5V
Within:
-40C to +105C ±1% (2)ATtiny1634 [DATASHEET] 241
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Table 25-3. Accuracy of Calibrated 32kHz Oscillator
Table 25-4. External Clock Drive
25.4 System and Reset
Table 25-5. Enhanced Power-On Reset
Note: 1. Values are guidelines only.
2. Threshold where device is released from reset when voltage is rising.
3. The Power-on Reset will not work unless the supply voltage has been below VPOA.
Calibration
Method Target Frequency VCC Temperature Accuracy
Factory
Calibration 32kHz 1.8 – 5.5V -40C to +105C ±30%
Symbol Parameter
VCC = 1.8 - 5.5V VCC = 2.7 - 5.5V VCC = 4.5 - 5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL Clock Frequency 0 2 0 8 0 10 MHz
tCLCL Clock Period 500 125 100 ns
tCHCX High Time 200 40 20 ns
tCLCX Low Time 200 40 20 ns
tCLCH Rise Time 2.0 1.6 0.5 s
tCHCL Fall Time 2.0 1.6 0.5 s
tCLCL
Change in period from one
clock cycle to next 2 2 2 %
Symbol Parameter Min(1) Typ(1) Max(1) Units
VPOR Release threshold of power-on reset (2) 1.1 1.4 1.7 V
VPOA Activation threshold of power-on reset (3) 0.6 1.3 1.7 V
SRON Power-On Slope Rate 0.01 V/msATtiny1634 [DATASHEET] 242
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26. Typical Characteristics
The data contained in this section is largely based on simulations and characterization of similar devices in the
same process and design methods. Thus, the data should be treated as indications of how the part will behave.
The following charts show typical behavior. These figures are not tested during manufacturing. During characterisation
devices are operated at frequencies higher than test limits but they are not guaranteed to function properly
at frequencies higher than the ordering code indicates.
All current consumption measurements are performed with all I/O pins configured as inputs and with internal pullups
enabled. Current consumption is a function of several factors such as operating voltage, operating frequency,
loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature. The dominating factors are
operating voltage and frequency.
A sine wave generator with rail-to-rail output is used as clock source but current consumption in Power-Down
mode is independent of clock selection. The difference between current consumption in Power-Down mode with
Watchdog Timer enabled and Power-Down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.
The current drawn from pins with a capacitive load may be estimated (for one pin) as follows:
where VCC = operating voltage, CL = load capacitance and fSW = average switching frequency of I/O pin.
26.1 Current Consumption in Active Mode
Figure 26-1. Active Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
I
CP VCC CL f
SW
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
ICC[mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
1.8V
2.7VATtiny1634 [DATASHEET] 243
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-2. Active Supply Current vs. Frequency (1 - 12 MHz)
Figure 26-3. Active Supply Current vs. VCC (Internal Oscillator, 8 MHz)
0
1
2
3
4
5
6
7
0 1 2 3 4 5 6 7 8 9 10 11 12
ICC [mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
2.0V
2.7V
1
1.5
2
2.5
3
3.5
4
4.5
5
5.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC[mA]
VCC [V]
INTERNAL RC OSCILLATOR, 8 MHz
105°C
85°C
25°C
-40°C
125°CATtiny1634 [DATASHEET] 244
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-4. Active Supply Current vs. VCC (Internal Oscillator, 1 MHz)
Figure 26-5. Active Supply Current vs. VCC (Internal Oscillator, 32kHz)
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC[mA]
VCC [V]
105°C
85°C
25°C
-40°C
125°C
0
5
10
15
20
25
30
35
40
45
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [µA]
VCC[V]
105°C
85°C
25°C
-40°C
125°CATtiny1634 [DATASHEET] 245
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.2 Current Consumption in Idle Mode
Figure 26-6. Idle Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
Figure 26-7. Idle Supply Current vs. Frequency (1 - 12 MHz)
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
ICC[mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
1.8V
2.7V
0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
0 1 2 3 4 5 6 7 8 9 10 11 12
ICC[mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
1.8V
2.7VATtiny1634 [DATASHEET] 246
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-8. Idle Supply Current vs. VCC (Internal Oscillator, 8 MHz)
Figure 26-9. Idle Supply Current vs. VCC (Internal Oscillator, 1 MHz)
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
2 2.25 2.5 2.75 3 3.25 3.5 3.75 4 4.25 4.5 4.75 5 5.25 5.5
ICC [mA]
VCC [V]
105°C
85°C
25°C
-40°C
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC[mA]
VCC [V]
105 °C
85°C
25°C
-40°CATtiny1634 [DATASHEET] 247
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-10. Idle Supply Current vs. VCC (Internal Oscillator, 32kHz)
26.3 Current Consumption in Standby Mode
Figure 26-11. Standby Supply Current vs. VCC (Watchdog Timer Enabled)
0
5
10
15
20
25
30
35
40
45
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [µA]
VCC [V]
105°C
85°C
25°C
-40°C
0
0.025
0.05
0.075
0.1
0.125
0.15
0.175
0.2
0.225
0.25
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [mA]
VCC [V]
8MHz
32kHzATtiny1634 [DATASHEET] 248
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.4 Current Consumption in Power-down Mode
Figure 26-12. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
Figure 26-13. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
0
0.25
0.5
0.75
1
1.25
1.5
1.75
2
2.25
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [µA]
VCC [V]
105°C
85°C
25°C
-40°C
0
1
2
3
4
5
6
7
8
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [µA]
VCC [V]
105°C
85°C
25°C
-40°CATtiny1634 [DATASHEET] 249
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.5 Current Consumption in Reset
Figure 26-14. Reset Current vs. Frequency (0.1 – 1MHz, Excluding Pull-Up Current)
Figure 26-15. Reset Current vs. Frequency (1 – 12MHz, Excluding Pull-Up Current)
0
0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
ICC [mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
1.8V
2.7V
0
1
2
3
4
5
6
7
8
9
10
0 1 2 3 4 5 6 7 8 9 10 11 12
ICC [mA]
Frequency [MHz]
5.5V
5.0V
4.5V
4.0V
3.3V
1.8V
2.7VATtiny1634 [DATASHEET] 250
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-16. Reset Current vs. VCC (No Clock, excluding Reset Pull-Up Current)
26.6 Current Consumption of Peripheral Units
Figure 26-17. Current Consumption of Peripherals at 4MHz
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [mA]
VCC [V]
105°C
85°C
25°C
-40°C
100
200
300
400
500
600
700
800
900
1000
1100
1.5 2 2.5 3 3.5 4 4.5 5 5.5
ICC [µA]
VCC [V]
ADC
AC
T/C1
T/C0ATtiny1634 [DATASHEET] 251
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-18. Watchdog Timer Current vs. VCC
Figure 26-19. Brownout Detector Current vs. VCC
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5
6.0
1.5 2 2.5 3 3.5 4 4.5 5 5.5
105°C
85°C
25°C
-40°C
ICC [µA]
VCC [V]
13
14
15
16
17
18
19
20
21
22
23
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2
ICC [µA]
VCC [V]
105°C
85°C
25°C
-40°CATtiny1634 [DATASHEET] 252
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-20. Sampled Brownout Detector Current vs. VCC
Figure 26-21. AREF External Reference Pin Current (VCC = 5V)
2
2.5
3
3.5
4
4.5
5
5.5
6
6.5
7
1.8 2.1 2.4 2.7 3 3.3 3.6 3.9 4.2 4.5 4.8 5.1
ICC [µA]
VCC [V]
105°C
85°C
25°C
-40°C
40
50
60
70
80
90
100
110
120
130
140
150
1.4 1.8 2.2 2.6 3 3.4 3.8 4.2 4.6 5
AREF pin current [µA]
AREF [V]
105°C
85°C
25°C
-40°CATtiny1634 [DATASHEET] 253
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.7 Pull-up Resistors
Figure 26-22. I/O pin Pull-up Resistor Current vs. Input Voltage (VCC = 1.8V)
Figure 26-23. I/O Pin Pull-up Resistor Current vs. input Voltage (VCC = 2.7V)
0
5
10
15
20
25
30
35
40
45
50
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8
IOP [µA]
105ºC
85ºC
25ºC
-40ºC
VOP [V]
0
10
20
30
40
50
60
70
80
0 0.3 0.6 0.9 1.2 1.5 1.8 2.1 2.4 2.7
IOP [µA]
VOP [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 254
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-24. I/O pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
Figure 26-25. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 1.8V)
0
20
40
60
80
100
120
140
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
IOP [µA]
VOP [V]
105ºC
85ºC
25ºC
-40ºC
0
5
10
15
20
25
30
35
40
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8
IRESET [µA]
VRESET [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 255
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-26. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
Figure 26-27. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
0
6
12
18
24
30
36
42
48
54
60
0 0.3 0.6 0.9 1.2 1.5 1.8 2.1 2.4 2.7
IRESET [µA]
VRESET [V]
105ºC
85ºC
25ºC
-40ºC
0
10
20
30
40
50
60
70
80
90
100
110
120
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
IRESET [µA]
VRESET [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 256
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.8 Input Thresholds
Figure 26-28. VIH: Input Threshold Voltage vs. VCC (I/O Pin, Read as ‘1’)
Figure 26-29. VIL: Input Threshold Voltage vs. VCC (I/O Pin, Read as ‘0’)
0.7
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.3
2.5
2.7
2.9
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
25ºC
-40ºC
Vthreshold [
V]
0
0.3
0.6
0.9
1.2
1.5
1.8
2.1
2.4
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
25ºC
-40ºC
Vthreshold [
V]ATtiny1634 [DATASHEET] 257
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-30. VIH-VIL: Input Hysteresis vs. VCC (I/O Pin)
Figure 26-31. VIH: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘1’)
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
25ºC
-40ºC
Vthreshold [
V]
0.5
0.7
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.3
2.5
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
-40ºC 25ºC
Vthreshold [
V]ATtiny1634 [DATASHEET] 258
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-32. VIL: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘0’)
Figure 26-33. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin as I/O)
0.5
0.7
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.3
2.5
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
Vthreshold [V]
105ºC
85ºC
25ºC
-40ºC
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 259
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.9 Output Driver Strength
Figure 26-34. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 1.8V)
Figure 26-35. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 3V)
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºC
2
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
3
0 1 2 3 4 5 6 7 8 9 10
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 260
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-36. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 5V)
Figure 26-37. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 1.8V)
4
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
5
0 2 4 6 8 10 12 14 16 18 20
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºC
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 261
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-38. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 3V)
Figure 26-39. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 5V)
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 1 2 3 4 5 6 7 8 9 10
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºC
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0 2 4 6 8 10 12 14 16 18 20
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 262
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-40. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 1.8V
Figure 26-41. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 3V
0
0.2
0.4
0.6
0.8
1
1.2
1.4
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºC
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2
2.1
2.2
2.3
2.4
2.5
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 263
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-42. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 5V
Figure 26-43. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 1.8V)
2.7
2.9
3.1
3.3
3.5
3.7
3.9
4.1
4.3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
VOH [V]
IOH [mA]
105ºC
85ºC
25ºC
-40ºC
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 264
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-44. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 3V)
Figure 26-45. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 5V)
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºC
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0 0.4 0.8 1.2 1.6 2 2.4 2.8 3.2 3.6 4
VOL [V]
IOL [mA]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 265
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.10 BOD
Figure 26-46. BOD Threshold vs Temperature (BODLEVEL = 4.3V)
Figure 26-47. BOD Threshold vs Temperature (BODLEVEL = 2.7V)
4.16
4.18
4.2
4.22
4.24
4.26
4.28
4.3
4.32
4.34
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V]
2.62
2.64
2.66
2.68
2.7
2.72
2.74
2.76
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V]ATtiny1634 [DATASHEET] 266
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-48. BOD Threshold vs Temperature (BODLEVEL = 1.8V)
Figure 26-49. Sampled BOD Threshold vs Temperature (BODLEVEL = 4.3V)
1.75
1.76
1.77
1.78
1.79
1.8
1.81
1.82
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V]
4.25
4.26
4.27
4.28
4.29
4.3
4.31
4.32
4.33
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 130
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V]ATtiny1634 [DATASHEET] 267
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-50. Sampled BOD Threshold vs Temperature (BODLEVEL = 2.7V)
Figure 26-51. Sampled BOD Threshold vs Temperature (BODLEVEL = 1.8V)
2.71
2.715
2.72
2.725
2.73
2.735
2.74
2.745
2.75
2.755
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V] 1.772
1.774
1.776
1.778
1.78
1.782
1.784
1.786
1.788
1.79
1.792
1.794
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Rising Vcc
Falling Vcc
Temperature [°C]
VThreshold [
V]ATtiny1634 [DATASHEET] 268
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.11 Bandgap Voltage
Figure 26-52. Bandgap Voltage vs. Supply Voltage
Figure 26-53. Bandgap Voltage vs. Temperature
1.04
1.045
1.05
1.055
1.06
1.065
1.07
1.075
1.08
1.5 2 2.5 3 3.5 4 4.5 5 5.5
Bandgap [V]
105°C
85°C
25°C
-40°C
VCC [V]
1.042
1.044
1.046
1.048
1.05
1.052
1.054
1.056
1.058
1.06
1.062
1.064
1.066
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
Bandgap Voltage [V]
5.5V
3.3V
1.8V
Temperature [°C]ATtiny1634 [DATASHEET] 269
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.12 Reset
Figure 26-54. VIH: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘1’)
Figure 26-55. VIL: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘0’)
0.6
0.9
1.2
1.5
1.8
2.1
2.4
2.7
3
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
Vthreshold [V]
105ºC
85ºC
25ºC
-40ºC
0
0.3
0.6
0.9
1.2
1.5
1.8
2.1
2.4
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
Vthreshold [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 270
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-56. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin )
Figure 26-57. Minimum Reset Pulse Width vs. VCC
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
VHysteresis [V]
105ºC
85ºC
25ºC
-40ºC
0
200
400
600
800
1000
1200
1400
1600
1800
2000
2200
2400
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC [V]
105ºC
85ºC
25ºC
-40ºC
TRST [ns]ATtiny1634 [DATASHEET] 271
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
26.13 Analog Comparator Offset
Figure 26-58. Analog Comparator Offset vs. VIN (VCC = 5V)
Figure 26-59. Analog Comparator Offset vs. VCC (VIN = 1.1V)
0
10
20
30
40
50
60
70
80
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Offset [mV]
VIN [V]
105°C 85°C
25°C
-40°C
3
3.5
4
4.5
5
5.5
6
6.5
7
7.5
8
1.5 2 2.5 3 3.5 4 4.5 5 5.5
Offset [mV]
VCC [V]
105°C
85°C
25°C
-40°CATtiny1634 [DATASHEET] 272
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-60. Analog Comparator Hysteresis vs. VIN (VCC = 5.0V)
26.14 Internal Oscillator Speed
Figure 26-61. Calibrated Oscillator Frequency (Nominal = 8MHz) vs. VCC
0
5
10
15
20
25
30
35
40
45
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Hysteresis [mV]
VIN [V]
105°C 85°C
25°C
-40°C
7.8
7.85
7.9
7.95
8
8.05
8.1
8.15
8.2
8.25
8.3
1.9 2.3 2.7 3.1 3.5 3.9 4.3 4.7 5.1 5.5
FRC [MHz]
VCC [V]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 273
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-62. Calibrated Oscillator Frequency (Nominal = 8MHz) vs. Temperature
Figure 26-63. Calibrated Oscillator Frequency (Nominal = 8MHz) vs. OSCCAL Value
7.92
7.94
7.96
7.98
8
8.02
8.04
8.06
8.08
8.1
8.12
8.14
8.16
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
FRC [MHz]
5.0V
3.0V
Temperature [°C]
0
2
4
6
8
10
12
14
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
FRC [MHz]
OSCCAL [X1]
105ºC
85ºC
25ºC
-40ºCATtiny1634 [DATASHEET] 274
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-64. Calibrated Oscillator Frequency (Nominal = 1MHz) vs. VCC
Figure 26-65. Calibrated Oscillator Frequency (Nominal = 1MHz) vs. Temperature
0.97
0.98
0.99
1
1.01
1.02
1.03
1.04
1.05
1.5 2 2.5 3 3.5 4 4.5 5 5.5
FRC [MHz]
VCC [V]
105ºC
85ºC
25ºC
-40ºC
0.975
0.98
0.985
0.99
0.995
1.00
1.005
1.01
1.015
1.02
1.025
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
FRC [MHz]
5.0V
1.8V
Temperature [°C]
3.0VATtiny1634 [DATASHEET] 275
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Figure 26-66. ULP Oscillator Frequency (Nominal = 32kHz) vs. VCC
Figure 26-67. ULP Oscillator Frequency (Nominal = 32kHz) vs. Temperature
28.0
28.5
29.0
29.5
30.0
30.5
31.0
31.5
32.0
1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
FRC [kHz]
VCC [V]
105ºC
85ºC
25ºC
-40ºC
26
27
28
29
30
31
32
33
-45 -35 -25 -15 -5 5 15 25 35 45 55 65 75 85 95 105 115 125
FRC [kHz]
Temperature [°C]ATtiny1634 [DATASHEET] 276
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
27. Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page(s)
(0xFF) Reserved – – – – – – – –
(0xFE) Reserved – – – – – – – –
(0xFD) Reserved – – – – – – – –
(0xFC) Reserved – – – – – – – –
(0xFB) Reserved – – – – – – – –
(0xFA) Reserved – – – – – – – –
(0xF9) Reserved – – – – – – – –
... ... ... ... ... ... ... ... ... ... ...
(0x85) Reserved – – – – – – – –
(0x84) Reserved – – – – – – – –
(0x83) Reserved – – – – – – – –
(0x82) Reserved – – – – – – – –
(0x81) Reserved – – – – – – – –
(0x80) Reserved – – – – – – – –
(0x7F) TWSCRA TWSHE – TWDIE TWASIE TWEN TWSIE TWPME TWSME 127
(0x7E) TWSCRB TWAA TWCMD[1:0] 127
(0x7D) TWSSRA TWDIF TWASIF TWCH TWRA TWC TWBE TWDIR TWAS 128
(0x7C) TWSA TWI Slave Address Register 130
(0x7B) TWSAM TWI Slave Address Mask Register 130
(0x7A) TWSD TWI Slave Data Register 130
(0x79) UCSR1A RXC1 TXC1 UDRE1 FE1 DOR1 UPE1 U2X1 MPCM1 167
(0x78) UCSR1B RXCIE1 TXCIE1 UDRIE1 RXEN1 TXEN1 UCSZ12 RXB81 TXB81 168
(0x77) UCSR1C UMSEL11 UMSEL10 UPM11 UPM01 USBS1 UCSZ11 UCSZ10 UCPOL1 169
(0x76) UCSR1D RXSIE1 RXS1 SFDE1 171
(0x75) UBRR1H USART1 Baud Rate Register High Byte 172
(0x74) UBRR1L USART1 Baud Rate Register Low Byte 172
(0x73) UDR1 USART1 I/O Data Register 167
(0x72) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 111
(0x71) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 113
(0x70) TCCR1C FOC1A FOC1B – – – – – – 114
(0x6F) TCNT1H Timer/Counter1 – Counter Register High Byte 114
(0x6E) TCNT1L Timer/Counter1 – Counter Register Low Byte 114
(0x6D) OCR1AH Timer/Counter1 – Compare Register A High Byte 114
(0x6C) OCR1AL Timer/Counter1 – Compare Register A Low Byte 114
(0x6B) OCR1BH Timer/Counter1 – Compare Register B High Byte 115
(0x6A) OCR1BL Timer/Counter1 – Compare Register B Low Byte 115
(0x69) ICR1H Timer/Counter1 – Input Capture Register High Byte 115
(0x68) ICR1L Timer/Counter1 – Input Capture Register Low Byte 115
(0x67) GTCCR TSM – – – – – – PSR10 118
(0x66) OSCCAL1 – – – – – – CAL11 CAL10 33
(0x65) OSCTCAL0B Oscillator Temperature Compensation Register B 33
(0x64) OSCTCAL0A Oscillator Temperature Compensation Register A 33
(0x63) OSCCAL0 CAL07 CAL06 CAL05 CAL04 CAL03 CAL02 CAL01 CAL00 32
(0x62) DIDR2 – – – – – ADC11D ADC10D ADC9D 200
(0x61) DIDR1 – – – – ADC8D ADC7D ADC6D ADC5D 200
(0x60) DIDR0 ADC4D ADC3D ADC2D ADC1D ADC0D AIN1D AIN0D AREFD 184, 200
0x3F (0x5F) SREG I T H S V N Z C 14
0x3E (0x5E) SPH – – – – – SP10 SP9 SP8 13
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 13
0x3C (0x5C) GIMSK – INT0 PCIE2 PCIE1 PCIE0 – – – 51
0x3B (0x5B) GIFR – INTF0 PCIF2 PCIF1 PCIF0 – – – 52
0x3A (0x5A) TIMSK TOIE1 OCIE1A OCIE1B – ICIE1 OCIE0B TOIE0 OCIE0A 88, 115
0x39 (0x59) TIFR TOV1 OCF1A OCF1B – ICF1 OCF0B TOV0 OCF0A 89, 116
0x38 (0x58) QTCSR QTouch Control and Status Register 6
0x37 (0x57) SPMCSR – – RSIG CTPB RFLB PGWRT PGERS SPMEN 207
0x36 (0x56) MCUCR – SM1 SM0 SE – – ISC01 ISC00 37, 51
0x35 (0x55) MCUSR – – – – WDRF BORF EXTRF PORF 44
0x34 (0x54) PRR – PRTWI PRTIM0 PRTIM0 PRUSI PRUSART1 PRUSART0 PRADC 38
0x33 (0x53) CLKPR – – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 31
0x32 (0x52) CLKSR OSCRDY CSTR CKOUT_IO SUT CKSEL3 CKSEL2 CKSEL1 CKSEL0 29
0x31 (0x51) Reserved – – – – – – – –
0x30 (0x50) WDTCSR WDIF WDIE WDP3 – WDE WDP2 WDP1 WDP0 45
0x2F (0x4F) CCP CPU Change Protection Register 13
0x2E (0x4E) DWDR DWDR[7:0] 202
0x2D (0x4D) USIBR USI Buffer Register 144
0x2C (0x4C) USIDR USI Data Register 143ATtiny1634 [DATASHEET] 277
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operation the specified bit, and can therefore be used on registers containing such Status Flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.
0x2B (0x4B) USISR USISIF USIOIF USIPF USIDC USICNT3 USICNT2 USICNT1 USICNT0 142
0x2A (0x4A) USICR USISIE USIOIE USIWM1 USIWM0 USICS1 USICS0 USICLK USITC 140
0x29 (0x49) PCMSK2 – – PCINT17 PCINT16 PCINT15 PCINT14 PCINT13 PCINT12 52
0x28 (0x48) PCMSK1 – – – – PCINT11 PCINT10 PCINT9 PCINT8 53
0x27 (0x47) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 53
0x26 (0x46) UCSR0A RXC0 TXC0 UDRE0 FE0 DOR0 UPE0 U2X0 MPCM 167
0x25 (0x45) UCSR0B RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80 168
0x24 (0x44) UCSR0C UMSEL01 UMSEL00 UPM01 UPM00 USBS0 UCSZ01 UCSZ00 UCPOL0 169
0x23 (0x43) UCSR0D RXCIE0 RXS0 SFDE0 – – – – – 171
0x22 (0x42) UBRR0H – – – – USART0 Baud Rate Register High Byte 172
0x21 (0x41) UBRR0L USART0 Baud Rate Register Low Byte 172
0x20 (0x40) UDR0 USART0 I/O Data Register 167
0x1F (0x3F) EEARH – – – – – – – –
0x1E (0x3E) EEARL EEAR[7:0] 22
0x1D (0x3D) EEDR EEPROM Data Register 22
0x1C (0x3C) EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE 22
0x1B (0x3B) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 84
0x1A (0x3A) TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00 86
0x19 (0x39) TCNT0 Timer/Counter0 88
0x18 (0x38) OCR0A Timer/Counter0 – Compare Register A 88
0x17 (0x37) OCR0B Timer/Counter0 – Compare Register B 88
0x16 (0x36) GPIOR2 General Purpose Register 2 23
0x15 (0x35) GPIOR1 General Purpose Register 1 24
0x14 (0x34) GPIOR0 General Purpose Register 0 24
0x13 (0x33) PORTCR – – – – – BBMC BBMB BBMA 71
0x12 (0x32) PUEA PUEA7 PUEA6 PUEA5 PUEA4 PUEA3 PUEA2 PUEA1 PUEA0 71
0x11 (0x31) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 71
0x10 (0x30) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 71
0x0F (0x2F) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 71
0x0E (0x2E) PUEB – – – – PUEB3 PUEB2 PUEB1 PUEB0 72
0x0D (0x2D) PORTB – – – – PORTB3 PORTB2 PORTB1 PORTB0 72
0x0C (0x2C) DDRB – – – – DDB3 DDB2 DDB1 DDB0 72
0x0B (0x2B) PINB – – – – PINB3 PINB2 PINB1 PINB0 72
0x0A (0x2A) PUEC – – PUEC5 PUEC4 PUEC3 PUEC2 PUEC1 PUEC0 72
0x09 (0x29) PORTC – – PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 72
0x08 (0x28) DDRC – – DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 72
0x07 (0x27) PINC – – PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 72
0x06 (0x26) ACSRA ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 182
0x05 (0x25) ACSRB HSEL HLEV ACLP – ACCE ACME ACIRS1 ACIRS0 183
0x04 (0x24) ADMUX REFS1 REFS0 REFEN ADC0EN MUX3 MUX2 MUX1 MUX0 196
0x03 (0x23) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 197
0x02 (0x22) ADCSRB VDEN VDPD – – ADLAR ADTS2 ADTS1 ADTS0 199
0x01 (0x21) ADCH ADC Data Register High Byte 198
0x00 (0x20) ADCL ADC Data Register Low Byte 198
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page(s)ATtiny1634 [DATASHEET] 278
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
28. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd Rd Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd Rd K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z,N,V 1
COM Rd One’s Complement Rd 0xFF Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd 0x00 Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd Rd (0xFF - K) Z,N,V 1
INC Rd Increment Rd Rd + 1 Z,N,V 1
DEC Rd Decrement Rd Rd 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd Rd Rd Z,N,V 1
CLR Rd Clear Register Rd Rd Rd Z,N,V 1
SER Rd Set Register Rd 0xFF None 1
BRANCH INSTRUCTIONS
JMP k Direct Jump PC k None 3
RJMP k Relative Jump PC PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC Z None 2
CALL k Direct Subroutine PC k None 4
RCALL k Relative Subroutine Call PC PC + k + 1 None 3
ICALL Indirect Call to (Z) PC Z None 3
RET Subroutine Return PC STACK None 4
RETI Interrupt Return PC STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd Rr C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) 0 None 2
LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z,C,N,V 1ATtiny1634 [DATASHEET] 279
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) T None 1
SEC Set Carry C 1 C1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1 N1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1 Z1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1 I1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1 S1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Twos Complement Overflow. V 1 V1
CLV Clear Twos Complement Overflow V 0 V 1
SET Set T in SREG T 1 T1
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1 H1
CLH Clear Half Carry Flag in SREG H 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd K None 1
LD Rd, X Load Indirect Rd (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2
LD Rd, Y Load Indirect Rd (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2
LD Rd, Z Load Indirect Rd (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd (k) None 2
ST X, Rr Store Indirect (X) Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) Rr, X X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2
ST Y, Rr Store Indirect (Y) Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) Rr, Y Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) Rr None 2
ST Z, Rr Store Indirect (Z) Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2
STS k, Rr Store Direct to SRAM (k) Rr None 2
LPM Load Program Memory R0 (Z) None 3
LPM Rd, Z Load Program Memory Rd (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd (Z), Z Z+1 None 3
SPM Store Program Memory (z) R1:R0 None
IN Rd, P In Port Rd P None 1
OUT P, Rr Out Port P Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 2
POP Rd Pop Register from Stack Rd STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/Timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #ClocksATtiny1634 [DATASHEET] 280
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
29. Ordering Information
Notes: 1. For speed vs. supply voltage, see section 24.3 “Speed” on page 229.
2. All packages are Pb-free, halide-free and fully green, and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Denotes accuracy of the internal oscillator. See Table 24-2 on page 230.
4. Code indicators:
– U: matte tin
– R: tape & reel
5. Can also be supplied in wafer form. Contact your local Atmel sales office for ordering information and minimum quantities.
29.1 ATtiny1634
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Accuracy (3) Ordering Code (4)
12 1.8 – 5.5
Industrial
(-40C to +85C)(5)
20M1
±10% ATtiny1634-MU
±2% ATtiny1634R-MU
±10% ATtiny1634-MUR
±2% ATtiny1634R-MUR
20S2
±10% ATtiny1634-SU
±2% ATtiny1634R-SU
±10% ATtiny1634-SUR
±2% ATtiny1634R-SUR
Extended
(-40C to +105C)(5) 20M1
±10% ATtiny1634-MN
±10% ATtiny1634-MNR
Package Type
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead / Micro Lead Frame Package (QFN/MLF)
20S2 20-lead, 0.300" Wide Body, Plastic Gull Wing Small Outline Package (SOIC)ATtiny1634 [DATASHEET] 281
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
30. Packaging Information
30.1 20M1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO. REV.
20M1, 20-pad, 4 x 4 x 0.8 mm Body, Lead Pitch 0.50 mm, 20M1 B
12/02/2014
2.6 mm Exposed Pad, Micro Lead Frame Package (MLF)
A 0.70 0.75 0.80
A1 – 0.01 0.05
A2 0.20 REF
b 0.18 0.23 0.30
D 4.00 BSC
D2 2.45 2.60 2.75
E 4.00 BSC
E2 2.45 2.60 2.75
e 0.50 BSC
L 0.35 0.40 0.55
SIDE VIEW
Pin 1 ID
Pin #1
Notch
(0.20 R)
BOTTOM VIEW
TOP VIEW
Note: Reference JEDEC Standard MO-220, Fig. 1 (SAW Singulation) WGGD-5.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D
E
e
A2
A1
A
D2
E2
0.08 C
L
1
2
3
b
1
2
3ATtiny1634 [DATASHEET] 282
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
30.2 20S2ATtiny1634 [DATASHEET] 283
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
31. Errata
The revision letters in this section refer to the revision of the corresponding ATtiny1634 device.
31.1 ATtiny1634
31.1.1 Rev. C
• Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
1. Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
Port pin PB3 is not guaranteed to perform as a reliable input when the Ultra Low Power (ULP) oscillator is not
running. In addition, the pin is pulled down internally when ULP oscillator is disabled.
Problem Fix / Workaround
The ULP oscillator is automatically activated when required. To use PB3 as an input, activate the watchdog
timer. The watchdog timer automatically enables the ULP oscillator.
31.1.2 Rev. B
• Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
1. Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
Port pin PB3 is not guaranteed to perform as a reliable input when the Ultra Low Power (ULP) oscillator is not
running. In addition, the pin is pulled down internally when ULP oscillator is disabled.
Problem Fix / Workaround
The ULP oscillator is automatically activated when required. To use PB3 as an input, activate the watchdog
timer. The watchdog timer automatically enables the ULP oscillator.
31.1.3 Rev. A
• Flash / EEPROM Can Not Be Written When Supply Voltage Is Below 2.4V
• Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
1. Flash / EEPROM Can Not Be Written When Supply Voltage Is Below 2.4V
When supply voltage is below 2.4V write operations to Flash and EEPROM may fail.
Problem Fix / Workaround
Do not write to Flash or EEPROM when supply voltage is below 2.4V.
2. Port Pin Should Not Be Used As Input When ULP Oscillator Is Disabled
Port pin PB3 is not guaranteed to perform as a reliable input when the Ultra Low Power (ULP) oscillator is not
running. In addition, the pin is pulled down internally when ULP oscillator is disabled.
Problem Fix / Workaround
The ULP oscillator is automatically activated when required. To use PB3 as an input, activate the watchdog
timer. The watchdog timer automatically enables the ULP oscillator.ATtiny1634 [DATASHEET] 284
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
32. Datasheet Revision History
32.1 Rev. 8303H – 02/2014
1. Updated:
– Updated the front page. Temperature range changed to -40C to +105C
– Table 19-2 on page 195. Added 375 LSB for 105C
– “Electrical Characteristics @ 105°C” on page 239
– “Typical Characteristics” on page 242 @ 105C
– “Ordering Information” on page 280. Ordering code: ATtiny1634-MNR added
2. Added:
– “Errata” “Rev. C” on page 283.
32.2 Rev. 8303G – 11/2013
1. Removed references to Wafer Level Chip Scale Package option.
32.3 Rev. 8303F – 08/2013
1. Updated Bit 2 from the UCSR1C register from “USBSZ11” to “UCSZ11” in “Register Summary” on page
276.
32.4 Rev. 8303E – 01/2013
1. Updated:
– Applied the Atmel new brand template that includes new log and new addresses.
32.5 Rev. 8303D – 06/12
1. Updated:
– “Ordering Information” on page 280
2. Added:
– Wafer Level Chip Scale Package “Errata” on page 283
32.6 Rev. 8303C – 03/12
1. Updated:
– “Register Description” on page 167
– “Self-Programming” on page 203
32.7 Rev. 8303B – 03/12
1. Removed Preliminary status.
2. Added:
– “Typical Characteristics” on page 242
– “Temperature Sensor” on page 235
– “Rev. B” on page 283
3. Updated:
– “Pin Descriptions” on page 3
– “Calibrated Internal 8MHz Oscillator” on page 27
– “OSCTCAL0A – Oscillator Temperature Calibration Register A” on page 33ATtiny1634 [DATASHEET] 285
Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014
– “OSCTCAL0B – Oscillator Temperature Calibration Register B” on page 33
– “TWSCRA – TWI Slave Control Register A” on page 127
– “USART (USART0 & USART1)” on page 145
– “Temperature vs. Sensor Output Voltage (Typical)” on page 195
– “DC Characteristics” on page 228
– “Calibration Accuracy of Internal 32kHz Oscillator” on page 231
– “External Clock Drive Characteristics” on page 231
– “Reset, Brown-out, and Internal Voltage Characteristics” on page 231
– “Analog Comparator Characteristics, TA = -40°C to +85°C” on page 235
– “Parallel Programming Characteristics, TA = 25°C, VCC = 5V” on page 237
– “Serial Programming Characteristics, TA = -40°C to +85°C” on page 238
– “Ordering Information” on page 280
32.8 Rev. 8303A – 11/11
Initial revision.ATtiny1634 [DATASHEET] i
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
Table of Contents
Features .....................................................................................................1
1 Pin Configurations ...................................................................................2
1.1 Pin Descriptions .................................................................................................3
2 Overview ...................................................................................................4
3 General Information .................................................................................6
3.1 Resources .........................................................................................................6
3.2 Code Examples .................................................................................................6
3.3 Capacitive Touch Sensing .................................................................................6
3.4 Data Retention ...................................................................................................6
4 CPU Core ...................................................................................................6
4.1 Architectural Overview .......................................................................................7
4.2 ALU – Arithmetic Logic Unit ...............................................................................8
4.3 Status Register ..................................................................................................8
4.4 General Purpose Register File ..........................................................................8
4.5 Stack Pointer ...................................................................................................10
4.6 Instruction Execution Timing ...........................................................................10
4.7 Reset and Interrupt Handling ...........................................................................11
4.8 Register Description ........................................................................................13
5 Memories .................................................................................................15
5.1 Program Memory (Flash) .................................................................................15
5.2 Data Memory (SRAM) and Register Files .......................................................16
5.3 Data Memory (EEPROM) ................................................................................17
5.4 Register Description ........................................................................................22
6 Clock System ..........................................................................................24
6.1 Clock Subsystems ...........................................................................................25
6.2 Clock Sources .................................................................................................26
6.3 System Clock Prescaler ..................................................................................28
6.4 Clock Output Buffer .........................................................................................29
6.5 Register Description ........................................................................................29
7 Power Management and Sleep Modes .................................................34
7.1 Sleep Modes ....................................................................................................34
7.2 Power Reduction Register ...............................................................................36
7.3 Minimizing Power Consumption ......................................................................36ATtiny1634 [DATASHEET] ii
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
7.4 Register Description ........................................................................................37
8 System Control and Reset .....................................................................39
8.1 Resetting the AVR ...........................................................................................39
8.2 Reset Sources .................................................................................................39
8.3 Internal Voltage Reference ..............................................................................42
8.4 Watchdog Timer ..............................................................................................43
8.5 Register Description ........................................................................................44
9 Interrupts .................................................................................................47
9.1 Interrupt Vectors ..............................................................................................47
9.2 External Interrupts ...........................................................................................48
9.3 Register Description ........................................................................................51
10 I/O Ports ..................................................................................................54
10.1 Overview ..........................................................................................................54
10.2 Ports as General Digital I/O .............................................................................54
10.3 Alternate Port Functions ..................................................................................59
10.4 Register Description ........................................................................................71
11 8-bit Timer/Counter0 with PWM ............................................................73
11.1 Features ..........................................................................................................73
11.2 Overview ..........................................................................................................73
11.3 Clock Sources .................................................................................................74
11.4 Counter Unit ....................................................................................................74
11.5 Output Compare Unit .......................................................................................75
11.6 Compare Match Output Unit ............................................................................77
11.7 Modes of Operation .........................................................................................78
11.8 Timer/Counter Timing Diagrams ......................................................................82
11.9 Register Description ........................................................................................84
12 16-bit Timer/Counter1 ............................................................................90
12.1 Features ..........................................................................................................90
12.2 Overview ..........................................................................................................90
12.3 Timer/Counter Clock Sources .........................................................................92
12.4 Counter Unit ....................................................................................................92
12.5 Input Capture Unit ...........................................................................................93
12.6 Output Compare Units .....................................................................................95
12.7 Compare Match Output Unit ............................................................................97
12.8 Modes of Operation .........................................................................................98ATtiny1634 [DATASHEET] iii
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
12.9 Timer/Counter Timing Diagrams ....................................................................106
12.10 Accessing 16-bit Registers ............................................................................107
12.11 Register Description ......................................................................................111
13 Timer/Counter Prescaler ......................................................................117
13.1 Prescaler Reset .............................................................................................117
13.2 External Clock Source ...................................................................................118
13.3 Register Description ......................................................................................118
14 I2C Compatible, Two-Wire Slave Interface .........................................119
14.1 Features ........................................................................................................119
14.2 Overview ........................................................................................................119
14.3 General TWI Bus Concepts ...........................................................................119
14.4 TWI Slave Operation .....................................................................................125
14.5 Register Description ......................................................................................127
15 USI – Universal Serial Interface ..........................................................131
15.1 Features ........................................................................................................131
15.2 Overview ........................................................................................................131
15.3 Three-wire Mode ...........................................................................................132
15.4 Two-wire Mode ..............................................................................................134
15.5 Alternative Use ..............................................................................................136
15.6 Program Examples ........................................................................................137
15.7 Register Descriptions ....................................................................................140
16 USART (USART0 & USART1) ..............................................................145
16.1 Features ........................................................................................................145
16.2 USART0 and USART1 ..................................................................................145
16.3 Overview ........................................................................................................145
16.4 Clock Generation ...........................................................................................147
16.5 Frame Formats ..............................................................................................149
16.6 USART Initialization .......................................................................................151
16.7 Data Transmission – The USART Transmitter ..............................................152
16.8 Data Reception – The USART Receiver .......................................................154
16.9 Asynchronous Data Reception ......................................................................158
16.10 Multi-processor Communication Mode ..........................................................162
16.11 Examples of Baud Rate Setting .....................................................................163
16.12 Register Description ......................................................................................167
17 USART in SPI Mode ..............................................................................173ATtiny1634 [DATASHEET] iv
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
17.1 Features ........................................................................................................173
17.2 Overview ........................................................................................................173
17.3 Clock Generation ...........................................................................................173
17.4 SPI Data Modes and Timing ..........................................................................173
17.5 Frame Formats ..............................................................................................174
17.6 Data Transfer .................................................................................................176
17.7 Compatibility with AVR SPI ...........................................................................178
17.8 Register Description ......................................................................................178
18 Analog Comparator ..............................................................................181
18.1 Analog Comparator Multiplexed Input ...........................................................181
18.2 Register Description ......................................................................................182
19 Analog to Digital Converter .................................................................185
19.1 Features ........................................................................................................185
19.2 Overview ........................................................................................................185
19.3 Operation .......................................................................................................186
19.4 Starting a Conversion ....................................................................................187
19.5 Prescaling and Conversion Timing ................................................................188
19.6 Changing Channel or Reference Selection ...................................................191
19.7 ADC Noise Canceler .....................................................................................192
19.8 Analog Input Circuitry ....................................................................................192
19.9 Noise Canceling Techniques .........................................................................193
19.10 ADC Accuracy Definitions .............................................................................193
19.11 ADC Conversion Result .................................................................................195
19.12 Temperature Measurement ...........................................................................195
19.13 Register Description ......................................................................................196
20 debugWIRE On-chip Debug System ...................................................201
20.1 Features ........................................................................................................201
20.2 Overview ........................................................................................................201
20.3 Physical Interface ..........................................................................................201
20.4 Software Break Points ...................................................................................202
20.5 Limitations of debugWIRE .............................................................................202
20.6 Register Description ......................................................................................202
21 Self-Programming ................................................................................203
21.1 Features ........................................................................................................203
21.2 Overview ........................................................................................................203ATtiny1634 [DATASHEET] v
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
21.3 Lock Bits ........................................................................................................203
21.4 Self-Programming the Flash ..........................................................................203
21.5 Preventing Flash Corruption ..........................................................................206
21.6 Programming Time for Flash when Using SPM .............................................206
21.7 Register Description ......................................................................................207
22 Lock Bits, Fuse Bits and Device Signature .......................................208
22.1 Lock Bits ........................................................................................................208
22.2 Fuse Bits ........................................................................................................209
22.3 Device Signature Imprint Table .....................................................................210
22.4 Reading Lock, Fuse and Signature Data from Software ...............................211
23 External Programming .........................................................................214
23.1 Memory Parametrics .....................................................................................214
23.2 Parallel Programming ....................................................................................214
23.3 Serial Programming .......................................................................................223
23.4 Programming Time for Flash and EEPROM ..................................................227
24 Electrical Characteristics ....................................................................228
24.1 Absolute Maximum Ratings* .........................................................................228
24.2 DC Characteristics .........................................................................................228
24.3 Speed ............................................................................................................229
24.4 Clock ..............................................................................................................230
24.5 System and Reset .........................................................................................231
24.6 Two-Wire Serial Interface ..............................................................................233
24.7 Analog to Digital Converter ............................................................................234
24.8 Analog Comparator .......................................................................................235
24.9 Temperature Sensor ......................................................................................235
24.10 Parallel Programming ....................................................................................235
24.11 Serial Programming .......................................................................................238
25 Electrical Characteristics @ 105C .....................................................239
25.1 Absolute Maximum Ratings* .........................................................................239
25.2 DC Characteristics .........................................................................................239
25.3 Clock ..............................................................................................................240
25.4 System and Reset .........................................................................................241
26 Typical Characteristics ........................................................................242
26.1 Current Consumption in Active Mode ............................................................242
26.2 Current Consumption in Idle Mode ................................................................245ATtiny1634 [DATASHEET] vi
Atmel-8303HS-AVR-ATtiny1634-Datasheet_02/2014
26.3 Current Consumption in Standby Mode ........................................................247
26.4 Current Consumption in Power-down Mode ..................................................248
26.5 Current Consumption in Reset ......................................................................249
26.6 Current Consumption of Peripheral Units ......................................................250
26.7 Pull-up Resistors ...........................................................................................253
26.8 Input Thresholds ............................................................................................256
26.9 Output Driver Strength ...................................................................................259
26.10 BOD ...............................................................................................................265
26.11 Bandgap Voltage ...........................................................................................268
26.12 Reset .............................................................................................................269
26.13 Analog Comparator Offset .............................................................................271
26.14 Internal Oscillator Speed ...............................................................................272
27 Register Summary ................................................................................276
28 Instruction Set Summary .....................................................................278
29 Ordering Information ...........................................................................280
29.1 ATtiny1634 ....................................................................................................280
30 Packaging Information .........................................................................281
30.1 20M1 ..............................................................................................................281
30.2 20S2 ..............................................................................................................282
31 Errata .....................................................................................................283
31.1 ATtiny1634 ....................................................................................................283
32 Datasheet Revision History .................................................................284
32.1 Rev. 8303H – 02/2014 ...................................................................................284
32.2 Rev. 8303G – 11/2013 ..................................................................................284
32.3 Rev. 8303F – 08/2013 ...................................................................................284
32.4 Rev. 8303E – 01/2013 ...................................................................................284
32.5 Rev. 8303D – 06/12 .......................................................................................284
32.6 Rev. 8303C – 03/12 .......................................................................................284
32.7 Rev. 8303B – 03/12 .......................................................................................284
32.8 Rev. 8303A – 11/11 .......................................................................................285
Table of Contents.......................................................................................iX X X X X X
Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com
© 2014 Atmel Corporation. / Rev.: Atmel-8303H-AVR-ATtiny1634-Datasheet_02/2014.
Atmel®, Atmel logo and combinations thereof, and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product
names may be trademarks of others.
DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right
is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE
ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT
SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES
FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this
document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information
contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended,
authorized, or warranted for use as components in applications intended to support or sustain life.
SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in connection with any applications where
the failure of such products would reasonably be expected to result in significant personal injury or death (“Safety-Critical Applications”) without an Atmel officer's specific written
consent. Safety-Critical Applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems.
Atmel products are not designed nor intended for use in military or aerospace applications or environments unless specifically designated by Atmel as military-grade. Atmel products are
not designed nor intended for use in automotive applications unless specifically designated by Atmel as automotive-grade.
Features
• High Performance, Low Power Atmel®AVR® 8-Bit Microcontroller
• Advanced RISC Architecture
– 130 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 16 MIPS Throughput at 16MHz
– On-Chip 2-cycle Multiplier
• High Endurance Non-volatile Memory Segments
– In-System Self-programmable Flash Program Memory
• 32KBytes (ATmega329/ATmega3290)
• 64KBytes (ATmega649/ATmega6490)
– EEPROM
• 1Kbytes (ATmega329/ATmega3290)
• 2Kbytes (ATmega649/ATmega6490)
– Internal SRAM
• 2Kbytes (ATmega329/ATmega3290)
• 4Kbytes (ATmega649/ATmega6490)
– Write/Erase Cycles: 10,000 Flash/ 100,000 EEPROM
– Data retention: 20 years at 85°C/100 years at 25°C(1)
– Optional Boot Code Section with Independent Lock Bits
• In-System Programming by On-chip Boot Program
• True Read-While-Write Operation
– Programming Lock for Software Security
• JTAG (IEEE std. 1149.1 compliant) Interface
– Boundary-scan Capabilities According to the JTAG Standard
– Extensive On-chip Debug Support
– Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface
• Peripheral Features
– 4 x 25 Segment LCD Driver (ATmega329/ATmega649)
– 4 x 40 Segment LCD Driver (ATmega3290/ATmega6490)
– Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode
– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture
Mode
– Real Time Counter with Separate Oscillator
– Four PWM Channels
– 8-channel, 10-bit ADC
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Universal Serial Interface with Start Condition Detector
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
– Interrupt and Wake-up on Pin Change
• Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated Oscillator
– External and Internal Interrupt Sources
– Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and
Standby
• I/O and Packages
– 53/68 Programmable I/O Lines
– 64-lead TQFP, 64-pad QFN/MLF, and 100-lead TQFP
• Speed Grade:
– ATmega329V/ATmega3290V/ATmega649V/ATmega6490V:
– 0 - 4MHz @ 1.8 - 5.5V, 0 - 8MHz @ 2.7 - 5.5V
– ATmega329/3290/649/6490:
– 0 - 8MHz @ 2.7 - 5.5V, 0 - 16MHz @ 4.5 - 5.5V
• Temperature range:
– -40°C to 85°C Industrial
• Ultra-Low Power Consumption
– Active Mode:
• 1MHz, 1.8V: 350µA
• 32kHz, 1.8V: 20µA (including Oscillator)
• 32kHz, 1.8V: 40µA (including Oscillator and LCD)
– Power-down Mode:
• 100nA at 1.8V
8-bit Atmel
Microcontroller
with In-System
Programmable
Flash
ATmega329/V
ATmega3290/V
ATmega649/V
ATmega6490/V
2552K–AVR–04/112
2552K–AVR–04/11
ATmega329/3290/649/6490
1. Pin Configurations
Figure 1-1. Pinout ATmega3290/6490 (OC2A/PCINT15) PB7 DNC (T1/SEG33) PG3 (T0/SEG32) PG4 RESET/PG5
VCC
GND
(TOSC2) XTAL2
(TOSC1) XTAL1
DNC
DNC
(PCINT26/SEG31) PJ2
(PCINT27/SEG30) PJ3
(PCINT28/SEG29) PJ4
(PCINT29/SEG28) PJ5
(PCINT30/SEG27) PJ6
DNC
(ICP1/SEG26) PD0
(INT0/SEG25) PD1
(SEG24) PD2
(SEG23) PD3
(SEG22) PD4
(SEG21) PD5
(SEG20) PD6
(SEG19) PD7
AVCC
AGND
AREF
PF0 (ADC0)
PF1 (ADC1)
PF2 (ADC2)
PF3 (ADC3)
PF4 (ADC4/TCK)
PF5 (ADC5/TMS)
PF6 (ADC6/TDO)
PF7 (ADC7/TDI)
DNC
DNC
PH7 (PCINT23/SEG36)
PH6 (PCINT22/SEG37)
PH5 (PCINT21/SEG38)
PH4 (PCINT20/SEG39)
DNC
DNC
GND
VCC
DNC
PA0 (COM0)
PA1 (COM1)
PA2 (COM2)
PA3 (COM3)
PA4 (SEG0)
PA5 (SEG1)
PA6 (SEG2)
PA7 (SEG3)
PG2 (SEG4)
PC7 (SEG5)
PC6 (SEG6)
DNC
PH3 (PCINT19/SEG7)
PH2 (PCINT18/SEG8)
PH1 (PCINT17/SEG9)
PH0 (PCINT16/SEG10)
DNC
DNC
DNC
DNC
PC5 (SEG11)
PC4 (SEG12)
PC3 (SEG13)
PC2 (SEG14)
PC1 (SEG15)
PC0 (SEG16)
PG1 (SEG17)
PG0 (SEG18)
INDEX CORNER
ATmega3290/6490
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
75
74
73
72
71
70
69
68
67
66
65
64
63
62
61
60
59
58
57
56
55
54
53
52
51
100
99
98
97
96
95
94
93
92
91
90
89
88
87
86
85
84
83
82
81
80
79
78
77
76
LCDCAP
(RXD/PCINT0) PE0
(TXD/PCINT1) PE1
(XCK/AIN0/PCINT2) PE2
(AIN1/PCINT3) PE3
(USCK/SCL/PCINT4) PE4
(DI/SDA/PCINT5) PE5
(DO/PCINT6) PE6
(CLKO/PCINT7) PE7
VCC
GND
DNC
(PCINT24/SEG35) PJ0
(PCINT25/SEG34) PJ1
DNC
DNC
DNC
DNC
(SS/PCINT8) PB0
(SCK/PCINT9) PB1
(MOSI/PCINT10) PB2
(MISO/PCINT11) PB3
(OC0A/PCINT12) PB4
(OC1A/PCINT13) PB5
(OC1B/PCINT14) PB6
TQFP3
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 1-2. Pinout ATmega329/649
Note: The large center pad underneath the QFN/MLF packages is made of metal and internally connected
to GND. It should be soldered or glued to the board to ensure good mechanical stability. If
the center pad is left unconnected, the package might loosen from the board.
PC0 (SEG12)
VCC
A
GND
AREF
PF0 (ADC0)
PF1 (ADC1)
PF2 (ADC2)
PF3 (ADC3)
PF4 (ADC4/TCK)
PF5 (ADC5/TMS)
PF6 (ADC6/TDO)
PF7 (ADC7/TDI)
GND
VCC 17
61
60
18
59
20
58
19
21
57
22
56
23
55
24
54
25
53
26
52
27
51
28
29
50
49
30
31
32
(RXD/PCINT0) PE0
(TXD/PCINT1) PE1
LCDCAP
(XCK/AIN0/PCINT2) PE2
(AIN1/PCINT3) PE3
(USCK/SCL/PCINT4) PE4
(DI/SDA/PCINT5) PE5
(DO/PCINT6) PE6
(CLKO/PCINT7) PE7
(SCK/PCINT9) PB1
(MOSI/PCINT10) PB2
(MISO/PCINT11) PB3
(OC0A/PCINT12) PB4
(OC2A/PCINT15) PB7
(T1/SEG24) PG3
(OC1B/PCINT14) PB6
(T0/SEG23) PG4
(OC1A/PCINT13) PB5
PC1 (SEG11)
PG0 (SEG14)
(SEG15) PD7
PC2 (SEG10)
PC3 (SEG9)
PC4 (SEG8)
PC5 (SEG7)
PC6 (SEG6)
PC7 (SEG5)
PA7 (SEG3)
PG2 (SEG4)
PA6 (SEG2)
PA5 (SEG1)
PA4 (SEG0)
PA3 (COM3)
PA0 (COM0)
PA1 (COM1)
PA2 (COM2)
PG1 (SEG13)
(SEG19) PD3
(SEG18) PD4
(SEG17) PD5
(SEG16) PD6
(SEG20) PD2
(ICP1/SEG22) PD0
(INT0/SEG21) PD1
(TOSC2) XTAL2
(TOSC1) XTAL1
RESET/PG5
V
GND
CC
INDEX CORNER
(SS/PCINT8) PB0
2
3
1
4
5
6
7
8
9
10
11
12
13
14
16
15
64
63
62
47
46
48
45
44
43
42
41
40
39
38
37
36
35
33
34
ATmega329/6494
2552K–AVR–04/11
ATmega329/3290/649/6490
2. Overview
The ATmega329/3290/649/6490 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture.
By executing powerful instructions in a single clock cycle, the ATmega329/3290/649/6490 achieves throughputs
approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.
2.1 Block Diagram
Figure 2-1. Block Diagram
PROGRAM
COUNTER
INTERNAL
OSCILLATOR
WATCHDOG
TIMER
STACK
POINTER
PROGRAM
FLASH
MCU CONTROL
REGISTER SRAM
GENERAL
PURPOSE
REGISTERS
INSTRUCTION
REGISTER
TIMER/
COUNTERS
INSTRUCTION
DECODER
DATA DIR.
REG. PORTB
DATA DIR.
REG. PORTE
DATA DIR.
REG. PORTA
DATA DIR.
REG. PORTD
DATA REGISTER
PORTB
DATA REGISTER
PORTE
DATA REGISTER
PORTA
DATA REGISTER
PORTD
TIMING AND
CONTROL
OSCILLATOR
INTERRUPT
UNIT
EEPROM
USART SPI
STATUS
REGISTER
Z
Y
X
ALU
PORTE DRIVERS PORTB DRIVERS
PORTF DRIVERS PORTA DRIVERS
PORTD DRIVERS
PORTC DRIVERS
PE0 - PE7 PB0 - PB7
PF0 - PF7 PA0 - PA7 GND VCC
XTAL1
XTAL2
CONTROL
LINES
+
-
ANALOG
COMPARATOR
PC0 - PC7
8-BIT DATA BUS
RESET
CALIB. OSC
DATA DIR.
REG. PORTC
DATA REGISTER
PORTC
ON-CHIP DEBUG
JTAG TAP
PROGRAMMING
LOGIC
BOUNDARYSCAN
DATA DIR.
REG. PORTF
DATA REGISTER
PORTF
ADC
PD0 - PD7
DATA DIR.
REG. PORTG
DATA REG.
PORTG
PORTG DRIVERS
PG0 - PG4
AGND
AREF
AVCC
UNIVERSAL
SERIAL INTERFACE
AVR CPU
LCD
CONTROLLER/
DRIVER
PORTH DRIVERS
PH0 - PH7
DATA DIR.
REG. PORTH
DATA REGISTER
PORTH
PORTJ DRIVERS
PJ0 - PJ6
DATA DIR.
REG. PORTJ
DATA REGISTER
PORTJ5
2552K–AVR–04/11
ATmega329/3290/649/6490
The Atmel® AVR® core combines a rich instruction set with 32 general purpose working registers.
All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two
independent registers to be accessed in one single instruction executed in one clock cycle. The
resulting architecture is more code efficient while achieving throughputs up to ten times faster
than conventional CISC microcontrollers.
The Atmel ATmega329/3290/649/6490 provides the following features: 32/64K bytes of In-System
Programmable Flash with Read-While-Write capabilities, 1/2K bytes EEPROM, 2/4K byte
SRAM, 54/69 general purpose I/O lines, 32 general purpose working registers, a JTAG interface
for Boundary-scan, On-chip Debugging support and programming, a complete On-chip LCD
controller with internal contrast control, three flexible Timer/Counters with compare modes, internal
and external interrupts, a serial programmable USART, Universal Serial Interface with Start
Condition Detector, an 8-channel, 10-bit ADC, a programmable Watchdog Timer with internal
Oscillator, an SPI serial port, and five software selectable power saving modes. The Idle mode
stops the CPU while allowing the SRAM, Timer/Counters, SPI port, and interrupt system to continue
functioning. The Power-down mode saves the register contents but freezes the Oscillator,
disabling all other chip functions until the next interrupt or hardware reset. In Power-save mode,
the asynchronous timer and the LCD controller continues to run, allowing the user to maintain a
timer base and operate the LCD display while the rest of the device is sleeping. The ADC Noise
Reduction mode stops the CPU and all I/O modules except asynchronous timer, LCD controller
and ADC, to minimize switching noise during ADC conversions. In Standby mode, the crystal/resonator
Oscillator is running while the rest of the device is sleeping. This allows very fast
start-up combined with low-power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The
On-chip In-System re-Programmable (ISP) Flash allows the program memory to be reprogrammed
In-System through an SPI serial interface, by a conventional non-volatile memory
programmer, or by an On-chip Boot program running on the AVR core. The Boot program can
use any interface to download the application program in the Application Flash memory. Software
in the Boot Flash section will continue to run while the Application Flash section is updated,
providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System
Self-Programmable Flash on a monolithic chip, the Atmel ATmega329/3290/649/6490 is a powerful
microcontroller that provides a highly flexible and cost effective solution to many embedded
control applications.
The Atmel ATmega329/3290/649/6490 is supported with a full suite of program and system
development tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators,
In-Circuit Emulators, and Evaluation kits.6
2552K–AVR–04/11
ATmega329/3290/649/6490
2.2 Comparison between ATmega329, ATmega3290, ATmega649 and ATmega6490
The ATmega329, ATmega3290, ATmega649, and ATmega6490 differs only in memory sizes,
pin count and pinout. Table 2-1 on page 6 summarizes the different configurations for the four
devices.
2.3 Pin Descriptions
The following section describes the I/O-pin special functions.
2.3.1 VCC
Digital supply voltage.
2.3.2 GND
Ground.
2.3.3 Port A (PA7..PA0)
Port A is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port A output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port A pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port A pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port A also serves the functions of various special features of the ATmega329/3290/649/6490
as listed on page 67.
2.3.4 Port B (PB7..PB0)
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port B has better driving capabilities than the other ports.
Port B also serves the functions of various special features of the ATmega329/3290/649/6490
as listed on page 68.
Table 2-1. Configuration Summary
Device Flash EEPROM RAM
LCD
Segments
General Purpose
I/O Pins
ATmega329 32Kbytes 1Kbytes 2Kbytes 4 x 25 54
ATmega3290 32Kbytes 1K bytes 2Kbytes 4 x 40 69
ATmega649 64Kbytes 2Kbytes 4Kbytes 4 x 25 54
ATmega6490 64Kbytes 2Kbytes 4Kbytes 4 x 40 697
2552K–AVR–04/11
ATmega329/3290/649/6490
2.3.5 Port C (PC7..PC0)
Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port C output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port C also serves the functions of special features of the ATmega329/3290/649/6490 as listed
on page 71.
2.3.6 Port D (PD7..PD0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port D also serves the functions of various special features of the ATmega329/3290/649/6490
as listed on page 73.
2.3.7 Port E (PE7..PE0)
Port E is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port E output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port E pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port E also serves the functions of various special features of the ATmega329/3290/649/6490
as listed on page 75.
2.3.8 Port F (PF7..PF0)
Port F serves as the analog inputs to the A/D Converter.
Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port pins
can provide internal pull-up resistors (selected for each bit). The Port F output buffers have symmetrical
drive characteristics with both high sink and source capability. As inputs, Port F pins
that are externally pulled low will source current if the pull-up resistors are activated. The Port F
pins are tri-stated when a reset condition becomes active, even if the clock is not running. If the
JTAG interface is enabled, the pull-up resistors on pins PF7(TDI), PF5(TMS), and PF4(TCK) will
be activated even if a reset occurs.
Port F also serves the functions of the JTAG interface.8
2552K–AVR–04/11
ATmega329/3290/649/6490
2.3.9 Port G (PG5..PG0)
Port G is a 6-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port G output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port G pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port G pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port G also serves the functions of various special features of the ATmega329/3290/649/6490
as listed on page 75.
2.3.10 Port H (PH7..PH0)
Port H is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port H output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port H pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port H pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port H also serves the functions of various special features of the ATmega3290/6490 as listed
on page 75.
2.3.11 Port J (PJ6..PJ0)
Port J is a 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port J output buffers have symmetrical drive characteristics with both high sink and source capability.
As inputs, Port J pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port J pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port J also serves the functions of various special features of the ATmega3290/6490 as listed on
page 75.
2.3.12 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running. The minimum pulse length is given in “System and Reset
Characteristics” on page 330. Shorter pulses are not guaranteed to generate a reset.
2.3.13 XTAL1
Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.
2.3.14 XTAL2
Output from the inverting Oscillator amplifier.
2.3.15 AVCC
AVCC is the supply voltage pin for Port F and the A/D Converter. It should be externally connected
to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC
through a low-pass filter.
2.3.16 AREF
This is the analog reference pin for the A/D Converter.9
2552K–AVR–04/11
ATmega329/3290/649/6490
2.3.17 LCDCAP
An external capacitor (typical > 470nF) must be connected to the LCDCAP pin as shown in Figure
23-2. This capacitor acts as a reservoir for LCD power (VLCD). A large capacitance reduces
ripple on VLCD but increases the time until VLCD reaches its target value.
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
Note: 1.
4. Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.
5. About Code Examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is included before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.
For I/O Registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically
“LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.10
2552K–AVR–04/11
ATmega329/3290/649/6490
6. AVR CPU Core
6.1 Overview
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
6.2 Architectural Overview
Figure 6-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
I/O Module 2
I/O Module1
I/O Module n11
2552K–AVR–04/11
ATmega329/3290/649/6490
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format.
Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the
ATmega329/3290/649/6490 has Extended I/O space from 0x60 - 0xFF in SRAM where only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
6.3 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.12
2552K–AVR–04/11
ATmega329/3290/649/6490
6.4 AVR Status Register
The Status Register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.
6.4.1 SREG – AVR Status Register
The AVR Status Register – SREG – is defined as:
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination
for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N ⊕ V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
Bit 7 6 5 4 3 2 1 0
0x3F (0x5F) I T H S V N Z C SREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 013
2552K–AVR–04/11
ATmega329/3290/649/6490
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
6.5 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 6-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 6-2. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 6-2, each register is also assigned a data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte14
2552K–AVR–04/11
ATmega329/3290/649/6490
6.5.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 6-3.
Figure 6-3. The X-, Y-, and Z-registers
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
6.6 Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x60. The Stack Pointer is decremented by one when data is pushed onto the Stack
with the PUSH instruction, and it is decremented by two when the return address is pushed onto
the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is
popped from the Stack with the POP instruction, and it is incremented by two when data is
popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations
of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
15 XH XL 0
X-register 7 07 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 07 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 70 7 0
R31 (0x1F) R30 (0x1E)
Bit 15 14 13 12 11 10 9 8
0x3E (0x5E) SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
0000000015
2552K–AVR–04/11
ATmega329/3290/649/6490
6.7 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the
chip. No internal clock division is used.
Figure 6-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 6-4. The Parallel Instruction Fetches and Instruction Executions
Figure 6-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Figure 6-5. Single Cycle ALU Operation
6.8 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate program vector in the program memory space. All interrupts are
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt. Depending on the Program
Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12
are programmed. This feature improves software security. See the section “Memory Programming”
on page 293 for details.
The lowest addresses in the program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 49. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU16
2552K–AVR–04/11
ATmega329/3290/649/6490
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request
0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL
bit in the MCU Control Register (MCUCR). Refer to “Interrupts” on page 49 for more information.
The Reset Vector can also be moved to the start of the Boot Flash section by programming the
BOOTRST Fuse, see “Boot Loader Support – Read-While-Write Self-Programming” on page
278.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s)
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt
Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMWE ; start EEPROM write
sbi EECR, EEWE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
__disable_interrupt();
EECR |= (1< xxx
;
.org 0x3802/0x7802
0x3804/0x7804 jmp EXT_INT0 ; IRQ0 Handler
0x3806/0x7806 jmp PCINT0 ; PCINT0 Handler
... ... ... ;
0x1C2C jmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST Fuse is programmed and the Boot section size set to 4K bytes, the most
typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
.org 0x0002
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x002
2
jmp USI_OVF ; USI Overflow Handler
0x002
4
jmp ANA_COMP ; Analog Comparator Handler
0x002
6
jmp ADC ; ADC Conversion Complete
Handler
0x002
8
jmp EE_RDY ; EEPROM Ready Handler
0x002
A
jmp SPM_RDY ; SPM Ready Handler
0x002
C
jmp LCD_SOF ; LCD Start of Frame Handler
0x002
E
jmp PCINT2 ; PCINT2 Handler
0x003
0
jmp PCINT3 ; PCINT3 Handler
;
0x003
2
RESET
:
ldi r16,
high(RAMEND)
; Main program start
0x003
3
out SPH,r16 ; Set Stack Pointer to top of
RAM
0x003
4
ldi r16, low(RAMEND)
0x003
5
out SPL,r16
0x003
6
sei ; Enable interrupts
0x003
7
xxx
... ... ...52
2552K–AVR–04/11
ATmega329/3290/649/6490
0x0004 jmp PCINT0 ; PCINT0 Handler
... ... ... ;
0x002C jmp SPM_RDY ; Store Program Memory Ready Handler
;
.org 0x3800/0x7800
0x3800/0x7801RESET:ldir16,high(RAMEND); Main program start
0x3801/0x7801 out SPH,r16 ; Set Stack Pointer to top of RAM
0x3802/0x7802 ldi r16,low(RAMEND)
0x3803/0x7803 out SPL,r16
0x3804/0x7804 sei ; Enable interrupts
0x3805/0x7805 xxx
When the BOOTRST Fuse is programmed, the Boot section size set to 4K bytes and the IVSEL
bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general
program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
;
.org 0x3800/0x7800
0x3800/0x7800 jmp RESET ; Reset handler
0x3802/0x7802 jmp EXT_INT0 ; IRQ0 Handler
0x3804/0x7804 jmp PCINT0 ; PCINT0 Handler
... ... ... ;
0x382C/0x782C jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x382E/0x782ERESET:ldir16,high(RAMEND); Main program start
0x382F/0x782F out SPH,r16 ; Set Stack Pointer to top of RAM
0x3830/0x7830 ldi r16,low(RAMEND)
0x3831/0x7831 out SPL,r16
0x3832/0x7832 sei ; Enable interrupts
0x3833/0x7833 xxx
11.1.1 Moving Interrupts Between Application and Boot Space
The MCU Control Register controls the placement of the Interrupt Vector table.
11.2 Register Description
11.2.1 MCUCR – MCU Control Register
• Bit 1 – IVSEL: Interrupt Vector Select
When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash
memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot
Loader section of the Flash. The actual address of the start of the Boot Flash Section is determined
by the BOOTSZ Fuses. Refer to the section “Boot Loader Support – Read-While-Write
Bit 7 6 5 4 3 2 1 0
0x35 (0x55) JTD – – PUD – – IVSEL IVCE MCUCR
Read/Write R/W R R R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 053
2552K–AVR–04/11
ATmega329/3290/649/6490
Self-Programming” on page 278 for details. To avoid unintentional changes of Interrupt Vector
tables, a special write procedure must be followed to change the IVSEL bit:
1. Write the Interrupt Vector Change Enable (IVCE) bit to one.
2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled
in the cycle IVCE is set, and they remain disabled until after the instruction following the write to
IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status
Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed,
interrupts are disabled while executing from the Application section. If Interrupt Vectors are placed
in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while
executing from the Boot Loader section. Refer to the section “Boot Loader Support – Read-WhileWrite
Self-Programming” on page 278 for details on Boot Lock bits.
• Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by
hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable
interrupts, as explained in the IVSEL description above. See Code Example below.
Assembly Code Example
Move_interrupts:
;Get MCUCR
in r16, MCUCR
mov r17, r16
; Enable change of Interrupt Vectors
ori r16, (1< CSn2:0 > 1). The number of system clock
cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution.
However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
15.0.3 External Clock Source
An external clock source applied to the T1/T0 pin can be used as Timer/Counter clock
(clkT1/clkT0). The T1/T0 pin is sampled once every system clock cycle by the pin synchronization
logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 15-1
shows a functional equivalent block diagram of the T1/T0 synchronization and edge detector
logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch
is transparent in the high period of the internal system clock.
The edge detector generates one clkT1/clkT0 pulse for each positive (CSn2:0 = 7) or negative
(CSn2:0 = 6) edge it detects.
Figure 15-1. T1/T0 Pin Sampling
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T1/T0 pin to the counter is updated.
Tn_sync
(To Clock
Select Logic)
Synchronization Edge Detector
D Q D Q
LE
Tn D Q
clkI/O108
2552K–AVR–04/11
ATmega329/3290/649/6490
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least
one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system
clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency
(Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 15-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 15-1.
15.1 Register Description
15.1.1 GTCCR – General Timer/Counter Control Register
• Bit 7 – TSM: Timer/Counter Synchronization Mode
Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the
value that is written to the PSR2 and PSR10 bits is kept, hence keeping the corresponding prescaler
reset signals asserted. This ensures that the corresponding Timer/Counters are halted and
can be configured to the same value without the risk of one of them advancing during configuration.
When the TSM bit is written to zero, the PSR2 and PSR10 bits are cleared by hardware,
and the Timer/Counters start counting simultaneously.
• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0
PSR10
Clear
clkT1 clkT0
T1
T0
clkI/O
Synchronization
Synchronization
Bit 7 6 5 4 3 2 1 0
0x23 (0x43) TSM – – – – – PSR2 PSR10 GTCCR
Read/Write R/W R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0109
2552K–AVR–04/11
ATmega329/3290/649/6490
When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally
cleared immediately by hardware, except if the TSM bit is set. Note that Timer/Counter1
and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both
timers.110
2552K–AVR–04/11
ATmega329/3290/649/6490
16. 16-bit Timer/Counter1
16.1 Features
The 16-bit Timer/Counter unit allows accurate program execution timing (event management),
wave generation, and signal timing measurement. The main features are:
• True 16-bit Design (i.e., Allows 16-bit PWM)
• Two independent Output Compare Units
• Double Buffered Output Compare Registers
• One Input Capture Unit
• Input Capture Noise Canceler
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• External Event Counter
• Four independent interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)
16.2 Overview
Most register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit.
However, when using the register or bit defines in a program, the precise form must be used,
i.e., TCNT1 for accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 16-1. For the actual
placement of I/O pins, refer to “Pinout ATmega3290/6490” on page 2. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit
locations are listed in the “Register Description” on page 132.
The PRTIM1 bit in “Power Reduction Register” on page 37 must be written to zero to enable the
Timer/Counter1 module.111
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 16-1. 16-bit Timer/Counter Block Diagram(1)
Note: 1. Refer to Figure 1-1 on page 2, Table 13-5 on page 68, and Table 13-11 on page 72 for
Timer/Counter1 pin placement and description.
16.2.1 Registers
The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Register
(ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16-
bit registers. These procedures are described in the section “Accessing 16-bit Registers” on
page 113. The Timer/Counter Control Registers (TCCR1A/B) are 8-bit registers and have no
CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all
visible in the Timer Interrupt Flag Register (TIFR1). All interrupts are individually masked with
the Timer Interrupt Mask Register (TIMSK1). TIFR1 and TIMSK1 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the T1 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the Clock Select logic is referred to as the timer clock (clkT1).
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter
value at all time. The result of the compare can be used by the Waveform Generator to
generate a PWM or variable frequency output on the Output Compare pin (OC1A/B). See “OutClock
Select
Timer/Counter
DATA BUS
OCRnA
OCRnB
ICRn
=
=
TCNTn
Waveform
Generation
Waveform
Generation
OCnA
OCnB
Noise
Canceler
ICPn
=
Fixed
TOP
Values
Edge
Detector
Control Logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(Int.Req.)
OCnA
(Int.Req.)
OCnB
(Int.Req.)
ICFn (Int.Req.)
TCCRnA TCCRnB
( From Analog
Comparator Ouput )
Tn Edge
Detector
( From Prescaler )
clkTn112
2552K–AVR–04/11
ATmega329/3290/649/6490
put Compare Units” on page 119.. The compare match event will also set the Compare Match
Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request.
The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered)
event on either the Input Capture pin (ICP1) or on the Analog Comparator pins (See
“Analog Comparator” on page 207.) The Input Capture unit includes a digital filtering unit (Noise
Canceler) for reducing the chance of capturing noise spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined
by either the OCR1A Register, the ICR1 Register, or by a set of fixed values. When using
OCR1A as TOP value in a PWM mode, the OCR1A Register can not be used for generating a
PWM output. However, the TOP value will in this case be double buffered allowing the TOP
value to be changed in run time. If a fixed TOP value is required, the ICR1 Register can be used
as an alternative, freeing the OCR1A to be used as PWM output.
16.2.2 Definitions
The following definitions are used extensively throughout the section:
16.2.3 Compatibility
The 16-bit Timer/Counter has been updated and improved from previous versions of the 16-bit
AVR Timer/Counter. This 16-bit Timer/Counter is fully compatible with the earlier version
regarding:
• All 16-bit Timer/Counter related I/O Register address locations, including Timer Interrupt
Registers.
• Bit locations inside all 16-bit Timer/Counter Registers, including Timer Interrupt Registers.
• Interrupt Vectors.
The following control bits have changed name, but have same functionality and register location:
• PWM10 is changed to WGM10.
• PWM11 is changed to WGM11.
• CTC1 is changed to WGM12.
The following bits are added to the 16-bit Timer/Counter Control Registers:
• FOC1A and FOC1B are added to TCCR1C.
• WGM13 is added to TCCR1B.
The 16-bit Timer/Counter has improvements that will affect the compatibility in some special
cases.
Table 16-1. Definitions of Timer/Counter values.
BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).
TOP
The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be one of the fixed values:
0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCR1A or ICR1 Register.
The assignment is dependent of the mode of operation.113
2552K–AVR–04/11
ATmega329/3290/649/6490
16.3 Accessing 16-bit Registers
The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via
the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations.
Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit
access. The same temporary register is shared between all 16-bit registers within each 16-bit
timer. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a
16-bit register is written by the CPU, the high byte stored in the temporary register, and the low
byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of
a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary
register in the same clock cycle as the low byte is read.
Not all 16-bit accesses uses the temporary register for the high byte. Reading the OCR1A/B 16-
bit registers does not involve using the temporary register.
To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low
byte must be read before the high byte.
The following code examples show how to access the 16-bit Timer Registers assuming that no
interrupts updates the temporary register. The same principle can be used directly for accessing
the OCR1A/B and ICR1 Registers. Note that when using “C”, the compiler handles the 16-bit
access.
Note: 1. See “About Code Examples” on page 9.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt
occurs between the two instructions accessing the 16-bit register, and the interrupt code
updates the temporary register by accessing the same or any other of the 16-bit Timer Registers,
then the result of the access outside the interrupt will be corrupted. Therefore, when both
Assembly Code Examples(1)
...
; Set TCNT1 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT1H,r17
out TCNT1L,r16
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
...
C Code Examples(1)
unsigned int i;
...
/* Set TCNT1 to 0x01FF */
TCNT1 = 0x1FF;
/* Read TCNT1 into i */
i = TCNT1;
...114
2552K–AVR–04/11
ATmega329/3290/649/6490
the main code and the interrupt code update the temporary register, the main code must disable
the interrupts during the 16-bit access.
The following code examples show how to do an atomic read of the TCNT1 Register contents.
Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
Note: 1. See “About Code Examples” on page 9.
The assembly code example returns the TCNT1 value in the r17:r16 register pair.
Assembly Code Example(1)
TIM16_ReadTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
__disable_interrupt();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}115
2552K–AVR–04/11
ATmega329/3290/649/6490
The following code examples show how to do an atomic write of the TCNT1 Register contents.
Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
Note: 1. See “About Code Examples” on page 9.
The assembly code example requires that the r17:r16 register pair contains the value to be written
to TCNT1.
16.3.1 Reusing the Temporary High Byte Register
If writing to more than one 16-bit register where the high byte is the same for all registers written,
then the high byte only needs to be written once. However, note that the same rule of atomic
operation described previously also applies in this case.
Assembly Code Example(1)
TIM16_WriteTCNT1:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore global interrupt flag
out SREG,r18
ret
C Code Example(1)
void TIM16_WriteTCNT1( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
__disable_interrupt();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore global interrupt flag */
SREG = sreg;
}116
2552K–AVR–04/11
ATmega329/3290/649/6490
16.4 Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source
is selected by the Clock Select logic which is controlled by the Clock Select (CS12:0) bits
located in the Timer/Counter control Register B (TCCR1B). For details on clock sources and
prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 107.
16.5 Counter Unit
The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit.
Figure 16-2 shows a block diagram of the counter and its surroundings.
Figure 16-2. Counter Unit Block Diagram
Signal description (internal signals):
Count Increment or decrement TCNT1 by 1.
Direction Select between increment and decrement.
Clear Clear TCNT1 (set all bits to zero).
clkT1 Timer/Counter clock.
TOP Signalize that TCNT1 has reached maximum value.
BOTTOM Signalize that TCNT1 has reached minimum value (zero).
The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNT1H) containing
the upper eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight
bits. The TCNT1H Register can only be indirectly accessed by the CPU. When the CPU does an
access to the TCNT1H I/O location, the CPU accesses the high byte temporary register (TEMP).
The temporary register is updated with the TCNT1H value when the TCNT1L is read, and
TCNT1H is updated with the temporary register value when TCNT1L is written. This allows the
CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus.
It is important to notice that there are special cases of writing to the TCNT1 Register when the
counter is counting that will give unpredictable results. The special cases are described in the
sections where they are of importance.
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT1). The clkT1 can be generated from an external or internal clock source,
selected by the Clock Select bits (CS12:0). When no clock source is selected (CS12:0 = 0) the
timer is stopped. However, the TCNT1 value can be accessed by the CPU, independent of
TEMP (8-bit)
DATA BUS (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit) Control Logic
Count
Clear
Direction
TOVn
(Int.Req.)
Clock Select
TOP BOTTOM
Tn Edge
Detector
( From Prescaler )
clkTn117
2552K–AVR–04/11
ATmega329/3290/649/6490
whether clkT1 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the Waveform Generation mode bits
(WGM13:0) located in the Timer/Counter Control Registers A and B (TCCR1A and TCCR1B).
There are close connections between how the counter behaves (counts) and how waveforms
are generated on the Output Compare outputs OC1x. For more details about advanced counting
sequences and waveform generation, see “Modes of Operation” on page 123.
The Timer/Counter Overflow Flag (TOV1) is set according to the mode of operation selected by
the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt.
16.6 Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give
them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple
events, can be applied via the ICP1 pin or alternatively, via the analog-comparator unit. The
time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal
applied. Alternatively the time-stamps can be used for creating a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 16-3. The elements of
the block diagram that are not directly a part of the Input Capture unit are gray shaded. The
small “n” in register and bit names indicates the Timer/Counter number.
Figure 16-3. Input Capture Unit Block Diagram
When a change of the logic level (an event) occurs on the Input Capture pin (ICP1), alternatively
on the Analog Comparator output (ACO), and this change confirms to the setting of the edge
detector, a capture will be triggered. When a capture is triggered, the 16-bit value of the counter
(TCNT1) is written to the Input Capture Register (ICR1). The Input Capture Flag (ICF1) is set at
the same system clock as the TCNT1 value is copied into ICR1 Register. If enabled (ICIE1 = 1),
the Input Capture Flag generates an Input Capture interrupt. The ICF1 Flag is automatically
ICFn (Int.Req.)
Analog
Comparator
WRITE ICRn (16-bit Register)
ICRnH (8-bit)
Noise
Canceler
ICPn
Edge
Detector
TEMP (8-bit)
DATA BUS (8-bit)
ICRnL (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
ACO* ACIC* ICNC ICES118
2552K–AVR–04/11
ATmega329/3290/649/6490
cleared when the interrupt is executed. Alternatively the ICF1 Flag can be cleared by software
by writing a logical one to its I/O bit location.
Reading the 16-bit value in the Input Capture Register (ICR1) is done by first reading the low
byte (ICR1L) and then the high byte (ICR1H). When the low byte is read the high byte is copied
into the high byte temporary register (TEMP). When the CPU reads the ICR1H I/O location it will
access the TEMP Register.
The ICR1 Register can only be written when using a Waveform Generation mode that utilizes
the ICR1 Register for defining the counter’s TOP value. In these cases the Waveform Generation
mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1
Register. When writing the ICR1 Register the high byte must be written to the ICR1H I/O location
before the low byte is written to ICR1L.
For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 113.
16.6.1 Input Capture Trigger Source
The main trigger source for the Input Capture unit is the Input Capture pin (ICP1).
Timer/Counter1 can alternatively use the Analog Comparator output as trigger source for the
Input Capture unit. The Analog Comparator is selected as trigger source by setting the Analog
Comparator Input Capture (ACIC) bit in the Analog Comparator Control and Status Register
(ACSR). Be aware that changing trigger source can trigger a capture. The Input Capture Flag
must therefore be cleared after the change.
Both the Input Capture pin (ICP1) and the Analog Comparator output (ACO) inputs are sampled
using the same technique as for the T1 pin (Figure 15-1 on page 107). The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four system clock cycles. Note that the input of the
noise canceler and edge detector is always enabled unless the Timer/Counter is set in a Waveform
Generation mode that uses ICR1 to define TOP.
An Input Capture can be triggered by software by controlling the port of the ICP1 pin.
16.6.2 Noise Canceler
The noise canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC1) bit in
Timer/Counter Control Register B (TCCR1B). When enabled the noise canceler introduces additional
four system clock cycles of delay from a change applied to the input, to the update of the
ICR1 Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
16.6.3 Using the Input Capture Unit
The main challenge when using the Input Capture unit is to assign enough processor capacity
for handling the incoming events. The time between two events is critical. If the processor has
not read the captured value in the ICR1 Register before the next event occurs, the ICR1 will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture interrupt, the ICR1 Register should be read as early in the interrupt
handler routine as possible. Even though the Input Capture interrupt has relatively high119
2552K–AVR–04/11
ATmega329/3290/649/6490
priority, the maximum interrupt response time is dependent on the maximum number of clock
cycles it takes to handle any of the other interrupt requests.
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is
actively changed during operation, is not recommended.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensing must be done as early as possible after the ICR1
Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the clearing of the ICF1 Flag is not required (if an interrupt handler is used).
16.7 Output Compare Units
The 16-bit comparator continuously compares TCNT1 with the Output Compare Register
(OCR1x). If TCNT equals OCR1x the comparator signals a match. A match will set the Output
Compare Flag (OCF1x) at the next timer clock cycle. If enabled (OCIE1x = 1), the Output Compare
Flag generates an Output Compare interrupt. The OCF1x Flag is automatically cleared
when the interrupt is executed. Alternatively the OCF1x Flag can be cleared by software by writing
a logical one to its I/O bit location. The Waveform Generator uses the match signal to
generate an output according to operating mode set by the Waveform Generation mode
(WGM13:0) bits and Compare Output mode (COM1x1:0) bits. The TOP and BOTTOM signals
are used by the Waveform Generator for handling the special cases of the extreme values in
some modes of operation (See “Modes of Operation” on page 123.)
A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (i.e.,
counter resolution). In addition to the counter resolution, the TOP value defines the period time
for waveforms generated by the Waveform Generator.
Figure 16-4 shows a block diagram of the Output Compare unit. The small “n” in the register and
bit names indicates the device number (n = 1 for Timer/Counter 1), and the “x” indicates Output
Compare unit (A/B). The elements of the block diagram that are not directly a part of the Output
Compare unit are gray shaded.120
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 16-4. Output Compare Unit, Block Diagram
The OCR1x Register is double buffered when using any of the twelve Pulse Width Modulation
(PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the
double buffering is disabled. The double buffering synchronizes the update of the OCR1x Compare
Register to either TOP or BOTTOM of the counting sequence. The synchronization
prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output
glitch-free.
The OCR1x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR1x Buffer Register, and if double buffering is disabled
the CPU will access the OCR1x directly. The content of the OCR1x (Buffer or Compare)
Register is only changed by a write operation (the Timer/Counter does not update this register
automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the high byte
temporary register (TEMP). However, it is a good practice to read the low byte first as when
accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Register
since the compare of all 16 bits is done continuously. The high byte (OCR1xH) has to be
written first. When the high byte I/O location is written by the CPU, the TEMP Register will be
updated by the value written. Then when the low byte (OCR1xL) is written to the lower eight bits,
the high byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x Compare
Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 113.
16.7.1 Force Output Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC1x) bit. Forcing compare match will not set the
OCF1x Flag or reload/clear the timer, but the OC1x pin will be updated as if a real compare
match had occurred (the COM11:0 bits settings define whether the OC1x pin is set, cleared or
toggled).
OCFnx (Int.Req.)
= (16-bit Comparator )
OCRnx Buffer (16-bit Register)
OCRnxH Buf. (8-bit)
OCnx
TEMP (8-bit)
DATA BUS (8-bit)
OCRnxL Buf. (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
WGMn3:0 COMnx1:0
OCRnx (16-bit Register)
OCRnxH (8-bit) OCRnxL (8-bit)
Waveform Generator
TOP
BOTTOM121
2552K–AVR–04/11
ATmega329/3290/649/6490
16.7.2 Compare Match Blocking by TCNT1 Write
All CPU writes to the TCNT1 Register will block any compare match that occurs in the next timer
clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the
same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled.
16.7.3 Using the Output Compare Unit
Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT1 when using any of the Output Compare
units, independent of whether the Timer/Counter is running or not. If the value written to TCNT1
equals the OCR1x value, the compare match will be missed, resulting in incorrect waveform
generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The
compare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly,
do not write the TCNT1 value equal to BOTTOM when the counter is counting down.
The setup of the OC1x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC1x value is to use the Force Output Compare
(FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COM1x1:0 bits are not double buffered together with the compare value.
Changing the COM1x1:0 bits will take effect immediately.122
2552K–AVR–04/11
ATmega329/3290/649/6490
16.8 Compare Match Output Unit
The Compare Output mode (COM1x1:0) bits have two functions. The Waveform Generator uses
the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next compare match.
Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 16-5 shows a simplified
schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers, I/O bits, and I/O
pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COM1x1:0 bits are shown. When referring to the
OC1x state, the reference is for the internal OC1x Register, not the OC1x pin. If a system reset
occur, the OC1x Register is reset to “0”.
Figure 16-5. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC1x) from the Waveform
Generator if either of the COM1x1:0 bits are set. However, the OC1x pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC1x pin (DDR_OC1x) must be set as output before the OC1x value is visible
on the pin. The port override function is generally independent of the Waveform Generation
mode, but there are some exceptions. Refer to Table 16-2, Table 16-3 and Table 16-4 for
details.
The design of the Output Compare pin logic allows initialization of the OC1x state before the output
is enabled. Note that some COM1x1:0 bit settings are reserved for certain modes of
operation. See “Register Description” on page 132.
The COM1x1:0 bits have no effect on the Input Capture unit.
PORT
DDR
D Q
D Q
OCnx
OCnx Pin
D Q Waveform
Generator
COMnx1
COMnx0
0
1
DATA BUS
FOCnx
clkI/O123
2552K–AVR–04/11
ATmega329/3290/649/6490
16.8.1 Compare Output Mode and Waveform Generation
The Waveform Generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM1x1:0 = 0 tells the Waveform Generator that no action on the
OC1x Register is to be performed on the next compare match. For compare output actions in the
non-PWM modes refer to Table 16-2 on page 132. For fast PWM mode refer to Table 16-3 on
page 133, and for phase correct and phase and frequency correct PWM refer to Table 16-4 on
page 133.
A change of the COM1x1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC1x strobe bits.
16.9 Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is
defined by the combination of the Waveform Generation mode (WGM13:0) and Compare Output
mode (COM1x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM1x1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM1x1:0 bits control whether the output should be set, cleared or toggle at a compare
match (See “Compare Match Output Unit” on page 122.)
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 130.
16.9.1 Normal Mode
The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the
BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOV1) will be set in
the same timer clock cycle as the TCNT1 becomes zero. The TOV1 Flag in this case behaves
like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow
interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be
written anytime.
The Input Capture unit is easy to use in Normal mode. However, observe that the maximum
interval between the external events must not exceed the resolution of the counter. If the interval
between events are too long, the timer overflow interrupt or the prescaler must be used to
extend the resolution for the capture unit.
The Output Compare units can be used to generate interrupts at some given time. Using the
Output Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
16.9.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register
are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when
the counter value (TCNT1) matches either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 =
12). The OCR1A or ICR1 define the top value for the counter, hence also its resolution. This124
2552K–AVR–04/11
ATmega329/3290/649/6490
mode allows greater control of the compare match output frequency. It also simplifies the operation
of counting external events.
The timing diagram for the CTC mode is shown in Figure 16-6. The counter value (TCNT1)
increases until a compare match occurs with either OCR1A or ICR1, and then counter (TCNT1)
is cleared.
Figure 16-6. CTC Mode, Timing Diagram
An interrupt can be generated at each time the counter value reaches the TOP value by either
using the OCF1A or ICF1 Flag according to the register used to define the TOP value. If the
interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However,
changing the TOP to a value close to BOTTOM when the counter is running with none or a
low prescaler value must be done with care since the CTC mode does not have the double buffering
feature. If the new value written to OCR1A or ICR1 is lower than the current value of
TCNT1, the counter will miss the compare match. The counter will then have to count to its maximum
value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
In many cases this feature is not desirable. An alternative will then be to use the fast PWM mode
using OCR1A for defining TOP (WGM13:0 = 15) since the OCR1A then will be double buffered.
For generating a waveform output in CTC mode, the OC1A output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COM1A1:0 = 1). The OC1A value will not be visible on the port pin unless the data direction for
the pin is set to output (DDR_OC1A = 1). The waveform generated will have a maximum frequency
of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). The waveform frequency is
defined by the following equation:
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x0000.
16.9.3 Fast PWM Mode
The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5, 6, 7, 14, or 15) provides a
high frequency PWM waveform generation option. The fast PWM differs from the other PWM
options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts
from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared
on the compare match between TCNT1 and OCR1x, and set at BOTTOM. In inverting Compare
TCNTn
OCnA
(Toggle)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4
(COMnA1:0 = 1)
f
OCnA
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnA = --------------------------------------------------125
2552K–AVR–04/11
ATmega329/3290/649/6490
Output mode output is set on compare match and cleared at BOTTOM. Due to the single-slope
operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct
and phase and frequency correct PWM modes that use dual-slope operation. This high
frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC
applications. High frequency allows physically small sized external components (coils, capacitors),
hence reduces total system cost.
The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or
OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum
resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be
calculated by using the following equation:
In fast PWM mode the counter is incremented until the counter value matches either one of the
fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 =
14), or the value in OCR1A (WGM13:0 = 15). The counter is then cleared at the following timer
clock cycle. The timing diagram for the fast PWM mode is shown in Figure 16-7. The figure
shows fast PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the
timing diagram shown as a histogram for illustrating the single-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1
slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will
be set when a compare match occurs.
Figure 16-7. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. In addition
the OC1A or ICF1 Flag is set at the same timer clock cycle as TOV1 is set when either OCR1A
or ICR1 is used for defining the TOP value. If one of the interrupts are enabled, the interrupt handler
routine can be used for updating the TOP and compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x.
Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCR1x Registers are written.
RFPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
TCNTn
OCRnx / TOP Update
and TOVn Interrupt Flag
Set and OCnA Interrupt
Flag Set or ICFn
Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4 5 6 7 8
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)126
2552K–AVR–04/11
ATmega329/3290/649/6490
The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP
value. The ICR1 Register is not double buffered. This means that if ICR1 is changed to a low
value when the counter is running with none or a low prescaler value, there is a risk that the new
ICR1 value written is lower than the current value of TCNT1. The result will then be that the
counter will miss the compare match at the TOP value. The counter will then have to count to the
MAX value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
The OCR1A Register however, is double buffered. This feature allows the OCR1A I/O location
to be written anytime. When the OCR1A I/O location is written the value written will be put into
the OCR1A Buffer Register. The OCR1A Compare Register will then be updated with the value
in the Buffer Register at the next timer clock cycle the TCNT1 matches TOP. The update is done
at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set.
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using
ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However,
if the base PWM frequency is actively changed (by changing the TOP value), using the OCR1A
as TOP is clearly a better choice due to its double buffer feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins.
Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM1x1:0 to three (see Table 16-3 on page 133). The actual
OC1x value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at
the compare match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register at
the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output
will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCR1x equal to TOP
will result in a constant high or low output (depending on the polarity of the output set by the
COM1x1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC1A to toggle its logical level on each compare match (COM1A1:0 = 1). This applies only
if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have
a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). This feature is
similar to the OC1A toggle in CTC mode, except the double buffer feature of the Output Compare
unit is enabled in the fast PWM mode.
16.9.4 Phase Correct PWM Mode
The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1, 2, 3,
10, or 11) provides a high resolution phase correct PWM waveform generation option. The
phase correct PWM mode is, like the phase and frequency correct PWM mode, based on a dualslope
operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from
TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is
cleared on the compare match between TCNT1 and OCR1x while counting up, and set on the
compare match while counting down. In inverting Output Compare mode, the operation is
f
OCnxPWM
f
clk_I/O
N ⋅ ( ) 1 + TOP = -----------------------------------127
2552K–AVR–04/11
ATmega329/3290/649/6490
inverted. The dual-slope operation has lower maximum operation frequency than single slope
operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes
are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode can be fixed to 8-, 9-, or 10-bit, or defined
by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to
0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution
in bits can be calculated by using the following equation:
In phase correct PWM mode the counter is incremented until the counter value matches either
one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1
(WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counter has then reached the
TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock
cycle. The timing diagram for the phase correct PWM mode is shown on Figure 16-8. The figure
shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1
value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The
diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on
the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt
Flag will be set when a compare match occurs.
Figure 16-8. Phase Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When
either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set accordingly
at the same timer clock cycle as the OCR1x Registers are updated with the double buffer
value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter
reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x.
RPCPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
OCRnx/TOP Update and
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TOVn Interrupt Flag Set
(Interrupt on Bottom)
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)128
2552K–AVR–04/11
ATmega329/3290/649/6490
Note that when using fixed TOP values, the unused bits are masked to zero when any of the
OCR1x Registers are written. As the third period shown in Figure 16-8 illustrates, changing the
TOP actively while the Timer/Counter is running in the phase correct mode can result in an
unsymmetrical output. The reason for this can be found in the time of update of the OCR1x Register.
Since the OCR1x update occurs at TOP, the PWM period starts and ends at TOP. This
implies that the length of the falling slope is determined by the previous TOP value, while the
length of the rising slope is determined by the new TOP value. When these two values differ the
two slopes of the period will differ in length. The difference in length gives the unsymmetrical
result on the output.
It is recommended to use the phase and frequency correct mode instead of the phase correct
mode when changing the TOP value while the Timer/Counter is running. When using a static
TOP value there are practically no differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the
OC1x pins. Setting the COM1x1:0 bits to two will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COM1x1:0 to three (See Table 1 on page 133).
The actual OC1x value will only be visible on the port pin if the data direction for the port pin is
set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x
Register at the compare match between OCR1x and TCNT1 when the counter increments, and
clearing (or setting) the OC1x Register at compare match between OCR1x and TCNT1 when
the counter decrements. The PWM frequency for the output when using phase correct PWM can
be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If
OCR1A is used to define the TOP value (WGM13:0 = 11) and COM1A1:0 = 1, the OC1A output
will toggle with a 50% duty cycle.
16.9.5 Phase and Frequency Correct PWM Mode
The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM
mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform
generation option. The phase and frequency correct PWM mode is, like the phase correct
PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM
(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the
Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x while
counting up, and set on the compare match while counting down. In inverting Compare Output
mode, the operation is inverted. The dual-slope operation gives a lower maximum operation frequency
compared to the single-slope operation. However, due to the symmetric feature of the
dual-slope PWM modes, these modes are preferred for motor control applications.
The main difference between the phase correct, and the phase and frequency correct PWM
mode is the time the OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 16-
8 and Figure 16-9).
f
OCnxPCPWM
f
clk_I/O
2 ⋅ ⋅ N TOP = ----------------------------129
2552K–AVR–04/11
ATmega329/3290/649/6490
The PWM resolution for the phase and frequency correct PWM mode can be defined by either
ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and
the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can
be calculated using the following equation:
In phase and frequency correct PWM mode the counter is incremented until the counter value
matches either the value in ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The
counter has then reached the TOP and changes the count direction. The TCNT1 value will be
equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency
correct PWM mode is shown on Figure 16-9. The figure shows phase and frequency correct
PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram
shown as a histogram for illustrating the dual-slope operation. The diagram includes noninverted
and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent
compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a
compare match occurs.
Figure 16-9. Phase and Frequency Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x
Registers are updated with the double buffer value (at BOTTOM). When either OCR1A or ICR1
is used for defining the TOP value, the OC1A or ICF1 Flag set when TCNT1 has reached TOP.
The Interrupt Flags can then be used to generate an interrupt each time the counter reaches the
TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x.
As Figure 16-9 shows the output generated is, in contrast to the phase correct mode, symmetrical
in all periods. Since the OCR1x Registers are updated at BOTTOM, the length of the rising
and the falling slopes will always be equal. This gives symmetrical output pulses and is therefore
frequency correct.
RPFCPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
OCRnx/TOP Updateand
TOVn Interrupt Flag Set
(Interrupt on Bottom)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)130
2552K–AVR–04/11
ATmega329/3290/649/6490
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using
ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However,
if the base PWM frequency is actively changed by changing the TOP value, using the OCR1A as
TOP is clearly a better choice due to its double buffer feature.
In phase and frequency correct PWM mode, the compare units allow generation of PWM waveforms
on the OC1x pins. Setting the COM1x1:0 bits to two will produce a non-inverted PWM and
an inverted PWM output can be generated by setting the COM1x1:0 to three (See Table 1 on
page 133). The actual OC1x value will only be visible on the port pin if the data direction for the
port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing)
the OC1x Register at the compare match between OCR1x and TCNT1 when the counter increments,
and clearing (or setting) the OC1x Register at compare match between OCR1x and
TCNT1 when the counter decrements. The PWM frequency for the output when using phase
and frequency correct PWM can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be set to high for noninverted
PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A
is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output will toggle
with a 50% duty cycle.
16.10 Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT1) is therefore shown as a
clock enable signal in the following figures. The figures include information on when Interrupt
Flags are set, and when the OCR1x Register is updated with the OCR1x buffer value (only for
modes utilizing double buffering). Figure 16-10 shows a timing diagram for the setting of OCF1x.
Figure 16-10. Timer/Counter Timing Diagram, Setting of OCF1x, no Prescaling
Figure 16-11 shows the same timing data, but with the prescaler enabled.
f
OCnxPFCPWM
f
clk_I/O
2 ⋅ ⋅ N TOP = ----------------------------
clkTn
(clkI/O/1)
OCFnx
clkI/O
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2131
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 16-11. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)
Figure 16-12 shows the count sequence close to TOP in various modes. When using phase and
frequency correct PWM mode the OCR1x Register is updated at BOTTOM. The timing diagrams
will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on.
The same renaming applies for modes that set the TOV1 Flag at BOTTOM.
Figure 16-12. Timer/Counter Timing Diagram, no Prescaling
Figure 16-13 shows the same timing data, but with the prescaler enabled.
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkTn
(clkI/O/1)
clkI/O132
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 16-13. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
16.11 Register Description
16.11.1 TCCR1A – Timer/Counter1 Control Register A
• Bit 7:6 – COM1A1:0: Compare Output Mode for Unit A
• Bit 5:4 – COM1B1:0: Compare Output Mode for Unit B
The COM1A1:0 and COM1B1:0 control the Output Compare pins (OC1A and OC1B respectively)
behavior. If one or both of the COM1A1:0 bits are written to one, the OC1A output
overrides the normal port functionality of the I/O pin it is connected to. If one or both of the
COM1B1:0 bit are written to one, the OC1B output overrides the normal port functionality of the
I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding
to the OC1A or OC1B pin must be set in order to enable the output driver.
When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is dependent
of the WGM13:0 bits setting. Table 16-2 shows the COM1x1:0 bit functionality when the
WGM13:0 bits are set to a Normal or a CTC mode (non-PWM).
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM)
TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
Bit 7 6 5 4 3 2 1 0
(0x80) COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 TCCR1A
Read/Write R/W R/W R/W R/W R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 16-2. Compare Output Mode, non-PWM
COM1A1/COM1B1 COM1A0/COM1B0 Description
0 0 Normal port operation, OC1A/OC1B
disconnected.
0 1 Toggle OC1A/OC1B on Compare Match.
1 0 Clear OC1A/OC1B on Compare Match (Set
output to low level).
1 1 Set OC1A/OC1B on Compare Match (Set output
to high level).133
2552K–AVR–04/11
ATmega329/3290/649/6490
Table 16-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast
PWM mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. In
this case the compare match is ignored, but the set or clear is done at BOTTOM. See “Fast
PWM Mode” on page 124. for more details.
Table 16-4 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase
correct or the phase and frequency correct, PWM mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. See
“Phase Correct PWM Mode” on page 126. for more details.
• Bit 1:0 – WGM11:0: Waveform Generation Mode
Combined with the WGM13:2 bits found in the TCCR1B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 16-5. Modes of operation supported by the Timer/Counter
unit are: Normal mode (counter), Clear Timer on Compare match (CTC) mode, and three types
of Pulse Width Modulation (PWM) modes. (See “Modes of Operation” on page 123.).
Table 16-3. Compare Output Mode, Fast PWM(1)
COM1A1/COM1B1 COM1A0/COM1B0 Description
0 0 Normal port operation, OC1A/OC1B
disconnected.
0 1 WGM13:0 = 14 or 15: Toggle OC1A on Compare
Match, OC1B disconnected (normal port
operation). For all other WGM1 settings, normal
port operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match, set
OC1A/OC1B at BOTTOM (non-inverting mode).
1 1 Set OC1A/OC1B on Compare Match, clear
OC1A/OC1B at BOTTOM (inverting mode).
Table 16-4. Compare Output Mode, Phase Correct and Phase and Frequency Correct
PWM(1)
COM1A1/COM1B1 COM1A0/COM1B0 Description
0 0 Normal port operation, OC1A/OC1B
disconnected.
0 1 WGM13:0 = 9 or 11: Toggle OC1A on Compare
Match, OC1B disconnected (normal port
operation). For all other WGM1 settings, normal
port operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match when upcounting.
Set OC1A/OC1B on Compare Match
when counting down.
1 1 Set OC1A/OC1B on Compare Match when upcounting.
Clear OC1A/OC1B on Compare Match
when counting down.134
2552K–AVR–04/11
ATmega329/3290/649/6490
Note: 1. The CTC1 and PWM11:0 bit definition names are obsolete. Use the WGM12:0 definitions. However, the functionality and
location of these bits are compatible with previous versions of the timer.
16.11.2 TCCR1B – Timer/Counter1 Control Register B
• Bit 7 – ICNC1: Input Capture Noise Canceler
Setting this bit (to one) activates the Input Capture Noise Canceler. When the noise canceler is
activated, the input from the Input Capture pin (ICP1) is filtered. The filter function requires four
successive equal valued samples of the ICP1 pin for changing its output. The Input Capture is
therefore delayed by four Oscillator cycles when the noise canceler is enabled.
• Bit 6 – ICES1: Input Capture Edge Select
This bit selects which edge on the Input Capture pin (ICP1) that is used to trigger a capture
event. When the ICES1 bit is written to zero, a falling (negative) edge is used as trigger, and
when the ICES1 bit is written to one, a rising (positive) edge will trigger the capture.
When a capture is triggered according to the ICES1 setting, the counter value is copied into the
Input Capture Register (ICR1). The event will also set the Input Capture Flag (ICF1), and this
can be used to cause an Input Capture Interrupt, if this interrupt is enabled.
Table 16-5. Waveform Generation Mode Bit Description(1)
Mode WGM13
WGM12
(CTC1)
WGM11
(PWM11)
WGM10
(PWM10)
Timer/Counter Mode of
Operation TOP
Update of
OCR1x at
TOV1 Flag
Set on
00 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM
3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCR1A Immediate MAX
5 0 1 0 1 Fast PWM, 8-bit 0x00FF BOTTOM TOP
6 0 1 1 0 Fast PWM, 9-bit 0x01FF BOTTOM TOP
7 0 1 1 1 Fast PWM, 10-bit 0x03FF BOTTOM TOP
8 1 0 0 0 PWM, Phase and Frequency
Correct
ICR1 BOTTOM BOTTOM
9 1 0 0 1 PWM, Phase and Frequency
Correct
OCR1A BOTTOM BOTTOM
10 1 0 1 0 PWM, Phase Correct ICR1 TOP BOTTOM
11 1 0 1 1 PWM, Phase Correct OCR1A TOP BOTTOM
12 1 1 0 0 CTC ICR1 Immediate MAX
13 1 1 0 1 (Reserved) – – –
14 1 1 1 0 Fast PWM ICR1 BOTTOM TOP
15 1 1 1 1 Fast PWM OCR1A BOTTOM TOP
Bit 7 6 5 4 3 2 1 0
(0x81) ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 TCCR1B
Read/Write R/W R/W R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0135
2552K–AVR–04/11
ATmega329/3290/649/6490
When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the
TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Capture
function is disabled.
• Bit 5 – Reserved Bit
This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be
written to zero when TCCR1B is written.
• Bit 4:3 – WGM13:2: Waveform Generation Mode
See TCCR1A Register description.
• Bit 2:0 – CS12:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter, see Figure
16-10 and Figure 16-11.
If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
16.11.3 TCCR1C – Timer/Counter1 Control Register C
• Bit 7 – FOC1A: Force Output Compare for Unit A
• Bit 6 – FOC1B: Force Output Compare for Unit B
The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM mode.
However, for ensuring compatibility with future devices, these bits must be set to zero when
TCCR1A is written when operating in a PWM mode. When writing a logical one to the
FOC1A/FOC1B bit, an immediate compare match is forced on the Waveform Generation unit.
The OC1A/OC1B output is changed according to its COM1x1:0 bits setting. Note that the
FOC1A/FOC1B bits are implemented as strobes. Therefore it is the value present in the
COM1x1:0 bits that determine the effect of the forced compare.
Table 16-6. Clock Select Bit Description
CS12 CS11 CS10 Description
000 No clock source (Timer/Counter stopped).
0 0 1 clkI/O/1 (No prescaling)
0 1 0 clkI/O/8 (From prescaler)
0 1 1 clkI/O/64 (From prescaler)
1 0 0 clkI/O/256 (From prescaler)
1 0 1 clkI/O/1024 (From prescaler)
1 1 0 External clock source on T1 pin. Clock on falling edge.
1 1 1 External clock source on T1 pin. Clock on rising edge.
Bit 7 6 5 4 3 2 1 0
(0x82) FOC1A FOC1B – – – – – – TCCR1C
Read/Write R/W R/W R R R R R R
Initial Value 0 0 0 0 0 0 0 0136
2552K–AVR–04/11
ATmega329/3290/649/6490
A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer
on Compare match (CTC) mode using OCR1A as TOP. The FOC1A/FOC1B bits are always
read as zero.
16.11.4 TCNT1H and TCNT1L – Timer/Counter1
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct
access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To
ensure that both the high and low bytes are read and written simultaneously when the CPU
accesses these registers, the access is performed using an 8-bit temporary High Byte Register
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit
Registers” on page 113.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a compare
match between TCNT1 and one of the OCR1x Registers.
Writing to the TCNT1 Register blocks (removes) the compare match on the following timer clock
for all compare units.
16.11.5 OCR1AH and OCR1AL – Output Compare Register 1 A
16.11.6 OCR1BH and OCR1BL – Output Compare Register 1 B
The Output Compare Registers contain a 16-bit value that is continuously compared with the
counter value (TCNT1). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC1x pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are
written simultaneously when the CPU writes to these registers, the access is performed using an
8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other
16-bit registers. See “Accessing 16-bit Registers” on page 113.
Bit 7 6 5 4 3 2 1 0
(0x85) TCNT1[15:8] TCNT1H
(0x84) TCNT1[7:0] TCNT1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0x89) OCR1A[15:8] OCR1AH
(0x88) OCR1A[7:0] OCR1AL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0x8B) OCR1B[15:8] OCR1BH
(0x8A) OCR1B[7:0] OCR1BL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0137
2552K–AVR–04/11
ATmega329/3290/649/6490
16.11.7 ICR1H and ICR1L –
Input Capture Register 1
The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the
ICP1 pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture
can be used for defining the counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes are read
simultaneously when the CPU accesses these registers, the access is performed using an 8-bit
temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit
registers. See “Accessing 16-bit Registers” on page 113.
16.11.8 TIMSK1 – Timer/Counter1 Interrupt Mask Register
• Bit 5 – ICIE1: Timer/Counter1, Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Input Capture interrupt is enabled. The corresponding Interrupt
Vector (See “Interrupts” on page 49.) is executed when the ICF1 Flag, located in TIFR1, is set.
• Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Output Compare B Match interrupt is enabled. The corresponding
Interrupt Vector (See “Interrupts” on page 49.) is executed when the OCF1B Flag, located in
TIFR1, is set.
• Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Output Compare A Match interrupt is enabled. The corresponding
Interrupt Vector (See “Interrupts” on page 49.) is executed when the OCF1A Flag, located in
TIFR1, is set.
• Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Overflow interrupt is enabled. The corresponding Interrupt Vector
(See “Interrupts” on page 49.) is executed when the TOV1 Flag, located in TIFR1, is set.
Bit 7 6 5 4 3 2 1 0
(0x87) ICR1[15:8] ICR1H
(0x86) ICR1[7:0] ICR1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0x6F) – – ICIE1 – – OCIE1B OCIE1A TOIE1 TIMSK1
Read/Write R R R/W R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0138
2552K–AVR–04/11
ATmega329/3290/649/6490
16.11.9 TIFR1 – Timer/Counter1 Interrupt Flag Register
• Bit 5 – ICF1: Timer/Counter1, Input Capture Flag
This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register
(ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the counter
reaches the TOP value.
ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively,
ICF1 can be cleared by writing a logic one to its bit location.
• Bit 2 – OCF1B: Timer/Counter1, Output Compare B Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output
Compare Register B (OCR1B).
Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag.
OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed.
Alternatively, OCF1B can be cleared by writing a logic one to its bit location.
Bit 1 – OCF1A: Timer/Counter1, Output Compare A Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output
Compare Register A (OCR1A).
Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag.
OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector is executed.
Alternatively, OCF1A can be cleared by writing a logic one to its bit location.
• Bit 0 – TOV1: Timer/Counter1, Overflow Flag
The setting of this flag is dependent of the WGM13:0 bits setting. In Normal and CTC modes,
the TOV1 Flag is set when the timer overflows. Refer to Table 16-5 on page 134 for the TOV1
Flag behavior when using another WGM13:0 bit setting.
TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed.
Alternatively, TOV1 can be cleared by writing a logic one to its bit location.
Bit 7 6 5 4 3 2 1 0
0x16 (0x36) – – ICF1 – – OCF1B OCF1A TOV1 TIFR1
Read/Write R R R/W R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0139
2552K–AVR–04/11
ATmega329/3290/649/6490
17. 8-bit Timer/Counter2 with PWM and Asynchronous Operation
17.1 Features
Timer/Counter2 is a general purpose, single compare unit, 8-bit Timer/Counter module. The
main features are:
• Single Compare Unit Counter
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Frequency Generator
• 10-bit Clock Prescaler
• Overflow and Compare Match Interrupt Sources (TOV2 and OCF2A)
• Allows Clocking from External 32kHz Watch Crystal Independent of the I/O Clock
17.2 Overview
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 17-1. For the actual
placement of I/O pins, refer to “Pinout ATmega3290/6490” on page 2. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit
locations are listed in the “Register Description” on page 153.
Figure 17-1. 8-bit Timer/Counter Block Diagram
Timer/Counter
DATA BUS
=
TCNTn
Waveform
Generation OCnx
= 0
Control Logic
= 0xFF
BOTTOM TOP
count
clear
direction
TOVn
(Int.Req.)
OCnx
(Int.Req.)
Synchronization Unit
OCRnx
TCCRnx
ASSRn Status flags
clkI/O
clkASY
Synchronized Status flags
asynchronous mode
select (ASn)
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkTn
clkI/O140
2552K–AVR–04/11
ATmega329/3290/649/6490
17.2.1 Registers
The Timer/Counter (TCNT2) and Output Compare Register (OCR2A) are 8-bit registers. Interrupt
request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register
(TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK2).
TIFR2 and TIMSK2 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from
the TOSC1/2 pins, as detailed later in this section. The asynchronous operation is controlled by
the Asynchronous Status Register (ASSR). The Clock Select logic block controls which clock
source the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive
when no clock source is selected. The output from the Clock Select logic is referred to as the
timer clock (clkT2).
The double buffered Output Compare Register (OCR2A) is compared with the Timer/Counter
value at all times. The result of the compare can be used by the Waveform Generator to generate
a PWM or variable frequency output on the Output Compare pin (OC2A). See “Output
Compare Unit” on page 141. for details. The compare match event will also set the Compare
Flag (OCF2A) which can be used to generate an Output Compare interrupt request.
17.2.2 Definitions
Many register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 2. However, when using the register or bit
defines in a program, the precise form must be used, i.e., TCNT2 for accessing Timer/Counter2
counter value and so on.
The definitions in Table 17-1 are also used extensively throughout the section.
17.3 Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal synchronous or an external asynchronous
clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2
bit in the ASSR Register is written to logic one, the clock source is taken from the Timer/Counter
Oscillator connected to TOSC1 and TOSC2. For details on asynchronous operation, see “ASSR
– Asynchronous Status Register” on page 155. For details on clock sources and prescaler, see
“Timer/Counter Prescaler” on page 152.
17.4 Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
17-2 shows a block diagram of the counter and its surrounding environment.
Table 17-1. Definitions of Timer/Counter values.
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00).
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest
value in the count sequence. The TOP value can be assigned to be the
fixed value 0xFF (MAX) or the value stored in the OCR2A Register. The
assignment is dependent on the mode of operation.141
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 17-2. Counter Unit Block Diagram
Signal description (internal signals):
count Increment or decrement TCNT2 by 1.
direction Selects between increment and decrement.
clear Clear TCNT2 (set all bits to zero).
clkT2 Timer/Counter clock.
top Signalizes that TCNT2 has reached maximum value.
bottom Signalizes that TCNT2 has reached minimum value (zero).
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source,
selected by the Clock Select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the
timer is stopped. However, the TCNT2 value can be accessed by the CPU, regardless of
whether clkT2 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in
the Timer/Counter Control Register (TCCR2A). There are close connections between how the
counter behaves (counts) and how waveforms are generated on the Output Compare output
OC2A. For more details about advanced counting sequences and waveform generation, see
“Modes of Operation” on page 145.
The Timer/Counter Overflow Flag (TOV2) is set according to the mode of operation selected by
the WGM21:0 bits. TOV2 can be used for generating a CPU interrupt.
17.5 Output Compare Unit
The 8-bit comparator continuously compares TCNT2 with the Output Compare Register
(OCR2A). Whenever TCNT2 equals OCR2A, the comparator signals a match. A match will set
the Output Compare Flag (OCF2A) at the next timer clock cycle. If enabled (OCIE2A = 1), the
Output Compare Flag generates an Output Compare interrupt. The OCF2A Flag is automatically
cleared when the interrupt is executed. Alternatively, the OCF2A Flag can be cleared by software
by writing a logical one to its I/O bit location. The Waveform Generator uses the match
signal to generate an output according to operating mode set by the WGM21:0 bits and Compare
Output mode (COM2A1:0) bits. The max and bottom signals are used by the Waveform
Generator for handling the special cases of the extreme values in some modes of operation
(“Modes of Operation” on page 145).
Figure 17-3 shows a block diagram of the Output Compare unit.
DATA BUS
TCNTn Control Logic
count
TOVn
(Int.Req.)
bottom top
direction
clear
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkI/O
clk Tn142
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 17-3. Output Compare Unit, Block Diagram
The OCR2A Register is double buffered when using any of the Pulse Width Modulation (PWM)
modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double
buffering is disabled. The double buffering synchronizes the update of the OCR2A Compare
Register to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR2A Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR2A Buffer Register, and if double buffering is
disabled the CPU will access the OCR2A directly.
17.5.1 Force Output Compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC2A) bit. Forcing compare match will not set the
OCF2A Flag or reload/clear the timer, but the OC2A pin will be updated as if a real compare
match had occurred (the COM2A1:0 bits settings define whether the OC2A pin is set, cleared or
toggled).
17.5.2 Compare Match Blocking by TCNT2 Write
All CPU write operations to the TCNT2 Register will block any compare match that occurs in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR2A to be initialized
to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is
enabled.
17.5.3 Using the Output Compare Unit
Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT2 when using the Output Compare unit,
independently of whether the Timer/Counter is running or not. If the value written to TCNT2
equals the OCR2A value, the compare match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is
counting down.
OCFnx (Int.Req.)
= (8-bit Comparator )
OCRnx
OCnx
DATA BUS
TCNTn
WGMn1:0
Waveform Generator
top
FOCn
COMnX1:0
bottom143
2552K–AVR–04/11
ATmega329/3290/649/6490
The setup of the OC2A should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC2A value is to use the Force Output Compare
(FOC2A) strobe bit in Normal mode. The OC2A Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COM2A1:0 bits are not double buffered together with the compare value.
Changing the COM2A1:0 bits will take effect immediately.144
2552K–AVR–04/11
ATmega329/3290/649/6490
17.6 Compare Match Output Unit
The Compare Output mode (COM2A1:0) bits have two functions. The Waveform Generator
uses the COM2A1:0 bits for defining the Output Compare (OC2A) state at the next compare
match. Also, the COM2A1:0 bits control the OC2A pin output source. Figure 17-4 shows a simplified
schematic of the logic affected by the COM2A1:0 bit setting. The I/O Registers, I/O bits,
and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COM2A1:0 bits are shown. When referring to the
OC2A state, the reference is for the internal OC2A Register, not the OC2A pin.
Figure 17-4. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC2A) from the Waveform
Generator if either of the COM2A1:0 bits are set. However, the OC2A pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC2A pin (DDR_OC2A) must be set as output before the OC2A value is visible
on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC2A state before the
output is enabled. Note that some COM2A1:0 bit settings are reserved for certain modes of
operation. See “Register Description” on page 153.
17.6.1 Compare Output Mode and Waveform Generation
The Waveform Generator uses the COM2A1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM2A1:0 = 0 tells the Waveform Generator that no action on the
OC2A Register is to be performed on the next compare match. For compare output actions in
the non-PWM modes refer to Table 17-3 on page 154. For fast PWM mode, refer to Table 17-4
on page 154, and for phase correct PWM refer to Table 17-5 on page 154.
PORT
DDR
D Q
D Q
OCnx
OCnx Pin
D Q Waveform
Generator
COMnx1
COMnx0
0
1
DATA BUS
FOCnx
clkI/O145
2552K–AVR–04/11
ATmega329/3290/649/6490
A change of the COM2A1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC2A strobe bits.
17.7 Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is
defined by the combination of the Waveform Generation mode (WGM21:0) and Compare Output
mode (COM2A1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM2A1:0 bits control whether the PWM
output generated should be inverted or not (inverted or non-inverted PWM). For non-PWM
modes the COM2A1:0 bits control whether the output should be set, cleared, or toggled at a
compare match (See “Compare Match Output Unit” on page 144.).
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 149.
17.7.1 Normal Mode
The simplest mode of operation is the Normal mode (WGM21:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same
timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV2 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare unit can be used to generate interrupts at some given time. Using the Output
Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
17.7.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare or CTC mode (WGM21:0 = 2), the OCR2A Register is used to
manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter
value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence
also its resolution. This mode allows greater control of the compare match output frequency. It
also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 17-5. The counter value (TCNT2)
increases until a compare match occurs between TCNT2 and OCR2A, and then counter
(TCNT2) is cleared.146
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 17-5. CTC Mode, Timing Diagram
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing the TOP to a value close to BOTTOM when the counter is
running with none or a low prescaler value must be done with care since the CTC mode does
not have the double buffering feature. If the new value written to OCR2A is lower than the current
value of TCNT2, the counter will miss the compare match. The counter will then have to
count to its maximum value (0xFF) and wrap around starting at 0x00 before the compare match
can occur.
For generating a waveform output in CTC mode, the OC2A output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COM2A1:0 = 1). The OC2A value will not be visible on the port pin unless the data direction for
the pin is set to output. The waveform generated will have a maximum frequency of fOC2A =
fclk_I/O/2 when OCR2A is set to zero (0x00). The waveform frequency is defined by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
As for the Normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
17.7.3 Fast PWM Mode
The fast Pulse Width Modulation or fast PWM mode (WGM21:0 = 3) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope
operation. The counter counts from BOTTOM to MAX then restarts from BOTTOM. In
non-inverting Compare Output mode, the Output Compare (OC2A) is cleared on the compare
match between TCNT2 and OCR2A, and set at BOTTOM. In inverting Compare Output mode,
the output is set on compare match and cleared at BOTTOM. Due to the single-slope operation,
the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that uses dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the MAX value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
TCNTn
OCnx
(Toggle)
OCnx Interrupt Flag Set
Period 1 2 3 4
(COMnx1:0 = 1)
f
OCnx
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnx = -------------------------------------------------147
2552K–AVR–04/11
ATmega329/3290/649/6490
PWM mode is shown in Figure 17-6. The TCNT2 value is in the timing diagram shown as a histogram
for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare
matches between OCR2A and TCNT2.
Figure 17-6. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches MAX. If the interrupt
is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2A pin.
Setting the COM2A1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM2A1:0 to three (See Table 17-4 on page 154). The actual
OC2A value will only be visible on the port pin if the data direction for the port pin is set as output.
The PWM waveform is generated by setting (or clearing) the OC2A Register at the compare
match between OCR2A and TCNT2, and clearing (or setting) the OC2A Register at the timer
clock cycle the counter is cleared (changes from MAX to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR2A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR2A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM2A1:0
bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC2A to toggle its logical level on each compare match (COM2A1:0 = 1). The waveform
generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2A is set to zero. This feature
is similar to the OC2A toggle in CTC mode, except the double buffer feature of the Output
Compare unit is enabled in the fast PWM mode.
TCNTn
OCRnx Update and
TOVn Interrupt Flag Set
Period 1 2 3
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Interrupt Flag Set
4 5 6 7
f
OCnxPWM
f
clk_I/O
N ⋅ 256 = ------------------148
2552K–AVR–04/11
ATmega329/3290/649/6490
17.7.4 Phase Correct PWM Mode
The phase correct PWM mode (WGM21:0 = 1) provides a high resolution phase correct PWM
waveform generation option. The phase correct PWM mode is based on a dual-slope operation.
The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In noninverting
Compare Output mode, the Output Compare (OC2A) is cleared on the compare match
between TCNT2 and OCR2A while counting up, and set on the compare match while counting
down. In inverting Output Compare mode, the operation is inverted. The dual-slope operation
has lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct
PWM mode the counter is incremented until the counter value matches MAX. When the counter
reaches MAX, it changes the count direction. The TCNT2 value will be equal to MAX for one
timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 17-7.
The TCNT2 value is in the timing diagram shown as a histogram for illustrating the dual-slope
operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal
line marks on the TCNT2 slopes represent compare matches between OCR2A and TCNT2.
Figure 17-7. Phase Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC2A pin. Setting the COM2A1:0 bits to two will produce a non-inverted PWM. An inverted
PWM output can be generated by setting the COM2A1:0 to three (See Table 17-5 on page 154).
The actual OC2A value will only be visible on the port pin if the data direction for the port pin is
set as output. The PWM waveform is generated by clearing (or setting) the OC2A Register at the
compare match between OCR2A and TCNT2 when the counter increments, and setting (or
clearing) the OC2A Register at compare match between OCR2A and TCNT2 when the counter
TOVn Interrupt Flag Set
OCnx Interrupt Flag Set
1 2 3
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Update149
2552K–AVR–04/11
ATmega329/3290/649/6490
decrements. The PWM frequency for the output when using phase correct PWM can be calculated
by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR2A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 17-7 OCn has a transition from high to low even though
there is no Compare Match. The point of this transition is to guarantee symmetry around BOTTOM.
There are two cases that give a transition without Compare Match.
• OCR2A changes its value from MAX, like in Figure 17-7. When the OCR2A value is MAX the
OCn pin value is the same as the result of a down-counting compare match. To ensure
symmetry around BOTTOM the OCn value at MAX must correspond to the result of an upcounting
Compare Match.
• The timer starts counting from a value higher than the one in OCR2A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up.
17.8 Timer/Counter Timing Diagrams
The following figures show the Timer/Counter in synchronous mode, and the timer clock (clkT2)
is therefore shown as a clock enable signal. In asynchronous mode, clkI/O should be replaced by
the Timer/Counter Oscillator clock. The figures include information on when Interrupt Flags are
set. Figure 17-8 contains timing data for basic Timer/Counter operation. The figure shows the
count sequence close to the MAX value in all modes other than phase correct PWM mode.
Figure 17-8. Timer/Counter Timing Diagram, no Prescaling
Figure 17-9 shows the same timing data, but with the prescaler enabled.
f
OCnxPCPWM
f
clk_I/O
N ⋅ 510 = ------------------
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1150
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 17-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
Figure 17-10 shows the setting of OCF2A in all modes except CTC mode.
Figure 17-10. Timer/Counter Timing Diagram, Setting of OCF2A, with Prescaler (fclk_I/O/8)
Figure 17-11 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode.
Figure 17-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler
(fclk_I/O/8)
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)151
2552K–AVR–04/11
ATmega329/3290/649/6490
17.9 Asynchronous Operation of Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken.
• Warning: When switching between asynchronous and synchronous clocking of
Timer/Counter2, the Timer Registers TCNT2, OCR2A, and TCCR2A might be corrupted. A
safe procedure for switching clock source is:
1. Disable the Timer/Counter2 interrupts by clearing OCIE2A and TOIE2.
2. Select clock source by setting AS2 as appropriate.
3. Write new values to TCNT2, OCR2A, and TCCR2A.
4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, and TCR2UB.
5. Clear the Timer/Counter2 Interrupt Flags.
6. Enable interrupts, if needed.
• The CPU main clock frequency must be more than four times the Oscillator frequency.
• When writing to one of the registers TCNT2, OCR2A, or TCCR2A, the value is transferred to
a temporary register, and latched after two positive edges on TOSC1. The user should not
write a new value before the contents of the temporary register have been transferred to its
destination. Each of the three mentioned registers have their individual temporary register,
which means that e.g. writing to TCNT2 does not disturb an OCR2A write in progress. To
detect that a transfer to the destination register has taken place, the Asynchronous Status
Register – ASSR has been implemented.
• When entering Power-save or ADC Noise Reduction mode after having written to TCNT2,
OCR2A, or TCCR2A, the user must wait until the written register has been updated if
Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode
before the changes are effective. This is particularly important if the Output Compare2
interrupt is used to wake up the device, since the Output Compare function is disabled
during writing to OCR2A or TCNT2. If the write cycle is not finished, and the MCU enters
sleep mode before the OCR2UB bit returns to zero, the device will never receive a compare
match interrupt, and the MCU will not wake up.
• If Timer/Counter2 is used to wake the device up from Power-save or ADC Noise Reduction
mode, precautions must be taken if the user wants to re-enter one of these modes: The
interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and reentering
sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the
device will fail to wake up. If the user is in doubt whether the time before re-entering Powersave
or ADC Noise Reduction mode is sufficient, the following algorithm can be used to
ensure that one TOSC1 cycle has elapsed:
1. Write a value to TCCR2A, TCNT2, or OCR2A.
2. Wait until the corresponding Update Busy Flag in ASSR returns to zero.
3. Enter Power-save or ADC Noise Reduction mode.
• When the asynchronous operation is selected, the 32.768kHz Oscillator for Timer/Counter2
is always running, except in Power-down and Standby modes. After a Power-up Reset or
wake-up from Power-down or Standby mode, the user should be aware of the fact that this
Oscillator might take as long as one second to stabilize. The user is advised to wait for at
least one second before using Timer/Counter2 after power-up or wake-up from Power-down
or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost
after a wake-up from Power-down or Standby mode due to unstable clock signal upon startup,
no matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin.
• Description of wake up from Power-save or ADC Noise Reduction mode when the timer is
clocked asynchronously: When the interrupt condition is met, the wake up process is started
on the following cycle of the timer clock, that is, the timer is always advanced by at least one
before the processor can read the counter value. After wake-up, the MCU is halted for four 152
2552K–AVR–04/11
ATmega329/3290/649/6490
cycles, it executes the interrupt routine, and resumes execution from the instruction
following SLEEP.
• Reading of the TCNT2 Register shortly after wake-up from Power-save may give an
incorrect result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2
must be done through a register synchronized to the internal I/O clock domain.
Synchronization takes place for every rising TOSC1 edge. When waking up from Powersave
mode, and the I/O clock (clkI/O) again becomes active, TCNT2 will read as the previous
value (before entering sleep) until the next rising TOSC1 edge. The phase of the TOSC
clock after waking up from Power-save mode is essentially unpredictable, as it depends on
the wake-up time. The recommended procedure for reading TCNT2 is thus as follows:
1. Write any value to either of the registers OCR2A or TCCR2A.
2. Wait for the corresponding Update Busy Flag to be cleared.
3. Read TCNT2.
During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous
timer takes 3 processor cycles plus one timer cycle. The timer is therefore advanced by at least
one before the processor can read the timer value causing the setting of the Interrupt Flag. The
Output Compare pin is changed on the timer clock and is not synchronized to the processor
clock.
17.10 Timer/Counter Prescaler
Figure 17-12. Prescaler for Timer/Counter2
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main
system I/O clock clkIO. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously
clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter
(RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port C. A crystal can
then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock
source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal. If applying
an external clock on TOSC1, the EXCLK bit in ASSR must be set.
10-BIT T/C PRESCALER
TIMER/COUNTER2 CLOCK SOURCE
clkI/O clkT2S
TOSC1
AS2
CS20
CS21
CS22
clkT2S/8
clkT2S/64
clkT2S/128
clkT2S/1024
clkT2S/256
clkT2S/32
0 PSR2
Clear
clkT2153
2552K–AVR–04/11
ATmega329/3290/649/6490
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64,
clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected.
Setting the PSR2 bit in GTCCR resets the prescaler. This allows the user to operate with a predictable
prescaler.
17.11 Register Description
17.11.1 TCCR2A – Timer/Counter Control Register A
• Bit 7 – FOC2A: Force Output Compare A
The FOC2A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring
compatibility with future devices, this bit must be set to zero when TCCR2A is written when
operating in PWM mode. When writing a logical one to the FOC2A bit, an immediate compare
match is forced on the Waveform Generation unit. The OC2A output is changed according to its
COM2A1:0 bits setting. Note that the FOC2A bit is implemented as a strobe. Therefore it is the
value present in the COM2A1:0 bits that determines the effect of the forced compare.
A FOC2A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2A as TOP.
The FOC2A bit is always read as zero.
• Bit 6, 3 – WGM21:0: Waveform Generation Mode
These bits control the counting sequence of the counter, the source for the maximum (TOP)
counter value, and what type of waveform generation to be used. Modes of operation supported
by the Timer/Counter unit are: Normal mode, Clear Timer on Compare match (CTC) mode, and
two types of Pulse Width Modulation (PWM) modes. See Table 17-2 and “Modes of Operation”
on page 145.
Note: 1. The CTC2 and PWM2 bit definition names are now obsolete. Use the WGM21:0 definitions.
However, the functionality and location of these bits are compatible with previous versions of
the timer.
• Bit 5:4 – COM2A1:0: Compare Match Output Mode A
These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0
bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to OC2A pin must be
set in order to enable the output driver.
Bit 7 6 5 4 3 2 1 0
(0xB0) FOC2A WGM20 COM2A1 COM2A0 WGM21 CS22 CS21 CS20 TCCR2A
Read/Write W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 17-2. Waveform Generation Mode Bit Description(1)
Mode
WGM21
(CTC2)
WGM20
(PWM2)
Timer/Counter Mode
of Operation TOP
Update of
OCR2A at
TOV2 Flag
Set on
00 0 Normal 0xFF Immediate MAX
1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM
2 1 0 CTC OCR2A Immediate MAX
3 1 1 Fast PWM 0xFF BOTTOM MAX154
2552K–AVR–04/11
ATmega329/3290/649/6490
When OC2A is connected to the pin, the function of the COM2A1:0 bits depends on the
WGM21:0 bit setting. Table 17-3 shows the COM2A1:0 bit functionality when the WGM21:0 bits
are set to a normal or CTC mode (non-PWM).
Table 17-4 shows the COM2A1:0 bit functionality when the WGM21:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the compare
match is ignored, but the set or clear is done at BOTTOM. See “Fast PWM Mode” on
page 146 for more details.
Table 17-5 shows the COM21:0 bit functionality when the WGM21:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the compare
match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on
page 148 for more details.
Table 17-3. Compare Output Mode, non-PWM Mode
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected.
0 1 Toggle OC2A on compare match.
1 0 Clear OC2A on compare match.
1 1 Set OC2A on compare match.
Table 17-4. Compare Output Mode, Fast PWM Mode(1)
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected.
0 1 Reserved
1 0 Clear OC2A on compare match, set OC2A at BOTTOM,
(non-inverting mode).
1 1 Set OC2A on compare match, clear OC2A at BOTTOM,
(inverting mode)
Table 17-5. Compare Output Mode, Phase Correct PWM Mode(1)
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected.
0 1 Reserved
1 0 Clear OC2A on compare match when up-counting. Set OC2A on
compare match when counting down.
1 1 Set OC2A on compare match when up-counting. Clear OC2A on
compare match when counting down.155
2552K–AVR–04/11
ATmega329/3290/649/6490
• Bit 2:0 – CS22:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter, see Table
17-6.
17.11.2 TCNT2 – Timer/Counter Register
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes) the compare
match on the following timer clock. Modifying the counter (TCNT2) while the counter is running,
introduces a risk of missing a compare match between TCNT2 and the OCR2A Register.
17.11.3 OCR2A – Output Compare Register A
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2A pin.
17.11.4 ASSR – Asynchronous Status Register
• Bit 4 – EXCLK: Enable External Clock Input
When EXCLK is written to one, and asynchronous clock is selected, the external clock input buffer
is enabled and an external clock can be input on Timer Oscillator 1 (TOSC1) pin instead of a
32kHz crystal. Writing to EXCLK should be done before asynchronous operation is selected.
Note that the crystal Oscillator will only run when this bit is zero.
Table 17-6. Clock Select Bit Description
CS22 CS21 CS20 Description
000 No clock source (Timer/Counter stopped).
0 0 1 clkT2S/(No prescaling)
0 1 0 clkT2S/8 (From prescaler)
0 1 1 clkT2S/32 (From prescaler)
1 0 0 clkT2S/64 (From prescaler)
1 0 1 clkT2S/128 (From prescaler)
1 1 0 clkT2S/256 (From prescaler)
1 1 1 clkT2S/1024 (From prescaler)
Bit 7 6 5 4 3 2 1 0
(0xB2) TCNT2[7:0] TCNT2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xB3) OCR2A[7:0] OCR2A
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xB6) – – – EXCLK AS2 TCN2UB OCR2UB TCR2UB ASSR
Read/Write R R R R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 0156
2552K–AVR–04/11
ATmega329/3290/649/6490
• Bit 3 – AS2: Asynchronous Timer/Counter2
When AS2 is written to zero, Timer/Counter2 is clocked from the I/O clock, clkI/O. When AS2 is
written to one, Timer/Counter2 is clocked from a crystal Oscillator connected to the Timer Oscillator
1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2A, and
TCCR2A might be corrupted.
• Bit 2 – TCN2UB: Timer/Counter2 Update Busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set.
When TCNT2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value.
• Bit 1 – OCR2UB: Output Compare Register2 Update Busy
When Timer/Counter2 operates asynchronously and OCR2A is written, this bit becomes set.
When OCR2A has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2A is ready to be updated with a new value.
• Bit 0 – TCR2UB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2A is written, this bit becomes set.
When TCCR2A has been updated from the temporary storage register, this bit is cleared by
hardware. A logical zero in this bit indicates that TCCR2A is ready to be updated with a new
value.
If a write is performed to any of the three Timer/Counter2 Registers while its update busy flag is
set, the updated value might get corrupted and cause an unintentional interrupt to occur.
The mechanisms for reading TCNT2, OCR2A, and TCCR2A are different. When reading
TCNT2, the actual timer value is read. When reading OCR2A or TCCR2A, the value in the temporary
storage register is read.
17.11.5 TIMSK2 – Timer/Counter2 Interrupt Mask Register
• Bit 1 – OCIE2A: Timer/Counter2 Output Compare Match A Interrupt Enable
When the OCIE2A bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match A interrupt is enabled. The corresponding interrupt is executed
if a compare match in Timer/Counter2 occurs, i.e., when the OCF2A bit is set in the Timer/Counter
2 Interrupt Flag Register – TIFR2.
• Bit 0 – TOIE2: Timer/Counter2 Overflow Interrupt Enable
When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter2 occurs, i.e., when the TOV2 bit is set in the Timer/Counter2 Interrupt
Flag Register – TIFR2.
Bit 7 6 5 4 3 2 1 0
(0x70) – – – – – – OCIE2A TOIE2 TIMSK2
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0157
2552K–AVR–04/11
ATmega329/3290/649/6490
17.11.6 TIFR2 – Timer/Counter2 Interrupt Flag Register
• Bit 1 – OCF2A: Output Compare Flag 2 A
The OCF2A bit is set (one) when a compare match occurs between the Timer/Counter2 and the
data in OCR2A – Output Compare Register2. OCF2A is cleared by hardware when executing
the corresponding interrupt handling vector. Alternatively, OCF2A is cleared by writing a logic
one to the flag. When the I-bit in SREG, OCIE2A (Timer/Counter2 Compare match Interrupt
Enable), and OCF2A are set (one), the Timer/Counter2 Compare match Interrupt is executed.
• Bit 0 – TOV2: Timer/Counter2 Overflow Flag
The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV2 is cleared
by writing a logic one to the flag. When the SREG I-bit, TOIE2A (Timer/Counter2 Overflow Interrupt
Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In
PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00.
17.11.7 GTCCR – General Timer/Counter Control Register
• Bit 1 – PSR2: Prescaler Reset Timer/Counter2
When this bit is one, the Timer/Counter2 prescaler will be reset. This bit is normally cleared
immediately by hardware. If the bit is written when Timer/Counter2 is operating in asynchronous
mode, the bit will remain one until the prescaler has been reset. The bit will not be cleared by
hardware if the TSM bit is set. Refer to the description of the “Bit 7 – TSM: Timer/Counter Synchronization
Mode” on page 108 for a description of the Timer/Counter Synchronization mode.
Bit 7 6 5 4 3 2 1 0
0x17 (0x37) – – – – – – OCF2A TOV2 TIFR2
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x23 (0x43) TSM – – – – – PSR2 PSR10 GTCCR
Read/Write R/W R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0158
2552K–AVR–04/11
ATmega329/3290/649/6490
18. SPI – Serial Peripheral Interface
18.1 Features
The ATmega329/3290/649/6490 SPI includes the following features:
• Full-duplex, Three-wire Synchronous Data Transfer
• Master or Slave Operation
• LSB First or MSB First Data Transfer
• Seven Programmable Bit Rates
• End of Transmission Interrupt Flag
• Write Collision Flag Protection
• Wake-up from Idle Mode
• Double Speed (CK/2) Master SPI Mode
18.2 Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
ATmega329/3290/649/6490 and peripheral devices or between several AVR devices. A simplified
block diagram of the Serial Peripheral Interface is shown in Figure 18-1.
The PRSPI bit in “Power Reduction Register” on page 37 must be written to zero to enable the
SPI module.
Figure 18-1. SPI Block Diagram(1)
Note: 1. Refer to Figure 1-1 on page 2, and Table 13-6 on page 68 for SPI pin placement. SPI2X SPI2X
DIVIDER
/2/4/8/16/32/64/128159
2552K–AVR–04/11
ATmega329/3290/649/6490
The interconnection between Master and Slave CPUs with SPI is shown in Figure 18-2. The system
consists of two shift Registers, and a Master clock generator. The SPI Master initiates the
communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and
Slave prepare the data to be sent in their respective shift Registers, and the Master generates
the required clock pulses on the SCK line to interchange data. Data is always shifted from Master
to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the Master In
– Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling
high the Slave Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This
must be handled by user software before communication can start. When this is done, writing a
byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight
bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of
Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an
interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be
kept in the Buffer Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin
until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission
Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt
is requested. The Slave may continue to place new data to be sent into SPDR before reading
the incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 18-2. SPI Master-slave Interconnection
The system is single buffered in the transmit direction and double buffered in the receive direction.
This means that bytes to be transmitted cannot be written to the SPI Data Register before
the entire shift cycle is completed. When receiving data, however, a received character must be
read from the SPI Data Register before the next character has been completely shifted in. Otherwise,
the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure
correct sampling of the clock signal, the minimum low and high period should be:
Low period: longer than 2 CPU clock cycles.
High period: longer than 2 CPU clock cycles.
SHIFT
ENABLE160
2552K–AVR–04/11
ATmega329/3290/649/6490
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 18-1. For more details on automatic port overrides, refer to “Alternate Port
Functions” on page 65.
Note: 1. See “Alternate Functions of Port B” on page 68 for a detailed description of how to define the
direction of the user defined SPI pins.
Table 18-1. SPI Pin Overrides(1)
Pin Direction, Master SPI Direction, Slave SPI
MOSI User Defined Input
MISO Input User Defined
SCK User Defined Input
SS User Defined Input161
2552K–AVR–04/11
ATmega329/3290/649/6490
The following code examples show how to initialize the SPI as a Master and how to perform a
simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction
Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the
actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI
with DDB5 and DDR_SPI with DDRB.
Note: 1. See “About Code Examples” on page 9.
Assembly Code Example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi r17,(1<>8);
UBRR0L = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSR0B = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}180
2552K–AVR–04/11
ATmega329/3290/649/6490
19.7.3 Receive Compete Flag and Interrupt
The USART Receiver has one flag that indicates the Receiver state.
The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive buffer.
This flag is one when unread data exist in the receive buffer, and zero when the receive
buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXENn = 0),
the receive buffer will be flushed and consequently the RXCn bit will become zero.
When the Receive Complete Interrupt Enable (RXCIEn) in UCSRnB is set, the USART Receive
Complete interrupt will be executed as long as the RXCn Flag is set (provided that global interrupts
are enabled). When interrupt-driven data reception is used, the receive complete routine
must read the received data from UDRn in order to clear the RXCn Flag, otherwise a new interrupt
will occur once the interrupt routine terminates.
19.7.4 Receiver Error Flags
The USART Receiver has three Error Flags: Frame Error (FEn), Data OverRun (DORn) and
Parity Error (UPEn). All can be accessed by reading UCSRnA. Common for the Error Flags is
that they are located in the receive buffer together with the frame for which they indicate the
error status. Due to the buffering of the Error Flags, the UCSRnA must be read before the
receive buffer (UDRn), since reading the UDRn I/O location changes the buffer read location.
Another equality for the Error Flags is that they can not be altered by software doing a write to
the flag location. However, all flags must be set to zero when the UCSRnA is written for upward
compatibility of future USART implementations. None of the Error Flags can generate interrupts.
The Frame Error (FEn) Flag indicates the state of the first stop bit of the next readable frame
stored in the receive buffer. The FEn Flag is zero when the stop bit was correctly read (as one),
and the FEn Flag will be one when the stop bit was incorrect (zero). This flag can be used for
detecting out-of-sync conditions, detecting break conditions and protocol handling. The FEn
Flag is not affected by the setting of the USBSn bit in UCSRnC since the Receiver ignores all,
except for the first, stop bits. For compatibility with future devices, always set this bit to zero
when writing to UCSRnA.
The Data OverRun (DORn) Flag indicates data loss due to a receiver buffer full condition. A
Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting
in the Receive Shift Register, and a new start bit is detected. If the DORn Flag is set there
was one or more serial frame lost between the frame last read from UDRn, and the next frame
read from UDRn. For compatibility with future devices, always write this bit to zero when writing
to UCSRnA. The DORn Flag is cleared when the frame received was successfully moved from
the Shift Register to the receive buffer.
The Parity Error (UPEn) Flag indicates that the next frame in the receive buffer had a Parity
Error when received. If Parity Check is not enabled the UPEn bit will always be read zero. For
compatibility with future devices, always set this bit to zero when writing to UCSRnA. For more
details see “Parity Bit Calculation” on page 173 and “Parity Checker” on page 180.
19.7.5 Parity Checker
The Parity Checker is active when the high USART Parity mode (UPMn1) bit is set. Type of Parity
Check to be performed (odd or even) is selected by the UPMn0 bit. When enabled, the Parity
Checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. The result of the check is stored in the receive buffer together
with the received data and stop bits. The Parity Error (UPEn) Flag can then be read by software
to check if the frame had a Parity Error.181
2552K–AVR–04/11
ATmega329/3290/649/6490
The UPEn bit is set if the next character that can be read from the receive buffer had a Parity
Error when received and the Parity Checking was enabled at that point (UPMn1 = 1). This bit is
valid until the receive buffer (UDRn) is read.
19.7.6 Disabling the Receiver
In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing
receptions will therefore be lost. When disabled (i.e., the RXENn is set to zero) the Receiver will
no longer override the normal function of the RxD port pin. The Receiver buffer FIFO will be
flushed when the Receiver is disabled. Remaining data in the buffer will be lost
19.7.7 Flushing the Receive Buffer
The receiver buffer FIFO will be flushed when the Receiver is disabled, i.e., the buffer will be
emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal
operation, due to for instance an error condition, read the UDRn I/O location until the RXCn Flag
is cleared. The following code example shows how to flush the receive buffer.
Note: 1. See “About Code Examples” on page 9.
19.8 Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data
reception. The clock recovery logic is used for synchronizing the internally generated baud rate
clock to the incoming asynchronous serial frames at the RxD pin. The data recovery logic samples
and low pass filters each incoming bit, thereby improving the noise immunity of the
Receiver. The asynchronous reception operational range depends on the accuracy of the internal
baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
19.8.1 Asynchronous Clock Recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 19-5
illustrates the sampling process of the start bit of an incoming frame. The sample rate is 16 times
the baud rate for Normal mode, and eight times the baud rate for Double Speed mode. The horizontal
arrows illustrate the synchronization variation due to the sampling process. Note the
larger time variation when using the Double Speed mode (U2Xn = 1) of operation. Samples
denoted zero are samples done when the RxD line is idle (i.e., no communication activity).
Assembly Code Example(1)
USART_Flush:
sbis UCSR0A, RXC0
ret
in r16, UDR0
rjmp USART_Flush
C Code Example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSR0A & (1< 470 nF) must be connected to the LCDCAP pin as shown in Figure
23-2. This capacitor acts as a reservoir for LCD power (VLCD). A large capacitance reduces
ripple on VLCD but increases the time until VLCD reaches its target value.
Figure 23-2. LCDCAP Connection
23.1.8 LCD Buffer Driver
Intermediate voltage levels are generated from buffers/drivers. The buffers are active the
amount of time specified by LCDDC[2:0] in LCDCCR. Then LCD output pins are tri-stated and
buffers are switched off. Shortening the drive time will reduce power consumption, but displays
with high internal resistance or capacitance may need longer drive time to achieve sufficient
contrast.
23.1.9 Display requirements
When using more than one common pin, the maximum period the LCD drivers can be turned on
for each voltage transition on the LCD pins is 50% of the prescaled LCD clock period, clkLCD_PS.
To avoid flickering, it is recommended to keep the framerate above 30Hz, thus giving a maximum
drive time of approximately 2ms when using 1/2 or 1/4 duty, and approximately 2.7ms
1 2 3
64
63
62 LCDCAP231
2552K–AVR–04/11
ATmega329/3290/649/6490
when using 1/3 duty. To achieve satisfactory contrast, all segments on the LCD display must
therefore be able to be fully charged/discharged within 2 or 2.7ms, depending on the number of
common pins.
23.1.10 Minimizing power consumption
By keeping the percentage of the time the LCD drivers are turned on at a minimum, the power
consumption of the LCD driver can be minimized. This can be achieved by using the lowest
acceptable frame rate, and using low power waveform if possible. The drive time should be kept
at the lowest setting that achieves satisfactory contrast for a particular display, while allowing
some headroom for production variations between individual LCD drivers and displays. Note
that some of the highest LCD voltage settings may result in high power consumption when VCC
is below 2.0V. The recommended maximum LCD voltage is 2*(VCC - 0.2V).
23.2 Mode of Operation
23.2.1 Static Duty and Bias
If all segments on a LCD have one electrode common, then each segment must have a unique
terminal.
This kind of display is driven with the waveform shown in Figure 23-3. SEG0 - COM0 is the voltage
across a segment that is on, and SEG1 - COM0 is the voltage across a segment that is off.
Figure 23-3. Driving a LCD with One Common Terminal
23.2.2 1/2 Duty and 1/2 Bias
For LCD with two common terminals (1/2 duty) a more complex waveform must be used to individually
control segments. Although 1/3 bias can be selected 1/2 bias is most common for these
displays. Waveform is shown in Figure 23-4. SEG0 - COM0 is the voltage across a segment that
is on, and SEG0 - COM1 is the voltage across a segment that is off.
VLCD
GND
VLCD
GND
VLCD
GND
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame
VLCD
GND
VLCD
GND
GND
SEG1
COM0
SEG1 - COM0
Frame Frame232
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 23-4. Driving a LCD with Two Common Terminals
23.2.3 1/3 Duty and 1/3 Bias
1/3 bias is usually recommended for LCD with three common terminals (1/3 duty). Waveform is
shown in Figure 23-5. SEG0 - COM0 is the voltage across a segment that is on and SEG0-
COM1 is the voltage across a segment that is off.
Figure 23-5. Driving a LCD with Three Common Terminals
23.2.4 1/4 Duty and 1/3 Bias
1/3 bias is optimal for LCD displays with four common terminals (1/4 duty). Waveform is shown
in Figure 23-6. SEG0 - COM0 is the voltage across a segment that is on and SEG0 - COM1 is
the voltage across a segment that is off.
VLCD
GND
VLCD
1/
2VLCD
GND
VLCD
1/
2VLCD
GND
-1/
2VLCD
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame
VLCD
GND
VLCD
1/
2VLCD
GND
VLCD
1/
2VLCD
GND
-1/
2VLCD
-VLCD
SEG0
COM1
SEG0 - COM1
Frame Frame
VLCD
2/
3VLCD 1/
3VLCD
GND
VLCD
2/
3VLCD 1/
3VLCD
GND
VLCD 2/
3VLCD 1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame
VLCD
2/
3VLCD 1/
3VLCD
GND
VLCD
2/
3VLCD 1/
3VLCD
GND
VLCD 2/
3VLCD 1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM1
SEG0 - COM1
Frame Frame233
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 23-6. Driving a LCD with Four Common Terminals
23.2.5 Low Power Waveform
To reduce toggle activity and hence power consumption a low power waveform can be selected
by writing LCDAB to one. Low power waveform requires two subsequent frames with the same
display data to obtain zero DC voltage. Consequently data latching and Interrupt Flag is only set
every second frame. Default and low power waveform is shown in Figure 23-7 for 1/3 duty and
1/3 bias. For other selections of duty and bias, the effect is similar.
Figure 23-7. Default and Low Power Waveform
23.2.6 Operation in Sleep Mode
When synchronous LCD clock is selected (LCDCS = 0) the LCD display will operate in Idle
mode and Power-save mode with any clock source.
An asynchronous clock from TOSC1 can be selected as LCD clock by writing the LCDCS bit to
one when Calibrated Internal RC Oscillator is selected as system clock source. The LCD will
then operate in Idle mode, ADC Noise Reduction mode and Power-save mode.
VLCD
2/
3VLCD
1/
3VLCD
GND
VLCD
2/
3VLCD
1/
3VLCD
GND
VLCD
2/
3VLCD
1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame
VLCD
2/
3VLCD
1/
3VLCD
GND
VLCD
2/
3VLCD
1/
3VLCD
GND
VLCD
2/
3VLCD
1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM1
SEG0 - COM1
Frame Frame
VLCD 2/
3VLCD 1/
3VLCD
GND
VLCD 2/
3VLCD
1/
3VLCD
GND
VLCD 2/
3VLCD
1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame
VLCD 2/
3VLCD 1/
3VLCD
GND
VLCD 2/
3VLCD
1/
3VLCD
GND
VLCD 2/
3VLCD
1/
3VLCD
GND
-1/
3VLCD
-2/
3VLCD
-VLCD
SEG0
COM0
SEG0 - COM0
Frame Frame234
2552K–AVR–04/11
ATmega329/3290/649/6490
When EXCLK in ASSR Register is written to one, and asynchronous clock is selected, the external
clock input buffer is enabled and an external clock can be input on Timer Oscillator 1
(TOSC1) pin instead of a 32kHz crystal. See “Asynchronous Operation of Timer/Counter2” on
page 151 for further details.
Before entering Power-down mode, Standby mode or ADC Noise Reduction mode with synchronous
LCD clock selected, the user have to disable the LCD. Refer to “Disabling the LCD” on
page 237.
23.2.7 Display Blanking
When LCDBL is written to one, the LCD is blanked after completing the current frame. All segments
and common pins are connected to GND, discharging the LCD. Display memory is
preserved. Display blanking should be used before disabling the LCD to avoid DC voltage
across segments, and a slowly fading image.
23.2.8 Port Mask
For LCD with less than 25/40 segment terminals, it is possible to mask some of the unused pins
and use them as ordinary port pins instead. Refer to Table 23-3 for details. Unused common
pins are automatically configured as port pins.235
2552K–AVR–04/11
ATmega329/3290/649/6490
23.3 LCD Usage
The following section describes how to use the LCD.
23.3.1 LCD Initialization
Prior to enabling the LCD some initialization must be preformed. The initialization process
normally consists of setting the frame rate, duty, bias and port mask. LCD contrast
is set initially, but can also be adjusted during operation.
Consider the following LCD as an example:
Figure 23-8.
Display: TN Positive, Reflective
Number of common terminals: 3
Number of segment terminals: 21
Bias system: 1/3 Bias
Drive system: 1/3 Duty
Operating voltage: 3.0 ± 0.3 V
1b
1c
2a
2b
2e 2c
2f
2d
2g
COM3
COM0 COM1 COM2
SEG0
SEG1
SEG2
1b,1c
2c
2f
2a
2d
2g
2b
2e
..
COM2
SEG0
SEG1
SEG2
ATmega329 COM0 COM1
Connection table
LCD
51 50 49
48
47
46
45236
2552K–AVR–04/11
ATmega329/3290/649/6490
Note: 1. See “About Code Examples” on page 9.
Before a re-initialization is done, the LCD controller/driver should be disabled
Assembly Code Example(1)
LCD_Init:
; Use 32 kHz crystal oscillator
; 1/3 Bias and 1/3 duty, SEG21:SEG24 is used as port pins
ldi r16, (1< 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck ≥ 12MHz
High: > 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck ≥ 12MHz
27.7.2 Serial Programming Algorithm
When writing serial data to the ATmega329/3290/649/6490, data is clocked on the rising edge of
SCK.
When reading data from the ATmega329/3290/649/6490, data is clocked on the falling edge of
SCK. See Figure 27-11 for timing details.
To program and verify the ATmega329/3290/649/6490 in the serial programming mode, the following
sequence is recommended (See four byte instruction formats in Table 27-15):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
the programmer can not guarantee that SCK is held low during power-up. In this
case, RESET must be given a positive pulse of at least two CPU clock cycles duration
after SCK has been set to “0”.
2. Wait for at least 20ms and enable serial programming by sending the Programming
Enable serial instruction to pin MOSI.
3. The serial programming instructions will not work if the communication is out of synchronization.
When in sync. the second byte (0x53), will echo back when issuing the third
byte of the Programming Enable instruction. Whether the echo is correct or not, all four
bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a
positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The page size is found in Table 27-10 on
page 298. The memory page is loaded one byte at a time by supplying the 6/7 LSB of the
address and data together with the Load Program Memory Page instruction. To ensure
correct loading of the page, the data low byte must be loaded before data high byte is
applied for a given address. The Program Memory Page is stored by loading the Write
Program Memory Page instruction with the 8 MSB of the address. If polling is not used,
the user must wait at least tWD_FLASH before issuing the next page. (See Table 27-14.)
Accessing the serial programming interface before the Flash write operation completes
can result in incorrect programming.
5. A: The EEPROM array is programmed one byte at a time by supplying the address and
data together with the appropriate Write instruction. An EEPROM memory location is first
automatically erased before new data is written. If polling (RDY/BSY) is not used, the
user must wait at least tWD_EEPROM before issuing the next byte (See Table 27-14.) In a
chip erased device, no 0xFFs in the data file(s) need to be programmed.
B: The EEPROM array is programmed one page at a time. The Memory page is loaded
one byte at a time by supplying the 2 LSB of the address and data together with the Load
EEPROM Memory Page instruction. The EEPROM Memory Page is stored by loading
the Write EEPROM Memory Page Instruction with the 4 MSB of the address. When using
EEPROM page access only byte locations loaded with the Load EEPROM Memory Page
instruction is altered. The remaining locations remain unchanged. If polling (RDY/BSY) is
not used, the used must wait at least tWD_EEPROM before issuing the next page (See Table
27-11). In a chip erased device, no 0xFF in the data file(s) need to be programmed.
6. Any memory location can be verified by using the Read instruction which returns the content
at the selected address at serial output MISO.
7. At the end of the programming session, RESET can be set high to commence normal
operation.310
2552K–AVR–04/11
ATmega329/3290/649/6490
8. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off.
Figure 27-11. Serial Programming Waveforms
27.7.3 Serial Programming Instruction set
Table 27-15 and Figure 27-12 on page 312 describes the Instruction set.
Table 27-14. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FUSE 4.5ms
tWD_FLASH 4.5ms
tWD_EEPROM 9.0ms
tWD_ERASE 9.0ms
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT
Table 27-15. Serial Programming Instruction Set
Instruction/Operation
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4
Programming Enable $AC $53 $00 $00
Chip Erase (Program Memory/EEPROM) $AC $80 $00 $00
Poll RDY/BSY $F0 $00 $00 data byte out
Load Instructions
Load Extended Address byte(1) $4D $00 Extended adr $00
Load Program Memory Page, High byte $48 $00 adr LSB high data byte in
Load Program Memory Page, Low byte $40 $00 adr LSB low data byte in
Load EEPROM Memory Page (page access) $C1 $00 0000 00aa
/
0000 0aaa
data byte in
Read Instructions
Read Program Memory, High byte $28 adr MSB adr LSB high data byte out
Read Program Memory, Low byte $20 adr MSB adr LSB low data byte out
Read EEPROM Memory $A0 0000 00aa
/
0000 0aaa
aaaa aaaa data byte out311
2552K–AVR–04/11
ATmega329/3290/649/6490
Note: 1. Not all instructions are applicable for all parts
2. a = address
3. Bits are programmed ‘0’, unprogrammed ‘1’.
4. To ensure future compatibility, unused Fuses and Lock bits should be unprogrammed (‘1’) .
5. Refer to the correspondig section for Fuse and Lock bits, Calibration and Signature bytes and Page size.
6. See htt://www.atmel.com/avr for Application Notes regarding programming and programmers.
If the LSB in RDY/BSY data byte out is ‘1’, a programming operation is still pending. Wait until
this bit returns ‘0’ before the next instruction is carried out.
Within the same page, the low data byte must be loaded prior to the high data byte.
After data is loaded to the page buffer, program the EEPROM page, see Figure 27-12.
Read Lock bits $58 $00 $00 data byte out
Read Signature Byte $30 $00 0000 000aa data byte out
Read Fuse bits $50 $00 $00 data byte out
Read Fuse High bits $58 $08 $00 data byte out
Read Extended Fuse Bits $50 $08 $00 data byte out
Read Calibration Byte $38 $00 $00 data byte out
Write Instructions
Write Program Memory Page $4C adr MSB adr LSB $00
Write EEPROM Memory $C0 0000 00aa
/
0000 0aaa
aaaa aaaa data byte in
Write EEPROM Memory Page (page access) $C2 0000 00aa
/
0000 0aaa
aaaa aa00
/
aaaa a000
$00
Write Lock bits $AC $E0 $00 data byte in
Write Fuse bits $AC $A0 $00 data byte in
Write Fuse High bits $AC $A8 $00 data byte in
Write Extended Fuse Bits $AC $A4 $00 data byte in
Table 27-15. Serial Programming Instruction Set
Instruction/Operation
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4312
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 27-12. Serial Programming Instruction example
27.7.4 SPI Serial Programming Characteristics
For characteristics of the SPI module see “SPI Timing Characteristics” on page 331.
Byte 1 Byte 2 Byte 3 Byte 4
Adr LSB
Bit 15 B 0
Serial Programming Instruction
Program Memory/
EEPROM Memory
Page 0
Page 1
Page 2
Page N-1
Page Buffer
Write Program Memory Page/
Write EEPROM Memory Page
Load Program Memory Page (High/Low Byte)/
Load EEPROM Memory Page (page access)
Byte 1 Byte 2 Byte 3 Byte 4
Bit 15 B 0
Adr MSB
Page Offset
Page Number
Adr MSB Adr LSB313
2552K–AVR–04/11
ATmega329/3290/649/6490
27.8 Programming via the JTAG Interface
Programming through the JTAG interface requires control of the four JTAG specific pins: TCK,
TMS, TDI, and TDO. Control of the reset and clock pins is not required.
To be able to use the JTAG interface, the JTAGEN Fuse must be programmed. The device is
default shipped with the fuse programmed. In addition, the JTD bit in MCUCSR must be cleared.
Alternatively, if the JTD bit is set, the external reset can be forced low. Then, the JTD bit will be
cleared after two chip clocks, and the JTAG pins are available for programming. This provides a
means of using the JTAG pins as normal port pins in Running mode while still allowing In-System
Programming via the JTAG interface. Note that this technique can not be used when using
the JTAG pins for Boundary-scan or On-chip Debug. In these cases the JTAG pins must be dedicated
for this purpose.
During programming the clock frequency of the TCK Input must be less than the maximum frequency
of the chip. The System Clock Prescaler can not be used to divide the TCK Clock Input
into a sufficiently low frequency.
As a definition in this data sheet, the LSB is shifted in and out first of all Shift Registers.
27.8.1 Programming Specific JTAG Instructions
The Instruction Register is 4-bit wide, supporting up to 16 instructions. The JTAG instructions
useful for programming are listed below.
The OPCODE for each instruction is shown behind the instruction name in hex format. The text
describes which Data Register is selected as path between TDI and TDO for each instruction.
The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be
used as an idle state between JTAG sequences. The state machine sequence for changing the
instruction word is shown in Figure 27-13.314
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 27-13. State Machine Sequence for Changing the Instruction Word
27.8.2 AVR_RESET (0xC)
The AVR specific public JTAG instruction for setting the AVR device in the Reset mode or taking
the device out from the Reset mode. The TAP controller is not reset by this instruction. The one
bit Reset Register is selected as Data Register. Note that the reset will be active as long as there
is a logic “one” in the Reset Chain. The output from this chain is not latched.
The active states are:
• Shift-DR: The Reset Register is shifted by the TCK input.
27.8.3 PROG_ENABLE (0x4)
The AVR specific public JTAG instruction for enabling programming via the JTAG port. The 16-
bit Programming Enable Register is selected as Data Register. The active states are the
following:
• Shift-DR: The programming enable signature is shifted into the Data Register.
• Update-DR: The programming enable signature is compared to the correct value, and
Programming mode is entered if the signature is valid.
Test-Logic-Reset
Run-Test/Idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR Scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR Scan
Capture-DR
0
1
0 11 1
0 0
0 0
1 1
1 0
1
1
0
1
0
0
1 0
1
1
0
1
0
0
0 0
1 1315
2552K–AVR–04/11
ATmega329/3290/649/6490
27.8.4 PROG_COMMANDS (0x5)
The AVR specific public JTAG instruction for entering programming commands via the JTAG
port. The 15-bit Programming Command Register is selected as Data Register. The active
states are the following:
• Capture-DR: The result of the previous command is loaded into the Data Register.
• Shift-DR: The Data Register is shifted by the TCK input, shifting out the result of the
previous command and shifting in the new command.
• Update-DR: The programming command is applied to the Flash inputs
• Run-Test/Idle: One clock cycle is generated, executing the applied command (not always
required, see Table 27-16 below).
27.8.5 PROG_PAGELOAD (0x6)
The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the 8 LSBs
of the Programming Command Register. The active states are the following:
• Shift-DR: The Flash Data Byte Register is shifted by the TCK input.
• Update-DR: The content of the Flash Data Byte Register is copied into a temporary register.
A write sequence is initiated that within 11 TCK cycles loads the content of the temporary
register into the Flash page buffer. The AVR automatically alternates between writing the low
and the high byte for each new Update-DR state, starting with the low byte for the first
Update-DR encountered after entering the PROG_PAGELOAD command. The Program
Counter is pre-incremented before writing the low byte, except for the first written byte. This
ensures that the first data is written to the address set up by PROG_COMMANDS, and
loading the last location in the page buffer does not make the program counter increment
into the next page.
27.8.6 PROG_PAGEREAD (0x7)
The AVR specific public JTAG instruction to directly capture the Flash content via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the 8 LSBs
of the Programming Command Register. The active states are the following:
• Capture-DR: The content of the selected Flash byte is captured into the Flash Data Byte
Register. The AVR automatically alternates between reading the low and the high byte for
each new Capture-DR state, starting with the low byte for the first Capture-DR encountered
after entering the PROG_PAGEREAD command. The Program Counter is post-incremented
after reading each high byte, including the first read byte. This ensures that the first data is
captured from the first address set up by PROG_COMMANDS, and reading the last location
in the page makes the program counter increment into the next page.
• Shift-DR: The Flash Data Byte Register is shifted by the TCK input.
27.8.7 Data Registers
The Data Registers are selected by the JTAG instruction registers described in section “Programming
Specific JTAG Instructions” on page 313. The Data Registers relevant for
programming operations are:
• Reset Register
• Programming Enable Register
• Programming Command Register
• Flash Data Byte Register316
2552K–AVR–04/11
ATmega329/3290/649/6490
27.8.8 Reset Register
The Reset Register is a Test Data Register used to reset the part during programming. It is
required to reset the part before entering Programming mode.
A high value in the Reset Register corresponds to pulling the external reset low. The part is reset
as long as there is a high value present in the Reset Register. Depending on the Fuse settings
for the clock options, the part will remain reset for a Reset Time-out period (refer to “Clock
Sources” on page 27) after releasing the Reset Register. The output from this Data Register is
not latched, so the reset will take place immediately, as shown in Figure 25-2 on page 253.
27.8.9 Programming Enable Register
The Programming Enable Register is a 16-bit register. The contents of this register is compared
to the programming enable signature, binary code 0b1010_0011_0111_0000. When the contents
of the register is equal to the programming enable signature, programming via the JTAG
port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when
leaving Programming mode.
Figure 27-14. Programming Enable Register
27.8.10 Programming Command Register
The Programming Command Register is a 15-bit register. This register is used to serially shift in
programming commands, and to serially shift out the result of the previous command, if any. The
JTAG Programming Instruction Set is shown in Table 27-16. The state sequence when shifting
in the programming commands is illustrated in Figure 27-16.
TDI
TDO
D
A
T
A
= D Q
ClockDR & PROG_ENABLE
Programming Enable
0xA370317
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 27-15. Programming Command Register TDI
TDO
S
T
R
O
B
E
S
A
D
D
R
E
S
S
/
D
A
T
A
Flash
EEPROM
Fuses
Lock Bits318
2552K–AVR–04/11
ATmega329/3290/649/6490
Table 27-16. JTAG Programming Instruction Set
a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don’t care
Instruction TDI Sequence TDO Sequence Notes
1a. Chip Erase 0100011_10000000
0110001_10000000
0110011_10000000
0110011_10000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
1b. Poll for Chip Erase Complete 0110011_10000000 xxxxxox_xxxxxxxx (2)
2a. Enter Flash Write 0100011_00010000 xxxxxxx_xxxxxxxx
2b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
2c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
2d. Load Data Low Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
2e. Load Data High Byte 0010111_iiiiiiii xxxxxxx_xxxxxxxx
2f. Latch Data 0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
2g. Write Flash Page 0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
2h. Poll for Page Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
3a. Enter Flash Read 0100011_00000010 xxxxxxx_xxxxxxxx
3b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
3c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
3d. Read Data Low and High Byte 0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo
Low byte
High byte
4a. Enter EEPROM Write 0100011_00010001 xxxxxxx_xxxxxxxx
4b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)
4c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
4d. Load Data Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
4e. Latch Data 0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
4f. Write EEPROM Page 0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
4g. Poll for Page Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
5a. Enter EEPROM Read 0100011_00000011 xxxxxxx_xxxxxxxx
5b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (9)319
2552K–AVR–04/11
ATmega329/3290/649/6490
5c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
5d. Read Data Byte 0110011_bbbbbbbb
0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
6a. Enter Fuse Write 0100011_01000000 xxxxxxx_xxxxxxxx
6b. Load Data Low Byte(6) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6c. Write Fuse Extended Byte 0111011_00000000
0111001_00000000
0111011_00000000
0111011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6d. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
6e. Load Data Low Byte(7) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6f. Write Fuse High Byte 0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6g. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
6h. Load Data Low Byte(7) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6i. Write Fuse Low Byte 0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6j. Poll for Fuse Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
7a. Enter Lock Bit Write 0100011_00100000 xxxxxxx_xxxxxxxx
7b. Load Data Byte(9) 0010011_11iiiiii xxxxxxx_xxxxxxxx (4)
7c. Write Lock Bits 0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
7d. Poll for Lock Bit Write complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
8a. Enter Fuse/Lock Bit Read 0100011_00000100 xxxxxxx_xxxxxxxx
8b. Read Extended Fuse Byte(6) 0111010_00000000
0111011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8c. Read Fuse High Byte(7) 0111110_00000000
0111111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8d. Read Fuse Low Byte(8) 0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8e. Read Lock Bits(9) 0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxoooooo
(5)
Table 27-16. JTAG Programming Instruction Set (Continued)
a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don’t care
Instruction TDI Sequence TDO Sequence Notes320
2552K–AVR–04/11
ATmega329/3290/649/6490
Notes: 1. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is
normally the case).
2. Repeat until o = “1”.
3. Set bits to “0” to program the corresponding Fuse, “1” to unprogram the Fuse.
4. Set bits to “0” to program the corresponding Lock bit, “1” to leave the Lock bit unchanged.
5. “0” = programmed, “1” = unprogrammed.
6. The bit mapping for Fuses Extended byte is listed in Table 27-3 on page 294
7. The bit mapping for Fuses High byte is listed in Table 27-4 on page 295
8. The bit mapping for Fuses Low byte is listed in Table 27-5 on page 295
9. The bit mapping for Lock bits byte is listed in Table 27-1 on page 293
10. Address bits exceeding PCMSB and EEAMSB (Table 27-10 and Table 27-11) are don’t care
11. All TDI and TDO sequences are represented by binary digits (0b...).
8f. Read Fuses and Lock Bits 0111010_00000000
0111110_00000000
0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo
xxxxxxx_oooooooo
xxxxxxx_oooooooo
(5)
Fuse Ext. byte
Fuse High byte
Fuse Low byte
Lock bits
9a. Enter Signature Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
9b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
9c. Read Signature Byte 0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
10a. Enter Calibration Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
10b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
10c. Read Calibration Byte 0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
11a. Load No Operation Command 0100011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
Table 27-16. JTAG Programming Instruction Set (Continued)
a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don’t care
Instruction TDI Sequence TDO Sequence Notes321
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 27-16. State Machine Sequence for Changing/Reading the Data Word
27.8.11 Flash Data Byte Register
The Flash Data Byte Register provides an efficient way to load the entire Flash page buffer
before executing Page Write, or to read out/verify the content of the Flash. A state machine sets
up the control signals to the Flash and senses the strobe signals from the Flash, thus only the
data words need to be shifted in/out.
The Flash Data Byte Register actually consists of the 8-bit scan chain and a 8-bit temporary register.
During page load, the Update-DR state copies the content of the scan chain over to the
temporary register and initiates a write sequence that within 11 TCK cycles loads the content of
the temporary register into the Flash page buffer. The AVR automatically alternates between
writing the low and the high byte for each new Update-DR state, starting with the low byte for the
first Update-DR encountered after entering the PROG_PAGELOAD command. The Program
Counter is pre-incremented before writing the low byte, except for the first written byte. This
ensures that the first data is written to the address set up by PROG_COMMANDS, and loading
the last location in the page buffer does not make the Program Counter increment into the next
page.
During Page Read, the content of the selected Flash byte is captured into the Flash Data Byte
Register during the Capture-DR state. The AVR automatically alternates between reading the
low and the high byte for each new Capture-DR state, starting with the low byte for the first CapTest-Logic-Reset
Run-Test/Idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR Scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR Scan
Capture-DR
0
1
0 11 1
0 0
0 0
1 1
1 0
1
1
0
1
0
0
1 0
1
1
0
1
0
0
0 0
1 1322
2552K–AVR–04/11
ATmega329/3290/649/6490
ture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is
post-incremented after reading each high byte, including the first read byte. This ensures that
the first data is captured from the first address set up by PROG_COMMANDS, and reading the
last location in the page makes the program counter increment into the next page.
Figure 27-17. Flash Data Byte Register
The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal
operation in which eight bits are shifted for each Flash byte, the clock cycles needed to navigate
through the TAP controller automatically feeds the state machine for the Flash Data Byte Register
with sufficient number of clock pulses to complete its operation transparently for the user.
However, if too few bits are shifted between each Update-DR state during page load, the TAP
controller should stay in the Run-Test/Idle state for some TCK cycles to ensure that there are at
least 11 TCK cycles between each Update-DR state.
27.8.12 Programming Algorithm
All references below of type “1a”, “1b”, and so on, refer to Table 27-16.
27.8.13 Entering Programming Mode
1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register.
2. Enter instruction PROG_ENABLE and shift 0b1010_0011_0111_0000 in the Programming
Enable Register.
27.8.14 Leaving Programming Mode
1. Enter JTAG instruction PROG_COMMANDS.
2. Disable all programming instructions by using no operation instruction 11a.
3. Enter instruction PROG_ENABLE and shift 0b0000_0000_0000_0000 in the programming
Enable Register.
4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register.
TDI
TDO
D
A
T
A
Flash
EEPROM
Fuses
Lock Bits
STROBES
ADDRESS
State
Machine323
2552K–AVR–04/11
ATmega329/3290/649/6490
27.8.15 Performing Chip Erase
1. Enter JTAG instruction PROG_COMMANDS.
2. Start Chip Erase using programming instruction 1a.
3. Poll for Chip Erase complete using programming instruction 1b, or wait for tWLRH_CE (refer
to Table 27-12 on page 307).
27.8.16 Programming the Flash
Before programming the Flash a Chip Erase must be performed, see “Performing Chip Erase”
on page 323.
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load address High byte using programming instruction 2b.
4. Load address Low byte using programming instruction 2c.
5. Load data using programming instructions 2d, 2e and 2f.
6. Repeat steps 4 and 5 for all instruction words in the page.
7. Write the page using programming instruction 2g.
8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH (refer to
Table 27-12 on page 307).
9. Repeat steps 3 to 7 until all data have been programmed.
A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction:
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load the page address using programming instructions 2b and 2c. PCWORD (refer to
Table 27-10 on page 298) is used to address within one page and must be written as 0.
4. Enter JTAG instruction PROG_PAGELOAD.
5. Load the entire page by shifting in all instruction words in the page byte-by-byte, starting
with the LSB of the first instruction in the page and ending with the MSB of the last
instruction in the page. Use Update-DR to copy the contents of the Flash Data Byte Register
into the Flash page location and to auto-increment the Program Counter before
each new word.
6. Enter JTAG instruction PROG_COMMANDS.
7. Write the page using programming instruction 2g.
8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH (refer to
Table 27-12 on page 307).
9. Repeat steps 3 to 8 until all data have been programmed.
27.8.17 Reading the Flash
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.
3. Load address using programming instructions 3b and 3c.
4. Read data using programming instruction 3d.
5. Repeat steps 3 and 4 until all data have been read.
A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction:
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.324
2552K–AVR–04/11
ATmega329/3290/649/6490
3. Load the page address using programming instructions 3b and 3c. PCWORD (refer to
Table 27-10 on page 298) is used to address within one page and must be written as 0.
4. Enter JTAG instruction PROG_PAGEREAD.
5. Read the entire page (or Flash) by shifting out all instruction words in the page (or Flash),
starting with the LSB of the first instruction in the page (Flash) and ending with the MSB
of the last instruction in the page (Flash). The Capture-DR state both captures the data
from the Flash, and also auto-increments the program counter after each word is read.
Note that Capture-DR comes before the shift-DR state. Hence, the first byte which is
shifted out contains valid data.
6. Enter JTAG instruction PROG_COMMANDS.
7. Repeat steps 3 to 6 until all data have been read.
27.8.18 Programming the EEPROM
Before programming the EEPROM a Chip Erase must be performed, see “Performing Chip
Erase” on page 323.
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM write using programming instruction 4a.
3. Load address High byte using programming instruction 4b.
4. Load address Low byte using programming instruction 4c.
5. Load data using programming instructions 4d and 4e.
6. Repeat steps 4 and 5 for all data bytes in the page.
7. Write the data using programming instruction 4f.
8. Poll for EEPROM write complete using programming instruction 4g, or wait for tWLRH
(refer to Table 27-12 on page 307).
9. Repeat steps 3 to 8 until all data have been programmed.
Note that the PROG_PAGELOAD instruction can not be used when programming the EEPROM.
27.8.19 Reading the EEPROM
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM read using programming instruction 5a.
3. Load address using programming instructions 5b and 5c.
4. Read data using programming instruction 5d.
5. Repeat steps 3 and 4 until all data have been read.
Note that the PROG_PAGEREAD instruction can not be used when reading the EEPROM.
27.8.20 Programming the Fuses
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse write using programming instruction 6a.
3. Load data high byte using programming instructions 6b. A bit value of “0” will program the
corresponding fuse, a “1” will unprogram the fuse.
4. Write Fuse High byte using programming instruction 6c.
5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (refer to
Table 27-12 on page 307).
6. Load data low byte using programming instructions 6e. A “0” will program the fuse, a “1”
will unprogram the fuse.
7. Write Fuse low byte using programming instruction 6f.325
2552K–AVR–04/11
ATmega329/3290/649/6490
8. Poll for Fuse write complete using programming instruction 6g, or wait for tWLRH (refer to
Table 27-12 on page 307).
27.8.21 Programming the Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Lock bit write using programming instruction 7a.
3. Load data using programming instructions 7b. A bit value of “0” will program the corresponding
lock bit, a “1” will leave the lock bit unchanged.
4. Write Lock bits using programming instruction 7c.
5. Poll for Lock bit write complete using programming instruction 7d, or wait for tWLRH (refer
to Table 27-12 on page 307).
Reading the Fuses
and Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse/Lock bit read using programming instruction 8a.
3. To read all Fuses and Lock bits, use programming instruction 8e.
To only read Fuse High byte, use programming instruction 8b.
To only read Fuse Low byte, use programming instruction 8c.
To only read Lock bits, use programming instruction 8d.
Reading the Signature
Bytes
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Signature byte read using programming instruction 9a.
3. Load address 0x00 using programming instruction 9b.
4. Read first signature byte using programming instruction 9c.
5. Repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third
signature bytes, respectively.
Reading the
Calibration Byte
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Calibration byte read using programming instruction 10a.
3. Load address 0x00 using programming instruction 10b.
Read the calibration byte using programming instruction 10c.326
2552K–AVR–04/11
ATmega329/3290/649/6490
28. Electrical Characteristics
28.1 Absolute Maximum Ratings*
28.2 DC Characteristics
Operating Temperature.................................. -55°C to +125°C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ................................................ 40.0mA
DC Current VCC and GND Pins................................. 200.0mA
Table 28-1. TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min. Typ. Max. Units
VIL
Input Low Voltage, Except
XTAL1 pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
-0.5
-0.5
0.2VCC(1)
0.3VCC(1) V
VIL1
Input Low Voltage, XTAL1
pin VCC = 1.8V - 5.5V -0.5 0.1VCC(1) V
VIH
Input High Voltage,
Except XTAL1 and
RESET pins
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.7VCC(2)
0.6VCC(2)
VCC + 0.5
VCC + 0.5 V
VIH1
Input High Voltage,
XTAL1 pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.8VCC(2)
0.7VCC(2)
VCC + 0.5
VCC + 0.5 V
VIH2
Input High Voltage,
RESET pin VCC = 1.8V - 5.5V 0.85VCC(2) VCC + 0.5 V
VOL
Output Low Voltage(3),
Port A, C, D, E, F, G, H, J
IOL = 10mA, VCC = 5V
IOL = 5mA, VCC = 3V
0.7
0.5 V
VOL1
Output Low Voltage(3),
Port B
I
OL = 20mA, VCC = 5V
IOL = 10mA, VCC = 3V
0.7
0.5 V
VOH
Output High Voltage(4),
Port A, C, D, E, F, G, H, J
IOH = -10mA, VCC = 5V
IOH = -5mA, VCC = 3V
4.2
2.3 V
VOH1
Output High Voltage(4),
Port B
IOH = -20mA, VCC = 5V
IOH = -10mA, VCC = 3V
4.2
2.3 V
IIL
Input Leakage
Current I/O Pin
VCC = 5.5V, pin low
(absolute value) 1 µA
IIH
Input Leakage
Current I/O Pin
VCC = 5.5V, pin high
(absolute value) 1 µA
RRST Reset Pull-up Resistor 20 100 kΩ
RPU I/O Pin Pull-up Resistor 20 100 kΩ327
2552K–AVR–04/11
ATmega329/3290/649/6490
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V for Port B and 10mA at
VCC = 5V, 5mA at VCC = 3V for all other ports) under steady state conditions (non-transient), the following must be observed:
TQFP and QFN/MLF Package:
1] The sum of all IOL, for all ports, should not exceed 400 mA.
2] The sum of all IOL, for ports A0 - A7, C4 - C7, G2 should not exceed 100mA.
3] The sum of all IOL, for ports B0 - B7, E0 - E7, G3 - G5 should not exceed 100mA.
4] The sum of all IOL, for ports D0 - D7, C0 - C3, G0 - G1 should not exceed 100mA.
5] The sum of all IOL, for ports F0 - F7, should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20 mA at VCC = 5V, 10 mA at VCC = 3V for Port B and 10mA
at VCC = 5V, 5mA at VCC = 3V for all other ports) under steady state conditions (non-transient), the following must be
observed:
TQFP and QFN/MLF Package:
1] The sum of all IOL, for all ports, should not exceed 400mA.
2] The sum of all IOL, for ports A0 - A7, C4 - C7, G2 should not exceed 100mA.
3] The sum of all IOL, for ports B0 - B7, E0 - E7, G3 - G5 should not exceed 100mA.
4] The sum of all IOL, for ports D0 - D7, C0 - C3, G0 - G1 should not exceed 100mA.
5] The sum of all IOL, for ports F0 - F7, should not exceed 100 mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
5. Typical values at 25°C.
ICC
Power Supply Current
Active 1MHz, VCC = 2V 1.5 mA
Active 4MHz, VCC = 3V 3.5 mA
Active 8MHz, VCC = 5V 12 mA
Idle 1MHz, VCC = 2V 0.45 mA
Idle 4MHz, VCC = 3V 1.5 mA
Idle 8MHz, VCC = 5V 5.5 mA
Power-down mode(5) WDT enabled, VCC = 3V 7 15 µA
WDT disabled, VCC = 3V 0.25 2 µA
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 <10 40 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nA
tACID
Analog Comparator
Propagation Delay
VCC = 2.7V
VCC = 4.0V
750
500 ns
Table 28-1. TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted) (Continued)
Symbol Parameter Condition Min. Typ. Max. Units328
2552K–AVR–04/11
ATmega329/3290/649/6490
28.3 Speed Grades
Figure 28-1. Maximum Frequency vs. VCC (4 - 8MHz).
Figure 28-2. Maximum Frequency vs. VCC (8 - 16MHz).
8 MHz
4 MHz
1.8V 2.7V 5.5V
Safe Operating Area
16 MHz
8 MHz
2.7V 4.5V 5.5V
Safe Operating Area329
2552K–AVR–04/11
ATmega329/3290/649/6490
28.4 Clock Characteristics
28.4.1 Calibrated Internal RC Oscillator Accuracy
Notes: 1. Voltage range for ATmega329V/3290V/649V/6490V.
2. Voltage range for ATmega329/3290/649/6490.
28.4.2 External Clock Drive Waveforms
Figure 28-3. External Clock Drive Waveforms
28.4.3 External Clock Drive
Table 28-2. Calibration Accuracy of Internal RC Oscillator
Frequency VCC Temperature Calibration Accuracy
Factory Calibration 8.0MHz 3V 25°C ±10%
User
Calibration 7.3 - 8.1MHz 1.8V - 5.5V(1)
2.7V - 5.5V(2) -40°C - 85°C ±1%
VIL1
VIH1
Table 28-3. External Clock Drive
Symbol Parameter
VCC=1.8-5.5V VCC=2.7-5.5V VCC=4.5-5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL
Oscillator
Frequency 040 8 0 16 MHz
tCLCL Clock Period 1000 125 62.5 ns
tCHCX High Time 400 50 25 ns
tCLCX Low Time 400 50 25 ns
tCLCH Rise Time 2.0 1.6 0.5 μs
tCHCL Fall Time 2.0 1.6 0.5 μs
ΔtCLCL
Change in period
from one clock
cycle to the next
2 2 2%330
2552K–AVR–04/11
ATmega329/3290/649/6490
28.5 System and Reset Characteristics
Notes: 1. The Power-on Reset will not work unless the supply voltage has been below VPOT (falling)
Notes: 1. VBOT may be below nominal minimum operating voltage for some devices. For devices where this is the case, the device is
tested down to VCC = VBOT during the production test. This guarantees that a Brown-Out Reset will occur before VCC drops to
a voltage where correct operation of the microcontroller is no longer guaranteed. The test is performed using
BODLEVEL = 10 for ATmega329/3290/649/6490V and BODLEVEL = 01 for ATmega329/3290/649/6490L.
Table 28-4. Reset, Brown-out, and Internal Voltage Reference Characteristics
Symbol Parameter Condition Min Typ Max Units
VPOT
Power-on Reset Threshold Voltage (rising) TA = -40°C to
85°C 0.7 1.0 1.4 V
Power-on Reset Threshold Voltage
(falling)(1)
TA = -40°C to
85°C 0.05 0.9 1.3 V
VPSR Power-on Slope Rate 0.01 4.5 V/ms
VRST RESET Pin Threshold Voltage VCC = 3V 0.2 VCC 0.85 VCC V
t
RST Minimum pulse width on RESET Pin VCC = 3V 800 ns
VHYST Brown-out Detector Hysteresis 50 mV
tBOD Min Pulse Width on Brown-out Reset 2 µs
VBG
Bandgap reference voltage VCC = 2.7V,
TA = 25°C 1.0 1.1 1.2 V
t
BG
Bandgap reference start-up time VCC = 2.7V,
TA = 25°C 40 70 µs
I
BG
Bandgap reference current consumption VCC = 2.7V,
TA = 25°C 15 µA
Table 28-5. BODLEVEL Fuse Coding(1)
BODLEVEL 1:0 Fuses Min VBOT Typ VBOT Max VBOT Units
11 BOD Disabled
10 1.7 1.8 2.0
01 2.5 2.7 2.9 V
00 4.1 4.3 4.5331
2552K–AVR–04/11
ATmega329/3290/649/6490
28.6 SPI Timing Characteristics
See Figure 28-4 and Figure 28-5 for details.
Note: 1. In SPI Programming mode the minimum SCK high/low period is:
- 2 tCLCL for fCK < 12MHz
- 3 tCLCL for fCK > 12MHz
Figure 28-4. SPI Interface Timing Requirements (Master Mode)
Table 28-6. SPI Timing Parameters
Description Mode Min Typ Max
1 SCK period Master See Table 18-5
ns
2 SCK high/low Master 50% duty cycle
3 Rise/Fall time Master 3.6
4 Setup Master 10
5 Hold Master 10
6 Out to SCK Master 0.5 • tsck
7 SCK to out Master 10
8 SCK to out high Master 10
9 SS low to out Slave 15
10 SCK period Slave 4 • tck
11 SCK high/low(1) Slave 2 • tck
12 Rise/Fall time Slave 1.6 µs
13 Setup Slave 10
ns
14 Hold Slave tck
15 SCK to out Slave 15
16 SCK to SS high Slave 20
17 SS high to tri-state Slave 10
18 SS low to SCK Slave 20 • tck
MOSI
(Data Output)
SCK
(CPOL = 1)
MISO
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
6 1
2 2
4 5 3
7 8332
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 28-5. SPI Interface Timing Requirements (Slave Mode)
MISO
(Data Output)
SCK
(CPOL = 1)
MOSI
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
10
11 11
13 14 12
15 17
9
X
16333
2552K–AVR–04/11
ATmega329/3290/649/6490
28.7 ADC Characteristics
Table 28-7. ADC Characteristics
Symbol Parameter Condition Min Typ Max Units
Resolution
Single Ended Conversion 10 Bits
Differential Conversion 8 Bits
Absolute accuracy (Including
INL, DNL, quantization error,
gain and offset error)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
2 2.5 LSB
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
4.5 LSB
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
Noise Reduction Mode
2 LSB
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
Noise Reduction Mode
4.5 LSB
Integral Non-Linearity (INL)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
0.5 LSB
Differential Non-Linearity (DNL)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
0.25 LSB
Gain Error
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
2 LSB
Offset Error
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
2 LSB
Conversion Time Free Running Conversion 13 260 µs
Clock Frequency Single Ended Conversion 50 1000 kHz
AVCC Analog Supply Voltage VCC - 0.3 VCC + 0.3 V
VREF Reference Voltage Single Ended Conversion 1.0 AVCC V
Differential Conversion 1.0 AVCC - 0.5 V
VIN
Pin Input Voltage
Single Ended Channels GND VREF V
Differential Channels GND AVCC V
Input Range
Single Ended Channels GND VREF V
Differential Channels(1) -0.85VREF VREF V
Input Bandwidth
Single Ended Channels 38.5 kHz
Differential Channels 4 kHz334
2552K–AVR–04/11
ATmega329/3290/649/6490
Note: 1. Voltage difference between channels.
28.8 LCD Controller Characteristics
VINT Internal Voltage Reference 1.0 1.1 1.2 V
RREF Reference Input Resistance 32 kΩ
RAIN Analog Input Resistance 100 MΩ
Table 28-8. LCD Controller Characteristics
Symbol Parameter Condition Min. Typ Max Units
ILCD LCD Driver Current Total for All COM and SEG pins 6 µA
RSEG Segment Driver Output Impedance 10 kΩ
RCOM Blackplane Driver Output Impedance 2 kΩ
Table 28-7. ADC Characteristics (Continued)
Symbol Parameter Condition Min Typ Max Units335
2552K–AVR–04/11
ATmega329/3290/649/6490
29. Typical Characteristics
The following charts show typical behavior. These figures are not tested during manufacturing.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. A sine wave generator with rail-to-rail output is used as clock
source.
All Active- and Idle current consumption measurements are done with all bits in the PRR register
set and thus, the corresponding I/O modules are turned off. Also the Analog Comparator is disabled
during these measurements. See “Power Reduction Register” on page 37 for details.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating
frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature.
The dominating factors are operating voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where
CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to
function properly at frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer
enabled and Power-down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.
29.0.1 Active Supply Current
Figure 29-1. Active Supply Current vs. Frequency (0.1 - 1.0MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (m A)336
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-2. Active Supply Current vs. Frequency (1 - 16MHz))
Figure 29-3. Active Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
2
4
6
8
10
12
14
16
0 2 4 6 8 10 12 14 16
Frequency (MHz)
ICC (mA)
0
2
4
6
8
10
12
14
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C337
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-4. Active Supply Current vs. VCC
(Internal RC Oscillator, CKDIV8 Programmed, 1MHz)
Figure 29-5. Active Supply Current vs. VCC (32kHz External Oscillator)
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
70
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)338
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.2 Idle Supply Current
Figure 29-6. Idle Supply Current vs. Frequency (0.1 - 1.0MHz)
Figure 29-7. Idle Supply Current vs. Frequency (1 - 16MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
0
1
2
3
4
5
6
0 2 4 6 8 10 12 14 16
Frequency (MHz)
ICC (mA)
1.8 V339
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-8. Idle Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
Figure 29-9. Idle Supply Current vs. VCC (Internal RC Oscillator, CKDIV8 Programmed,
1 MHz)
0
1
2
3
4
5
6
7
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85 C°
25 C°
-40 C°340
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-10. Idle Supply Current vs. VCC (32kHz External Oscillator)
29.0.3 Supply Current of I/O modules
The tables and formulas below can be used to calculate the additional current consumption for
the different I/O modules in Active and Idle mode. The enabling or disabling of the I/O modules
are controlled by the Power Reduction Register. See “Power Reduction Register” on page 37 for
details.
It is possible to calculate the typical current consumption based on the numbers from Table 29-2
for other VCC and frequency settings than listed in Table 29-1.
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
Table 29-1. Additional Current Consumption for the different I/O modules (absolute values)
PRR bit Typical numbers
VCC = 2V, F = 1MHz VCC = 3V, F = 4MHz VCC = 5V, F = 8MHz
PRADC 17µA 116µA 562µA
PRUSART0 9µA 59µA 248µA
PRSPI 10µA 62µA 257µA
PRTIM1 5µA 33µA 135µA
PRLCD 6µA 36µA 146µA
Table 29-2. Additional Current Consumption (percentage) in Active and Idle mode
PRR bit
Additional Current consumption
compared to Active with external
clock
(see Figure 29-1 and Figure 29-2)
Additional Current consumption
compared to Idle with external
clock
(see Figure 29-6 and Figure 29-7)
PRADC 5.4% 16.8%
PRUSART0 2.7% 8.5%
PRSPI 2.9% 9.0%
PRTIM1 1.5% 4.8%
PRLCD 1.7% 5.2%341
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.3.1 Example
Calculate the expected current consumption in idle mode with USART0, TIMER1, and SPI
enabled at VCC = 3.0V and F = 1MHz. Table 29-2 shows that we need to add 8.5% for the
USART0, 9% for the SPI, and 4.8% for the TIMER1 module. From Figure 29-6, we find that the
idle current consumption is ~0.16mA at VCC = 3.0V and F = 1MHz. The total current consumption
in idle mode with USART0, TIMER1, and SPI enabled, gives:
29.0.4 Power-down Supply Current
Figure 29-11. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
Figure 29-12. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
ICCtotal ≈ ≈ 0.16mA • ( ) 1 0.0 + ++ 85 0.09 0.048 0.20mA
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
3.5
4
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
16
18
20
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)342
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.5 Power-save Supply Current
Figure 29-13. Power-save Supply Current vs. VCC (Watchdog Timer Disabled)
29.0.6 Standby Supply Current
Figure 29-14. Standby Supply Current vs. VCC (Low Power Crystal Oscillator)
0
5
10
15
20
25
30
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
6MHz Xtal
6MHz Res.
4MHz Xtal
4MHz Res.
455kHz Res.
32kHz Xtal
2MHz Xtal
2MHz Res.
1MHz Res.
0
20
40
60
80
100
120
140
160
180
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)343
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.7 Pin Pull-up
Figure 29-15. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
Figure 29-16. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
0
20
40
60
80
100
120
140
160
012345
VIO (V)
IIO (uA)
85°C
25°C
-40°C
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5 3
VIO (V)
IIO (uA)
85°C 25°C
-40°C344
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-17. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 1.8V)
Figure 29-18. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
0
10
20
30
40
50
60
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOP (V)
IOP (uA)
85°C 25°C
-40°C
0
20
40
60
80
100
120
012345
VRESET (V)
IRESET (uA)
-40°C
25°C
85°C345
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-19. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
Figure 29-20. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 1.8V)
0
10
20
30
40
50
60
70
0 0.5 1 1.5 2 2.5 3
VRESET (V)
IRESET (uA)
-40°C 25°C
85°C
0
5
10
15
20
25
30
35
40
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VRESET (V)
IRESET (uA)
-40°C
25°C
85°C346
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.8 Pin Driver Strength
Figure 29-21. I/O Pin Source Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J (VCC = 5V)
Figure 29-22. I/O Pin Source Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J
(VCC = 2.7V)
0
10
20
30
40
50
60
70
0123456
VOH (V)
IOH (mA)
85°C
25°C
-40°C
0
5
10
15
20
25
0 0.5 1 1.5 2 2.5 3
VOH (V)
IOH (mA)
85°C
25°C
-40°C347
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-23. I/O Pin Source Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J
(VCC = 1.8V)
Figure 29-24. I/O Pin Source Current vs. Output Voltage, Port B (VCC= 5V)
0
1
2
3
4
5
6
7
8
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOH (V)
IOH (mA)
85°C
25°C
-40°C
0
10
20
30
40
50
60
70
80
01234
VOH (V)
IOH (mA)
85°C
25°C
-40°C348
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-25. I/O Pin Source Current vs. Output Voltage, Port B (VCC = 2.7V)
Figure 29-26. I/O Pin Source Current vs. Output Voltage, Port B (VCC = 1.8V)
0
5
10
15
20
25
30
35
0 0.5 1 1.5 2 2.5 3
VOH (V)
IOH (mA)
85°C
25°C
-40°C
0
1
2
3
4
5
6
7
8
9
10
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOH (V)
IOH (mA)
85°C
25°C
-40°C349
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-27. I/O Pin Sink Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J
(VCC = 5V)
Figure 29-28. I/O Pin Sink Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J
(VCC = 2.7V)
0
5
10
15
20
25
30
35
40
45
50
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
2
4
6
8
10
12
14
16
18
20
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C350
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-29. I/O Pin Sink Current vs. Output Voltage, Ports A, C, D, E, F, G, H, J
(VCC = 1.8V)
Figure 29-30. I/O Pin Sink Current vs. Output Voltage, Port B (VCC = 5V)
0
1
2
3
4
5
6
7
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
10
20
30
40
50
60
70
80
90
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C351
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-31. I/O Pin Sink Current vs. Output Voltage, Port B (VCC = 2.7V)
Figure 29-32. I/O Pin Sink Current vs. Output Voltage, Port B (VCC = 1.8V)
0
5
10
15
20
25
30
35
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
2
4
6
8
10
12
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C352
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.9 Pin Thresholds and hysteresis
Figure 29-33. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin Read as “1”)
Figure 29-34. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C353
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-35. I/O Pin Input Hysteresis vs. VCC
Figure 29-36. Reset Input Threshold Voltage vs. VCC (VIH,Reset Pin Read as “1”)
0
0.1
0.2
0.3
0.4
0.5
0.6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
85°C
25°C
-40°C
Input Hysteresis (V)
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C354
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-37. Reset Input Threshold Voltage vs. VCC (VIL,Reset Pin Read as “0”)
Figure 29-38. Reset Input Pin Hysteresis vs. VCC
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (V)
85°C
25°C
-40°C355
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.10 BOD Thresholds and Analog Comparator Offset
Figure 29-39. BOD Thresholds vs. Temperature (BOD Level is 4.3V)
Figure 29-40. BOD Thresholds vs. Temperature (BOD Level is 2.7V)
Rising VCC
Falling VCC
4
4.1
4.2
4.3
4.4
4.5
4.6
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
Threshold (V)
Rising VCC
Falling VCC
2.4
2.5
2.6
2.7
2.8
2.9
3
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
Threshol d ( V)356
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-41. BOD Thresholds vs. Temperature (BOD Level is 1.8V)
Figure 29-42. Bandgap Voltage vs. VCC
1.7
1.75
1.8
1.85
1.9
1.95
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
Threshold (V)
Rising VCC
Falling VCC
85°C
25°C
-40°C
1.068
1.069
1.07
1.071
1.072
1.073
1.074
1.075
1.076
1.5 2 2.5 3 3.5 4 4.5 5
VCC (V)
Bandgap Voltage (V)357
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-43. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 5V)
Figure 29-44. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 2.7V)
85°C
25°C
-40°C
0
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Common Mode Voltage (V)
Comparator Offset Voltage (V)
85°C
25°C
0 -40°C
0.0005
0.001
0.0015
0.002
0.0025
0.003
0.0035
0 0.5 1 1.5 2 2.5 3
Common Mode Voltage (V)
Comparator Offset Voltage (V)358
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.11 Internal Oscillator Speed
Figure 29-45. Watchdog Oscillator Frequency vs. VCC
Figure 29-46. Calibrated 8MHz RC Oscillator Frequency vs. Temperature
85 °C
25 °C
-40 °C
1000
1050
1100
1150
1200
1250
1300
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (kHz)
5.5 V
4.5 V
3.3 V
2.7 V
1.8 V
7.2
7.4
7.6
7.8
8
8.2
8.4
8.6
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (M Hz)359
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-47. Calibrated 8MHz RC Oscillator Frequency vs. VCC
Figure 29-48. Calibrated 8MHz RC Oscillator Frequency vs. Osccal Value
85 °C
25 °C
-40 °C
7.2
7.4
7.6
7.8
8
8.2
8.4
8.6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85 °C
25 °C
-40 °C
4
6
8
10
12
14
16
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
FRC (M Hz)360
2552K–AVR–04/11
ATmega329/3290/649/6490
29.0.12 Current Consumption of Peripheral Units
Figure 29-49. Brownout Detector Current vs. VCC
Figure 29-50. ADC Current vs. VCC (AREF = AVCC)
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
40
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
0
50
100
150
200
250
300
350
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
-40°C361
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-51. AREF External Reference Current vs. VCC
Figure 29-52. 32kHz TOSC Current vs. VCC (Watchdog Timer Disabled)
0
20
40
60
80
100
120
140
160
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
IAREF (uA)
85°C
25°C
-40°C
0
5
10
15
20
25
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C362
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-53. Watchdog Timer Current vs. VCC
Figure 29-54. Analog Comparator Current vs. VCC
0
2
4
6
8
10
12
14
16
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
-40°C
0
20
40
60
80
100
120
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
-40°C363
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-55. Programming Current vs. VCC
29.0.13 Current Consumption in Reset and Reset Pulsewidth
Figure 29-56. Reset Supply Current vs. VCC (0.1 - 1.0MHz, Excluding Current Through The
Reset Pull-up)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
16
18
20
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0.2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)364
2552K–AVR–04/11
ATmega329/3290/649/6490
Figure 29-57. Reset Supply Current vs. VCC (1 - 16MHz, Excluding Current Through The Reset
Pull-up)
Figure 29-58. Reset Pulse Width vs. VCC
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.5
1
1.5
2
2.5
3
0 2 4 6 8 10 12 14 16
Frequency (MHz)
ICC (mA)
0
500
1000
1500
2000
2500
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Pulsewidth (ns)
85°C
25°C
-40°C365
2552K–AVR–04/11
ATmega329/3290/649/6490
30. Register Summary
Note: Registers with bold type only available in ATmega3290/6490.
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0xFF) LCDDR19 SEG339 SEG338 SEG337 SEG336 SEG335 SEG334 SEG333 SEG332 244
(0xFE) LCDDR18 SEG331 SEG330 SEG329 SEG328 SEG327 SEG326 SEG325 SEG324 244
(0xFD) LCDDR17 SEG323 SEG322 SEG321 SEG320 SEG319 SEG318 SEG317 SEG316 244
(0xFC) LCDDR16 SEG315 SEG314 SEG313 SEG312 SEG311 SEG310 SEG309 SEG308 244
(0xFB) LCDDR15 SEG307 SEG306 SEG305 SEG304 SEG303 SEG302 SEG301 SEG300 244
(0xFA) LCDDR14 SEG239 SEG238 SEG237 SEG236 SEG235 SEG234 SEG233 SEG232 244
(0xF9) LCDDR13 SEG231 SEG230 SEG229 SEG228 SEG227 SEG226 SEG225 SEG224 244
(0xF8) LCDDR12 SEG223 SEG222 SEG221 SEG220 SEG219 SEG218 SEG217 SEG216 244
(0xF7) LCDDR11 SEG215 SEG214 SEG213 SEG212 SEG211 SEG210 SEG209 SEG208 244
(0xF6) LCDDR10 SEG207 SEG206 SEG205 SEG204 SEG203 SEG202 SEG201 SEG200 244
(0xF5) LCDDR09 SEG139 SEG138 SEG137 SEG136 SEG135 SEG134 SEG133 SEG132 244
(0xF4) LCDDR08 SEG131 SEG130 SEG129 SEG128 SEG127 SEG126 SEG125 SEG124 244
(0xF3) LCDDR07 SEG123 SEG122 SEG121 SEG120 SEG119 SEG118 SEG117 SEG116 244
(0xF2) LCDDR06 SEG115 SEG114 SEG113 SEG112 SEG111 SEG110 SEG109 SEG108 244
(0xF1) LCDDR05 SEG107 SEG106 SEG105 SEG104 SEG103 SEG102 SEG101 SEG100 244
(0xF0) LCDDR04 SEG039 SEG038 SEG037 SEG036 SEG035 SEG034 SEG033 SEG032 244
(0xEF) LCDDR03 SEG031 SEG030 SEG029 SEG028 SEG027 SEG026 SEG025 SEG024 244
(0xEE) LCDDR02 SEG023 SEG022 SEG021 SEG020 SEG019 SEG018 SEG017 SEG016 244
(0xED) LCDDR01 SEG015 SEG014 SEG013 SEG012 SEG011 SEG010 SEG009 SEG008 244
(0xEC) LCDDR00 SEG007 SEG006 SEG005 SEG004 SEG003 SEG002 SEG001 SEG000 244
(0xEB) Reserved - - - - - - - -
(0xEA) Reserved - - - - - - - -
(0xE9) Reserved - - - - - - - -
(0xE8) Reserved - - - - - - - -
(0xE7) LCDCCR LCDDC2 LCDDC1 LCDDC0 - LCDCC3 LCDCC2 LCDCC1 LCDCC0 243
(0xE6) LCDFRR - LCDPS2 LCDPS1 LCDPS0 - LCDCD2 LCDCD1 LCDCD0 241
(0xE5) LCDCRB LCDCS LCD2B LCDMUX1 LCDMUX0 LCDPM3 LCDPM2 LCDPM1 LCDPM0 239
(0xE4) LCDCRA LCDEN LCDAB - LCDIF LCDIE - - LCDBL 239
(0xE3) Reserved - - - - - - - -
(0xE2) Reserved - - - - - - - -
(0xE1) Reserved - - - - - - - -
(0xE0) Reserved - - - - - - - -
(0xDF) Reserved - - - - - - - -
(0xDE) Reserved - - - - - - - -
(0xDD) PORTJ - PORTJ6 PORTJ5 PORTJ4 PORTJ3 PORTJ2 PORTJ1 PORTJ0 90
(0xDC) DDRJ - DDJ6 DDJ5 DDJ4 DDJ3 DDJ2 DDJ1 DDJ0 90
(0xDB) PINJ - PINJ6 PINJ5 PINJ4 PINJ3 PINJ2 PINJ1 PINJ0 90
(0xDA) PORTH PORTH7 PORTH6 PORTH5 PORTH4 PORTH3 PORTH2 PORTH1 PORTH0 89
(0xD9) DDRH DDH7 DDH6 DDH5 DDH4 DDH3 DDH2 DDH1 DDH0 90
(0xD8) PINH PINH7 PINH6 PINH5 PINH4 PINH3 PINH2 PINH1 PINH0 90
(0xD7) Reserved - - - - - - - -
(0xD6) Reserved - - - - - - - -
(0xD5) Reserved - - - - - - - -
(0xD4) Reserved - - - - - - - -
(0xD3) Reserved - - - - - - - -
(0xD2) Reserved - - - - - - - -
(0xD1) Reserved - - - - - - - -
(0xD0) Reserved - - - - - - - -
(0xCF) Reserved - - - - - - - -
(0xCE) Reserved - - - - - - - -
(0xCD) Reserved - - - - - - - -
(0xCC) Reserved - - - - - - - -
(0xCB) Reserved - - - - - - - -
(0xCA) Reserved - - - - - - - -
(0xC9) Reserved - - - - - - - -
(0xC8) Reserved - - - - - - - -
(0xC7) Reserved - - - - - - - -
(0xC6) UDR0 USART0 Data Register 190
(0xC5) UBRR0H USART0 Baud Rate Register High 194
(0xC4) UBRR0L USART0 Baud Rate Register Low 194366
2552K–AVR–04/11
ATmega329/3290/649/6490
(0xC3) Reserved - - - - - - - -
(0xC2) UCSR0C - UMSEL0 UPM01 UPM00 USBS0 UCSZ01 UCSZ00 UCPOL0 192
(0xC1) UCSR0B RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80 191
(0xC0) UCSR0A RXC0 TXC0 UDRE0 FE0 DOR0 UPE0 U2X0 MPCM0 190
(0xBF) Reserved - - - - - - - -
(0xBE) Reserved - - - - - - - -
(0xBD) Reserved - - - - - - - -
(0xBC) Reserved - - - - - - - -
(0xBB) Reserved - - - - - - - -
(0xBA) USIDR USI Data Register 203
(0xB9) USISR USISIF USIOIF USIPF USIDC USICNT3 USICNT2 USICNT1 USICNT0 203
(0xB8) USICR USISIE USIOIE USIWM1 USIWM0 USICS1 USICS0 USICLK USITC 204
(0xB7) Reserved - - - - - - - -
(0xB6) ASSR - - - EXCLK AS2 TCN2UB OCR2UB TCR2UB 155
(0xB5) Reserved - - - - - - - -
(0xB4) Reserved - - - - - - - -
(0xB3) OCR2A Timer/Counter 2 Output Compare Register A 155
(0xB2) TCNT2 Timer/Counter2 155
(0xB1) Reserved - - - - - - - -
(0xB0) TCCR2A FOC2A WGM20 COM2A1 COM2A0 WGM21 CS22 CS21 CS20 153
(0xAF) Reserved - - - - - - - -
(0xAE) Reserved - - - - - - - -
(0xAD) Reserved - - - - - - - -
(0xAC) Reserved - - - - - - - -
(0xAB) Reserved - - - - - - - -
(0xAA) Reserved - - - - - - - -
(0xA9) Reserved - - - - - - - -
(0xA8) Reserved - - - - - - - -
(0xA7) Reserved - - - - - - - -
(0xA6) Reserved - - - - - - - -
(0xA5) Reserved - - - - - - - -
(0xA4) Reserved - - - - - - - -
(0xA3) Reserved - - - - - - - -
(0xA2) Reserved - - - - - - - -
(0xA1) Reserved - - - - - - - -
(0xA0) Reserved - - - - - - - -
(0x9F) Reserved - - - - - - - -
(0x9E) Reserved - - - - - - - -
(0x9D) Reserved - - - - - - - -
(0x9C) Reserved - - - - - - - -
(0x9B) Reserved - - - - - - - -
(0x9A) Reserved - - - - - - - -
(0x99) Reserved - - - - - - - -
(0x98) Reserved - - - - - - - -
(0x97) Reserved - - - - - - - -
(0x96) Reserved - - - - - - - -
(0x95) Reserved - - - - - - - -
(0x94) Reserved - - - - - - - -
(0x93) Reserved - - - - - - - -
(0x92) Reserved - - - - - - - -
(0x91) Reserved - - - - - - - -
(0x90) Reserved - - - - - - - -
(0x8F) Reserved - - - - - - - -
(0x8E) Reserved - - - - - - - -
(0x8D) Reserved - - - - - - - -
(0x8C) Reserved - - - - - - - -
(0x8B) OCR1BH Timer/Counter1 Output Compare Register B High 136
(0x8A) OCR1BL Timer/Counter1 Output Compare Register B Low 136
(0x89) OCR1AH Timer/Counter1 Output Compare Register A High 136
(0x88) OCR1AL Timer/Counter1 Output Compare Register A Low 136
(0x87) ICR1H Timer/Counter1 Input Capture Register High 137
(0x86) ICR1L Timer/Counter1 Input Capture Register Low 137
(0x85) TCNT1H Timer/Counter1 High 136
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page367
2552K–AVR–04/11
ATmega329/3290/649/6490
(0x84) TCNT1L Timer/Counter1 Low 136
(0x83) Reserved - - - - - - - -
(0x82) TCCR1C FOC1A FOC1B - - - - - - 135
(0x81) TCCR1B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 134
(0x80) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 - - WGM11 WGM10 132
(0x7F) DIDR1 - - - - - - AIN1D AIN0D 210
(0x7E) DIDR0 ADC7D ADC6D ADC5D ADC4D ADC3D ADC2D ADC1D ADC0D 227
(0x7D) Reserved - - - - - - - -
(0x7C) ADMUX REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0 223
(0x7B) ADCSRB - ACME - - - ADTS2 ADTS1 ADTS0 209/227
(0x7A) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 225
(0x79) ADCH ADC Data Register High 226
(0x78) ADCL ADC Data Register Low 226
(0x77) Reserved - - - - - - - -
(0x76) Reserved - - - - - - - -
(0x75) Reserved - - - - - - - -
(0x74) Reserved - - - - - - - -
(0x73) PCMSK3 - PCINT30 PCINT29 PCINT28 PCINT27 PCINT26 PCINT25 PCINT24 57
(0x72) Reserved - - - - - - - -
(0x71) Reserved - - - - - - - -
(0x70) TIMSK2 - - - - - - OCIE2A TOIE2 156
(0x6F) TIMSK1 - - ICIE1 - - OCIE1B OCIE1A TOIE1 137
(0x6E) TIMSK0 - - - - - - OCIE0A TOIE0 106
(0x6D) PCMSK2 PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 57
(0x6C) PCMSK1 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 58
(0x6B) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 58
(0x6A) Reserved - - - - - - - -
(0x69) EICRA - - - - - - ISC01 ISC00 55
(0x68) Reserved - - - - - - - -
(0x67) Reserved - - - - - - - -
(0x66) OSCCAL Oscillator Calibration Register [CAL7..0] 32
(0x65) Reserved - - - - - - - -
(0x64) PRR - - - PRLCD PRTIM1 PRSPI PSUSART0 PRADC 40
(0x63) Reserved - - - - - - - -
(0x62) Reserved - - - - - - - -
(0x61) CLKPR CLKPCE - - - CLKPS3 CLKPS2 CLKPS1 CLKPS0 33
(0x60) WDTCR - - - WDCE WDE WDP2 WDP1 WDP0 48
0x3F (0x5F) SREG I T H S V N Z C 12
0x3E (0x5E) SPH Stack Pointer High 14
0x3D (0x5D) SPL Stack Pointer Low 14
0x3C (0x5C) Reserved - - - - - - - -
0x3B (0x5B) Reserved - - - - - - - -
0x3A (0x5A) Reserved - - - - - - - -
0x39 (0x59) Reserved - - - - - - - -
0x38 (0x58) Reserved - - - - - - - -
0x37 (0x57) SPMCSR SPMIE RWWSB - RWWSRE BLBSET PGWRT PGERS SPMEN 291
0x36 (0x56) Reserved
0x35 (0x55) MCUCR JTD - - PUD - - IVSEL IVCE 52/87/254
0x34 (0x54) MCUSR - - - JTRF WDRF BORF EXTRF PORF 47
0x33 (0x53) SMCR - - - - SM2 SM1 SM0 SE 39
0x32 (0x52) Reserved - - - - - - - -
0x31 (0x51) OCDR IDRD/OCDR7 OCDR6 OCDR5 OCDR4 OCDR3 OCDR2 OCDR1 OCDR0 250
0x30 (0x50) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 209
0x2F (0x4F) Reserved - - - - - - - -
0x2E (0x4E) SPDR SPI Data Register 167
0x2D (0x4D) SPSR SPIF WCOL - - - - - SPI2X 167
0x2C (0x4C) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 165
0x2B (0x4B) GPIOR2 General Purpose I/O Register 25
0x2A (0x4A) GPIOR1 General Purpose I/O Register 25
0x29 (0x49) Reserved - - - - - - - -
0x28 (0x48) Reserved - - - - - - - -
0x27 (0x47) OCR0A Timer/Counter0 Output Compare A 105
0x26 (0x46) TCNT0 Timer/Counter0 105
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page368
2552K–AVR–04/11
ATmega329/3290/649/6490
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operate on the specified bit, and can therefore be used on registers containing such Status Flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used. When addressing I/O
Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. The
ATmega329/3290/649/6490 is a complex microcontroller with more peripheral units than can be supported within the 64
location reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only
the ST/STS/STD and LD/LDS/LDD instructions can be used.
0x25 (0x45) Reserved - - - - - - - -
0x24 (0x44) TCCR0A FOC0A WGM00 COM0A1 COM0A0 WGM01 CS02 CS01 CS00 103
0x23 (0x43) GTCCR TSM - - - - - PSR2 PSR10 108/157
0x22 (0x42) EEARH - - - - - EEPROM Address Register High 22
0x21 (0x41) EEARL EEPROM Address Register Low 22
0x20 (0x40) EEDR EEPROM Data Register 22
0x1F (0x3F) EECR - - - - EERIE EEMWE EEWE EERE 22
0x1E (0x3E) GPIOR0 General Purpose I/O Register 25
0x1D (0x3D) EIMSK PCIE3 PCIE2 PCIE1 PCIE0 - - - INT0 55
0x1C (0x3C) EIFR PCIF3 PCIF2 PCIF1 PCIF0 - - - INTF0 56
0x1B (0x3B) Reserved - - - - - - - -
0x1A (0x3A) Reserved - - - - - - - -
0x19 (0x39) Reserved - - - - - - - -
0x18 (0x38) Reserved - - - - - - - -
0x17 (0x37) TIFR2 - - - - - - OCF2A TOV2 157
0x16 (0x36) TIFR1 - - ICF1 - - OCF1B OCF1A TOV1 138
0x15 (0x35) TIFR0 - - - - - - OCF0A TOV0 106
0x14 (0x34) PORTG - - - PORTG4 PORTG3 PORTG2 PORTG1 PORTG0 89
0x13 (0x33) DDRG - - - DDG4 DDG3 DDG2 DDG1 DDG0 89
0x12 (0x32) PING - - PING5 PING4 PING3 PING2 PING1 PING0 89
0x11 (0x31) PORTF PORTF7 PORTF6 PORTF5 PORTF4 PORTF3 PORTF2 PORTF1 PORTF0 89
0x10 (0x30) DDRF DDF7 DDF6 DDF5 DDF4 DDF3 DDF2 DDF1 DDF0 89
0x0F (0x2F) PINF PINF7 PINF6 PINF5 PINF4 PINF3 PINF2 PINF1 PINF0 89
0x0E (0x2E) PORTE PORTE7 PORTE6 PORTE5 PORTE4 PORTE3 PORTE2 PORTE1 PORTE0 88
0x0D (0x2D) DDRE DDE7 DDE6 DDE5 DDE4 DDE3 DDE2 DDE1 DDE0 88
0x0C (0x2C) PINE PINE7 PINE6 PINE5 PINE4 PINE3 PINE2 PINE1 PINE0 89
0x0B (0x2B) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 88
0x0A (0x2A) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 88
0x09 (0x29) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 88
0x08 (0x28) PORTC PORTC7 PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 88
0x07 (0x27) DDRC DDC7 DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 88
0x06 (0x26) PINC PINC7 PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 88
0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 87
0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 87
0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 87
0x02 (0x22) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 87
0x01 (0x21) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 87
0x00 (0x20) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 87
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page369
2552K–AVR–04/11
ATmega329/3290/649/6490
31. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd ← Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd ← Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd ← Rd • Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd ← Rd • K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd ← Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd ← Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd ← Rd ⊕ Rr Z,N,V 1
COM Rd One’s Complement Rd ← 0xFF − Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd ← 0x00 − Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd ← Rd • (0xFF - K) Z,N,V 1
INC Rd Increment Rd ← Rd + 1 Z,N,V 1
DEC Rd Decrement Rd ← Rd − 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V 1
SER Rd Set Register Rd ← 0xFF None 1
MUL Rd, Rr Multiply Unsigned R1:R0 ← Rd x Rr Z,C 2
MULS Rd, Rr Multiply Signed R1:R0 ← Rd x Rr Z,C 2
MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 ← Rd x Rr Z,C 2
FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 ← (Rd x Rr) << 1 Z,C 2
FMULS Rd, Rr Fractional Multiply Signed R1:R0 ← (Rd x Rr) << 1 Z,C 2
FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 ← (Rd x Rr) << 1 Z,C 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC ← PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC ← Z None 2
JMP k Direct Jump PC ← k None 3
RCALL k Relative Subroutine Call PC ← PC + k + 1 None 3
ICALL Indirect Call to (Z) PC ← Z None 3
CALL k Direct Subroutine Call PC ← k None 4
RET Subroutine Return PC ← STACK None 4
RETI Interrupt Return PC ← STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd − Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd − Rr − C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd − K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1/2370
2552K–AVR–04/11
ATmega329/3290/649/6490
BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2
LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z,C,N,V 1
ROR Rd Rotate Right Through Carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1
BSET s Flag Set SREG(s) ← 1 SREG(s) 1
BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) ← T None 1
SEC Set Carry C ← 1 C1
CLC Clear Carry C ← 0 C 1
SEN Set Negative Flag N ← 1 N 1
CLN Clear Negative Flag N ← 0 N 1
SEZ Set Zero Flag Z ← 1 Z1
CLZ Clear Zero Flag Z ← 0 Z 1
SEI Global Interrupt Enable I ← 1 I1
CLI Global Interrupt Disable I ← 0 I 1
SES Set Signed Test Flag S ← 1 S1
CLS Clear Signed Test Flag S ← 0 S 1
SEV Set Twos Complement Overflow. V ← 1 V1
CLV Clear Twos Complement Overflow V ← 0 V 1
SET Set T in SREG T ← 1 T1
CLT Clear T in SREG T ← 0 T 1
SEH Set Half Carry Flag in SREG H ← 1 H1
CLH Clear Half Carry Flag in SREG H ← 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd ← Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd ← Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd ← K None 1
LD Rd, X Load Indirect Rd ← (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd ← (X), X ← X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X ← X - 1, Rd ← (X) None 2
LD Rd, Y Load Indirect Rd ← (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd ← (Y), Y ← Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y ← Y - 1, Rd ← (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd ← (Y + q) None 2
LD Rd, Z Load Indirect Rd ← (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd ← (Z), Z ← Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z ← Z - 1, Rd ← (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd ← (k) None 2
ST X, Rr Store Indirect (X) ← Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) ← Rr, X ← X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X ← X - 1, (X) ← Rr None 2
ST Y, Rr Store Indirect (Y) ← Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) ← Rr, Y ← Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y ← Y - 1, (Y) ← Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) ← Rr None 2
ST Z, Rr Store Indirect (Z) ← Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) ← Rr, Z ← Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z ← Z - 1, (Z) ← Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2
STS k, Rr Store Direct to SRAM (k) ← Rr None 2
LPM Load Program Memory R0 ← (Z) None 3
LPM Rd, Z Load Program Memory Rd ← (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd ← (Z), Z ← Z+1 None 3
SPM Store Program Memory (Z) ← R1:R0 None -
Mnemonics Operands Description Operation Flags #Clocks371
2552K–AVR–04/11
ATmega329/3290/649/6490
IN Rd, P In Port Rd ← P None 1
OUT P, Rr Out Port P ← Rr None 1
PUSH Rr Push Register on Stack STACK ← Rr None 2
POP Rd Pop Register from Stack Rd ← STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #Clocks372
2552K–AVR–04/11
ATmega329/3290/649/6490
32. Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. For Speed vs. VCC see Figure 28-1 on page 328 and Figure 28-2 on page 328.
4. Tape & Reel
32.1 ATmega329
Speed (MHz)(3) Power Supply Ordering Code(2) Package Type(1) Operational Range
8 1.8 - 5.5V
ATmega329V-8AU
ATmega329V-8AUR(4)
ATmega329V-8MU
ATmega329V-8MUR(4)
64A
64A
64M1
64M1
Industrial
(-40°C to 85°C)
16 2.7 - 5.5V
ATmega329-16AU
ATmega329-16AUR(4)
ATmega329-16MU
ATmega329-16MUR(4)
64A
64A
64M1
64M1
Industrial
(-40°C to 85°C)
Package Type
64A 64-lead, 14 x 14 x 1.0 mm, Thin Profile Plastic Quad Flat Package (TQFP)
64M1 64-pad, 9 x 9 x 1.0 mm, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)
100A 100-lead, 14 x 14 x 1.0 mm, 0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP)373
2552K–AVR–04/11
ATmega329/3290/649/6490
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. For Speed vs. VCC see Figure 28-1 on page 328 and Figure 28-2 on page 328.
4. Tape & Reel
32.2 ATmega3290
Speed (MHz)(3) Power Supply Ordering Code(2) Package Type(1) Operational Range
8 1.8 - 5.5V ATmega3290V-8AU
ATmega3290V-8AUR(4)
100A
100A
Industrial
(-40°C to 85°C)
16 2.7 - 5.5V ATmega3290-16AU
ATmega3290-16AUR(4)
100A
100A
Industrial
(-40°C to 85°C)
Package Type
64A 64-lead, 14 x 14 x 1.0 mm, Thin Profile Plastic Quad Flat Package (TQFP)
64M1 64-pad, 9 x 9 x 1.0 mm, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)
100A 100-lead, 14 x 14 x 1.0 mm, 0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP)374
2552K–AVR–04/11
ATmega329/3290/649/6490
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. For Speed vs. VCC see Figure 28-1 on page 328 and Figure 28-2 on page 328.
4. Tape & Reel
32.3 ATmega649
Speed (MHz)(3) Power Supply Ordering Code(2) Package Type(1) Operational Range
8 1.8 - 5.5V
ATmega649V-8AU
ATmega649V-8AUR(4)
ATmega649V-8MU
ATmega649V-8MUR(4)
64A
64A
64M1
64M1
Industrial
(-40°C to 85°C)
16 2.7 - 5.5V
ATmega649-16AU
ATmega649-16AUR(4)
ATmega649-16MU
ATmega649-16MUR(4)
64A
64A
64M1
64M1
Industrial
(-40°C to 85°C)
Package Type
64A 64-lead, 14 x 14 x 1.0 mm, Thin Profile Plastic Quad Flat Package (TQFP)
64M1 64-pad, 9 x 9 x 1.0 mm, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)
100A 100-lead, 14 x 14 x 1.0 mm, 0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP)375
2552K–AVR–04/11
ATmega329/3290/649/6490
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. For Speed Grades see Figure 28-1 on page 328 and Figure 28-2 on page 328.
4. Tape & Reel
32.4 ATmega6490
Speed (MHz)(3) Power Supply Ordering Code(2) Package Type(1) Operational Range
8 1.8 - 5.5V ATmega6490V-8AU
ATmega6490V-8AUR(4)
100A
100A
Industrial
(-40°C to 85°C)
16 2.7 - 5.5V ATmega6490-16AU
ATmega6490-16AUR(4)
100A
100A
Industrial
(-40°C to 85°C)
Package Type
64A 64-lead, 14 x 14 x 1.0 mm, Thin Profile Plastic Quad Flat Package (TQFP)
64M1 64-pad, 9 x 9 x 1.0 mm, Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)
100A 100-lead, 14 x 14 x 1.0 mm, 0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP)376
2552K–AVR–04/11
ATmega329/3290/649/6490
33. Packaging Information
33.1 64A
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
64A, 64-lead, 14 x 14 mm Body Size, 1.0 mm Body Thickness,
0.8 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP) 64A C
2010-10-20
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
e
E1 E
B
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
Notes:
1.This package conforms to JEDEC reference MS-026, Variation AEB.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.10 mm maximum.
A – – 1.20
A1 0.05 – 0.15
A2 0.95 1.00 1.05
D 15.75 16.00 16.25
D1 13.90 14.00 14.10 Note 2
E 15.75 16.00 16.25
E1 13.90 14.00 14.10 Note 2
B 0.30 – 0.45
C 0.09 – 0.20
L 0.45 – 0.75
e 0.80 TYP377
2552K–AVR–04/11
ATmega329/3290/649/6490
33.2 64M1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
64M1, 64-pad, 9 x 9 x 1.0 mm Body, Lead Pitch 0.50 mm, 64M1 H
2010-10-19
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A 0.80 0.90 1.00
A1 – 0.02 0.05
b 0.18 0.25 0.30
D
D2 5.20 5.40 5.60
8.90 9.00 9.10
E 8.90 9.00 9.10
E2 5.20 5.40 5.60
e 0.50 BSC
L 0.35 0.40 0.45
Notes:
1. JEDEC Standard MO-220, (SAW Singulation) Fig. 1, VMMD.
2. Dimension and tolerance conform to ASMEY14.5M-1994.
TOP VIEW
SIDE VIEW
BOTTOM VIEW
D
E
Marked Pin# 1 ID
SEATING PLANE
A1
C
A
0.08 C
1
2
3
K 1.25 1.40 1.55
E2
D2
b e
Pin #1 Corner L
Pin #1
Triangle
Pin #1
Chamfer
(C 0.30)
Option A
Option B
Pin #1
Notch
(0.20 R)
Option C
K
K
5.40 mm Exposed Pad, Micro Lead Frame Package (MLF) 378
2552K–AVR–04/11
ATmega329/3290/649/6490
33.3 100A
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
100A, 100-lead, 14 x 14 mm Body Size, 1.0 mm Body Thickness,
0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP) 100A D
2010-10-20
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
e E1 E
B
A – – 1.20
A1 0.05 – 0.15
A2 0.95 1.00 1.05
D 15.75 16.00 16.25
D1 13.90 14.00 14.10 Note 2
E 15.75 16.00 16.25
E1 13.90 14.00 14.10 Note 2
B 0.17 – 0.27
C 0.09 – 0.20
L 0.45 – 0.75
e 0.50 TYP
Notes:
1. This package conforms to JEDEC reference MS-026, Variation AED.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.08 mm maximum.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE379
2552K–AVR–04/11
ATmega329/3290/649/6490
34. Errata
34.1 ATmega329
34.1.1 ATmega329 rev. C
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).
34.1.2 ATmega329 rev. B
Not sampled.
34.1.3 ATmega329 rev. A
• LCD contrast voltage too high
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. LCD contrast voltage too high
When the LCD is active and using low power waveform, the LCD contrast voltage can be too
high. This occurs when VCC is higher than VLCD, and when using low LCD drivetime.
Problem Fix/Workaround
There are several possible workarounds:
- Use normal waveform instead of low power waveform
- Use drivetime of 375 µs or longer
2. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).380
2552K–AVR–04/11
ATmega329/3290/649/6490
34.2 ATmega3290
34.2.1 ATmega3290 rev. C
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).
34.2.2 ATmega3290 rev. B
Not sampled.
34.2.3 ATmega3290 rev. A
• LCD contrast voltage too high
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. LCD contrast voltage too high
When the LCD is active and using low power waveform, the LCD contrast voltage can be too
high. This occurs when VCC is higher than VLCD, and when using low LCD drivetime.
Problem Fix/Workaround
There are several possible workarounds:
- Use normal waveform instead of low power waveform
- Use drivetime of 375 µs or longer
2. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).381
2552K–AVR–04/11
ATmega329/3290/649/6490
34.3 ATmega649
34.3.1 ATmega649 rev. A
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).
34.4 ATmega6490
34.4.1 ATmega6490 rev. A
• Interrupts may be lost when writing the timer registers in the asynchronous timer
1. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the
asynchronous Timer/Counter register (TCNTx) is 0x00.
Problem Fix/Wortkaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register (TCCRx), asynchronous
Timer Counter Register (TCNTx), or asynchronous Output Compare Register (OCRx).382
2552K–AVR–04/11
ATmega329/3290/649/6490
35. Datasheet Revision History
Please note that the referring page numbers in this section are referring to this document.The
referring revision in this section are referring to the document revision.
35.1 Rev. 2552K – 04/11
35.2 Rev. 2552J – 08/07
35.3 Rev. 2552I – 04/07
35.4 Rev. 2552H – 11/06
1. Removed “Preliminary” from the front page.
2. Removed “Disclaimer Section” from the datasheet.
3. Updated Table 28-5 on page 330 “BODLEVEL Fuse Coding(1)” .
4. Updated Table 28-8 on page 334 “LCD Controller Characteristics” .
5. Updated “Ordering Information” on page 372 to include “Tape & Reel” devices.
The “AI” and “MI” devices removed.
6. Updated “Errata” on page 379.
7. Updated the datasheet according to the Atmel new brand style guide, including
the last page.
1. Updated “Features” on page 1.
2. Added “Data Retention” on page 9.
3. Updated “Serial Programming Algorithm” on page 309.
4. Updated “Speed Grades” on page 328.
5. Updated “System and Reset Characteristics” on page 330.
6. Moved Register Descriptions to the end of each chapter.
1. Updated date in backpage
2. Updated column in Table 28-5 on page 330.
1. Updated Table 28-7 on page 333.
2. Updated note in Table 28-7 on page 333 and Table 28-2 on page 329.383
2552K–AVR–04/11
ATmega329/3290/649/6490
35.5 Rev. 2552G – 07/06
35.6 Rev. 2552F – 06/06
35.7 Rev. 2552E – 04/06
35.8 Rev. 2552D – 03/06
35.9 Rev. 2552C – 03/06
1. Updated Table 14-2 on page 104, Table 14-4 on page 104, Table 16-3 on
page 133, Table 16-5 on page 134, Table 16-5 on page 134, Table 17-2 on
page 153 and Table 17-4 on page 154.
2. Updated “Fast PWM Mode” on page 124.
3. Updated Features in “USI – Universal Serial Interface” on page 195.
4. Added “Clock speed considerations.” on page 202.
5. “Errata” on page 379.
1. Updated “Calibrated Internal RC Oscillator” on page 29.
2. Updated “OSCCAL – Oscillator Calibration Register” on page 32
3. Added Table 28-2 on page 329.
1. Updated “Calibrated Internal RC Oscillator” on page 29.
1. Updated “Errata” on page 379.
1. Added “Resources” on page 9.
2. Added Addresses in Registers.
3. Updated number of General Purpose I/O pins.
4. Updated code example in “Bit 0 – IVCE: Interrupt Vector Change Enable”
on page 53.
5. Updated Introduction in “I/O-Ports” on page 59.
6. Updated “SPI – Serial Peripheral Interface” on page 158.
7. Updated “Bit 6 – ACBG: Analog Comparator Bandgap Select” on page
209.
8. Updated Features in “Analog to Digital Converter” on page 211.
9. Updated “Prescaling and Conversion Timing” on page 214.
10. Updated features in “LCD Controller” on page 228.
11. Updated “ATmega329/3290/649/6490 Boot Loader Parameters” on page
290.
12. Updated “DC Characteristics” on page 310.
13. Updated “” on page 334.384
2552K–AVR–04/11
ATmega329/3290/649/6490
35.10 Rev. 2552B – 05/05
35.11 Rev. 2552A –11/04
1. MLF-package alternative changed to “Quad Flat No-Lead/Micro Lead
Frame Package QFN/MLF”.
2. Added “Pin Change Interrupt Timing” on page 54.
3. Updated Table 23-6 on page 242, Table 23-7 on page 243 and Table 27-15
on page 310.
4. Added Figure 27-12 on page 312.
5. Updated Figure 22-9 on page 219 and Figure 27-5 on page 304.
6. Updated algorithm “Enter Programming Mode” on page 299.
7. Added “Supply Current of I/O modules” on page 340.
8. Updated “Ordering Information” on page 372.
1. Initial version.i
2552K–AVR–04/11
ATmega329/3290/649/6490
Table of Contents
Features ..................................................................................................... 1
1 Pin Configurations ................................................................................... 2
2 Overview ................................................................................................... 4
2.1 Block Diagram ...................................................................................................4
2.2 Comparison between ATmega329, ATmega3290, ATmega649 and
ATmega6490 6
2.3 Pin Descriptions .................................................................................................6
3 Resources ................................................................................................. 9
4 Data Retention .......................................................................................... 9
5 About Code Examples ............................................................................. 9
6 AVR CPU Core ........................................................................................ 10
6.1 Overview ..........................................................................................................10
6.2 Architectural Overview .....................................................................................10
6.3 ALU – Arithmetic Logic Unit .............................................................................11
6.4 AVR Status Register ........................................................................................12
6.5 General Purpose Register File ........................................................................13
6.6 Stack Pointer ...................................................................................................14
6.7 Instruction Execution Timing ...........................................................................15
6.8 Reset and Interrupt Handling ...........................................................................15
7 AVR ATmega329/3290/649/6490 Memories ......................................... 18
7.1 In-System Reprogrammable Flash Program Memory .....................................18
7.2 SRAM Data Memory ........................................................................................19
7.3 EEPROM Data Memory ..................................................................................20
7.4 I/O Memory ......................................................................................................21
7.5 Register Description ........................................................................................22
8 System Clock and Clock Options ......................................................... 26
8.1 Clock Systems and their Distribution ...............................................................26
8.2 Clock Sources .................................................................................................27
8.3 Crystal Oscillator .............................................................................................28
8.4 Low-frequency Crystal Oscillator .....................................................................29
8.5 Calibrated Internal RC Oscillator .....................................................................29
8.6 External Clock .................................................................................................31ii
2552K–AVR–04/11
ATmega329/3290/649/6490
8.7 Clock Output Buffer .........................................................................................31
8.8 Timer/Counter Oscillator ..................................................................................32
8.9 System Clock Prescaler ..................................................................................32
8.10 Register Description ........................................................................................32
9 Power Management and Sleep Modes ................................................. 35
9.1 Idle Mode .........................................................................................................36
9.2 ADC Noise Reduction Mode ............................................................................36
9.3 Power-down Mode ...........................................................................................36
9.4 Power-save Mode ............................................................................................36
9.5 Standby Mode .................................................................................................37
9.6 Power Reduction Register ...............................................................................37
9.7 Minimizing Power Consumption ......................................................................37
9.8 Register Description ........................................................................................39
10 System Control and Reset .................................................................... 41
10.1 Resetting the AVR ...........................................................................................41
10.2 Reset Sources .................................................................................................41
10.3 Power-on Reset ...............................................................................................42
10.4 External Reset .................................................................................................43
10.5 Brown-out Detection ........................................................................................43
10.6 Watchdog Reset ..............................................................................................44
10.7 Internal Voltage Reference ..............................................................................44
10.8 Watchdog Timer ..............................................................................................45
10.9 Timed Sequences for Changing the Configuration of the Watchdog Timer ....47
10.10 Register Description ........................................................................................47
11 Interrupts ................................................................................................ 49
11.1 Interrupt Vectors in ATmega329/3290/649/6490 .............................................49
11.2 Register Description ........................................................................................52
12 External Interrupts ................................................................................. 54
12.1 Pin Change Interrupt Timing ............................................................................54
12.2 Register Description ........................................................................................55
13 I/O-Ports .................................................................................................. 59
13.1 Introduction ......................................................................................................59
13.2 Ports as General Digital I/O .............................................................................60
13.3 Alternate Port Functions ..................................................................................65iii
2552K–AVR–04/11
ATmega329/3290/649/6490
13.4 Register Description ........................................................................................87
14 8-bit Timer/Counter0 with PWM ............................................................ 91
14.1 Features ..........................................................................................................91
14.2 Overview ..........................................................................................................91
14.3 Timer/Counter Clock Sources .........................................................................92
14.4 Counter Unit ....................................................................................................93
14.5 Output Compare Unit .......................................................................................93
14.6 Compare Match Output Unit ............................................................................95
14.7 Modes of Operation .........................................................................................97
14.8 Timer/Counter Timing Diagrams ...................................................................101
14.9 Register Description ......................................................................................103
15 Timer/Counter0 and Timer/Counter1 Prescalers .............................. 107
15.1 Register Description ......................................................................................108
16 16-bit Timer/Counter1 .......................................................................... 110
16.1 Features ........................................................................................................110
16.2 Overview ........................................................................................................110
16.3 Accessing 16-bit Registers ............................................................................113
16.4 Timer/Counter Clock Sources .......................................................................116
16.5 Counter Unit ..................................................................................................116
16.6 Input Capture Unit .........................................................................................117
16.7 Output Compare Units ...................................................................................119
16.8 Compare Match Output Unit ..........................................................................122
16.9 Modes of Operation .......................................................................................123
16.10 Timer/Counter Timing Diagrams ...................................................................130
16.11 Register Description ......................................................................................132
17 8-bit Timer/Counter2 with PWM and Asynchronous Operation ...... 139
17.1 Features ........................................................................................................139
17.2 Overview ........................................................................................................139
17.3 Timer/Counter Clock Sources .......................................................................140
17.4 Counter Unit ..................................................................................................140
17.5 Output Compare Unit .....................................................................................141
17.6 Compare Match Output Unit ..........................................................................144
17.7 Modes of Operation .......................................................................................145
17.8 Timer/Counter Timing Diagrams ...................................................................149
17.9 Asynchronous Operation of Timer/Counter2 .................................................151iv
2552K–AVR–04/11
ATmega329/3290/649/6490
17.10 Timer/Counter Prescaler ...............................................................................152
17.11 Register Description ......................................................................................153
18 SPI – Serial Peripheral Interface ......................................................... 158
18.1 Features ........................................................................................................158
18.2 Overview ........................................................................................................158
18.3 SS Pin Functionality ......................................................................................163
18.4 Data Modes ...................................................................................................164
18.5 Register Description ......................................................................................165
19 USART0 ................................................................................................. 168
19.1 Features ........................................................................................................168
19.2 Overview ........................................................................................................168
19.3 Clock Generation ...........................................................................................169
19.4 Frame Formats ..............................................................................................172
19.5 USART Initialization .......................................................................................173
19.6 Data Transmission – The USART Transmitter ..............................................175
19.7 Data Reception – The USART Receiver .......................................................177
19.8 Asynchronous Data Reception ......................................................................181
19.9 Multi-processor Communication Mode ..........................................................185
19.10 Examples of Baud Rate Setting .....................................................................186
19.11 Register Description ......................................................................................190
20 USI – Universal Serial Interface .......................................................... 195
20.1 Features ........................................................................................................195
20.2 Overview ........................................................................................................195
20.3 Functional Descriptions .................................................................................196
20.4 Alternative USI Usage ...................................................................................202
20.5 Register Descriptions ....................................................................................203
21 Analog Comparator ............................................................................. 207
21.1 Overview ........................................................................................................207
21.2 Analog Comparator Multiplexed Input ...........................................................208
21.3 Register Description ......................................................................................209
22 Analog to Digital Converter ................................................................ 211
22.1 Features ........................................................................................................211
22.2 Operation .......................................................................................................212
22.3 Starting a Conversion ....................................................................................213v
2552K–AVR–04/11
ATmega329/3290/649/6490
22.4 Prescaling and Conversion Timing ................................................................214
22.5 Changing Channel or Reference Selection ...................................................216
22.6 ADC Conversion Result .................................................................................221
22.7 Register Description ......................................................................................223
23 LCD Controller ..................................................................................... 228
23.1 Features ........................................................................................................228
23.2 Mode of Operation .........................................................................................231
23.3 LCD Usage ....................................................................................................235
23.4 Register Description ......................................................................................239
24 JTAG Interface and On-chip Debug System ..................................... 245
24.1 Features ........................................................................................................245
24.2 Overview ........................................................................................................245
24.3 Test Access Port – TAP ................................................................................245
24.4 TAP Controller ...............................................................................................247
24.5 Using the Boundary-scan Chain ....................................................................248
24.6 Using the On-chip Debug System .................................................................248
24.7 On-chip Debug Specific JTAG Instructions ...................................................249
24.8 Using the JTAG Programming Capabilities ...................................................250
24.9 Bibliography ...................................................................................................250
24.10 Register Description ......................................................................................250
25 IEEE 1149.1 (JTAG) Boundary-scan ................................................... 251
25.1 Features ........................................................................................................251
25.2 System Overview ...........................................................................................251
25.3 Data Registers ...............................................................................................251
25.4 Boundary-scan Specific JTAG Instructions ...................................................253
25.5 Boundary-scan Related Register in I/O Memory ...........................................254
25.6 Boundary-scan Chain ....................................................................................255
25.7 ATmega329/3290/649/6490 Boundary-scan Order .......................................264
25.8 Boundary-scan Description Language Files ..................................................277
26 Boot Loader Support – Read-While-Write Self-Programming ......... 278
26.1 Features ........................................................................................................278
26.2 Application and Boot Loader Flash Sections .................................................278
26.3 Read-While-Write and No Read-While-Write Flash Sections ........................278
26.4 Boot Loader Lock Bits ...................................................................................281
26.5 Entering the Boot Loader Program ................................................................282vi
2552K–AVR–04/11
ATmega329/3290/649/6490
26.6 Addressing the Flash During Self-Programming ...........................................283
26.7 Self-Programming the Flash ..........................................................................283
26.8 Register Description ......................................................................................291
27 Memory Programming ......................................................................... 293
27.1 Program And Data Memory Lock Bits ...........................................................293
27.2 Fuse Bits ........................................................................................................294
27.3 Signature Bytes .............................................................................................296
27.4 Calibration Byte .............................................................................................296
27.5 Parallel Programming Parameters, Pin Mapping, and Commands ...............296
27.6 Parallel Programming ....................................................................................299
27.7 Serial Downloading ........................................................................................308
27.8 Programming via the JTAG Interface ............................................................313
28 Electrical Characteristics .................................................................... 326
28.1 Absolute Maximum Ratings* .........................................................................326
28.2 DC Characteristics .........................................................................................326
28.3 Speed Grades ...............................................................................................328
28.4 Clock Characteristics .....................................................................................329
28.5 System and Reset Characteristics ................................................................330
28.6 SPI Timing Characteristics ............................................................................331
28.7 ADC Characteristics ......................................................................................333
28.8 LCD Controller Characteristics ......................................................................334
29 Typical Characteristics ........................................................................ 335
30 Register Summary ............................................................................... 365
31 Instruction Set Summary .................................................................... 369
32 Ordering Information ........................................................................... 372
32.1 ATmega329 ...................................................................................................372
32.2 ATmega3290 .................................................................................................373
32.3 ATmega649 ...................................................................................................374
32.4 ATmega6490 .................................................................................................375
33 Packaging Information ........................................................................ 376
33.1 64A ................................................................................................................376
33.2 64M1 ..............................................................................................................377
33.3 100A ..............................................................................................................378vii
2552K–AVR–04/11
ATmega329/3290/649/6490
34 Errata ..................................................................................................... 379
34.1 ATmega329 ...................................................................................................379
34.2 ATmega3290 .................................................................................................380
34.3 ATmega649 ...................................................................................................381
34.4 ATmega6490 .................................................................................................381
35 Datasheet Revision History ................................................................ 382
35.1 Rev. 2552K – 04/11 .......................................................................................382
35.2 Rev. 2552J – 08/07 .......................................................................................382
35.3 Rev. 2552I – 04/07 ........................................................................................382
35.4 Rev. 2552H – 11/06 .......................................................................................382
35.5 Rev. 2552G – 07/06 ......................................................................................383
35.6 Rev. 2552F – 06/06 .......................................................................................383
35.7 Rev. 2552E – 04/06 .......................................................................................383
35.8 Rev. 2552D – 03/06 .......................................................................................383
35.9 Rev. 2552C – 03/06 .......................................................................................383
35.10 Rev. 2552B – 05/05 .......................................................................................384
35.11 Rev. 2552A –11/04 ........................................................................................384
Table of Contents....................................................................................... i2552K–AVR–04/11
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: (+1)(408) 441-0311
Fax: (+1)(408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 1-5 & 16, 19/F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan
9F, Tonetsu Shinkawa Bldg.
1-24-8 Shinkawa
Chuo-ku, Tokyo 104-0033
JAPAN
Tel: (+81)(3) 3523-3551
Fax: (+81)(3) 3523-7581
© 2011 Atmel Corporation. All rights reserved.
Atmel®, Atmel logo and combinations thereof, AVR® and others are registered trademarks or trademarks of Atmel Corporation or its
subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to
any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL
TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY
EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT,
INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS,
BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness
of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice.
Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable
for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications
intended to support or sustain life.
Features
• High Performance, Low Power AVR® 8-Bit Microcontroller
• Advanced RISC Architecture
– 120 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 20 MIPS Throughput at 20 MHz
• Data and Non-volatile Program and Data Memories
– 2/4K Bytes of In-System Self Programmable Flash
• Endurance 10,000 Write/Erase Cycles
– 128/256 Bytes In-System Programmable EEPROM
• Endurance: 100,000 Write/Erase Cycles
– 128/256 Bytes Internal SRAM
– Programming Lock for Flash Program and EEPROM Data Security
• Peripheral Features
– One 8-bit Timer/Counter with Separate Prescaler and Compare Mode
– One 16-bit Timer/Counter with Separate Prescaler, Compare and Capture Modes
– Four PWM Channels
– On-chip Analog Comparator
– Programmable Watchdog Timer with On-chip Oscillator
– USI – Universal Serial Interface
– Full Duplex USART
• Special Microcontroller Features
– debugWIRE On-chip Debugging
– In-System Programmable via SPI Port
– External and Internal Interrupt Sources
– Low-power Idle, Power-down, and Standby Modes
– Enhanced Power-on Reset Circuit
– Programmable Brown-out Detection Circuit
– Internal Calibrated Oscillator
• I/O and Packages
– 18 Programmable I/O Lines
– 20-pin PDIP, 20-pin SOIC, 20-pad MLF/VQFN
• Operating Voltage
– 1.8 – 5.5V
• Speed Grades
– 0 – 4 MHz @ 1.8 – 5.5V
– 0 – 10 MHz @ 2.7 – 5.5V
– 0 – 20 MHz @ 4.5 – 5.5V
• Industrial Temperature Range: -40°C to +85°C
• Low Power Consumption
– Active Mode
• 190 µA at 1.8V and 1MHz
– Idle Mode
• 24 µA at 1.8V and 1MHz
– Power-down Mode
• 0.1 µA at 1.8V and +25°C
8-bit
Microcontroller
with 2/4K Bytes
In-System
Programmable
Flash
ATtiny2313A
ATtiny4313
Rev. 8246B–AVR–09/112
8246B–AVR–09/11
ATtiny2313A/4313
1. Pin Configurations
Figure 1-1. Pinout ATtiny2313A/4313
(PCINT10/RESET/dW) PA2
(PCINT11/RXD) PD0
(PCINT12/TXD) PD1
(PCINT9/XTAL2) PA1
(PCINT8/CLKI/XTAL1) PA0
(PCINT13/CKOUT/XCK/INT0) PD2
(PCINT14/INT1) PD3
(PCINT15/T0) PD4
(PCINT16/OC0B/T1) PD5
GND
20
19
18
17
16
15
14
13
12
11
1
2
3
4
5
6
7
8
9
10
VCC
PB7 (USCK/SCL/SCK/PCINT7)
PB6 (MISO/DO/PCINT6)
PB5 (MOSI/DI/SDA/PCINT5)
PB4 (OC1B/PCINT4)
PB3 (OC1A/PCINT3)
PB2 (OC0A/PCINT2)
PB1 (AIN1/PCINT1)
PB0 (AIN0/PCINT0)
PD6 (ICPI/PCINT17)
PDIP/SOIC
1
2
3
4
5
MLF/VQFN
15
14
13
12
11
20
19
18
17
16
6
7
8
9
10
(PCINT12/TXD) PD1
(PCINT9/XTAL2) PA1
(PCINT8/CLKI/XTAL1) PA0
(PCINT13/CKOUT/XCK/INT0) PD2
(PCINT14/INT1) PD3
(PCINT15/T0) PD4
(PCINT16/OC0B/T1) PD5
GND
(PCINT17/ICPI) PD6
(AIN0/PCINT0) PB0
PB5 (MOSI/DI/SDA/PCINT5)
PB4 (OC1B/PCINT4)
PB3 (OC1A/PCINT3)
PB2 (OC0A/PCINT2)
PB1 (AIN1/PCINT1)
PD0 (RXD/PCINT11)
PA2 (RESET/dW/PCINT10)
VCC
PB7 (USCK/SCL/SCK/PCINT7)
PB6 (MISO/DO/PCINT6)
NOTE: Bottom pad should be soldered to ground.3
8246B–AVR–09/11
ATtiny2313A/4313
1.1 Pin Descriptions
1.1.1 VCC
Digital supply voltage.
1.1.2 GND
Ground.
1.1.3 Port A (PA2..PA0)
Port A is a 3-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port A output buffers have symmetrical drive characteristics with both high sink and source
capability, except PA2 which has the RESET capability. To use pin PA2 as I/O pin, instead of
RESET pin, program (“0”) RSTDISBL fuse. As inputs, Port A pins that are externally pulled low
will source current if the pull-up resistors are activated. The Port A pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
Port A also serves the functions of various special features of the ATtiny2313A/4313 as listed on
page 62.
1.1.4 Port B (PB7..PB0)
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port B also serves the functions of various special features of the ATtiny2313A/4313 as listed on
page 63.
1.1.5 Port D (PD6..PD0)
Port D is a 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port D also serves the functions of various special features of the ATtiny2313A/4313 as listed on
page 67.
1.1.6 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running and provided that the reset pin has not been disabled. The
minimum pulse length is given in Table 22-3 on page 201. Shorter pulses are not guaranteed to
generate a reset. The Reset Input is an alternate function for PA2 and dW.
The reset pin can also be used as a (weak) I/O pin.
1.1.7 XTAL1
Input to the inverting Oscillator amplifier and input to the internal clock operating circuit. XTAL1
is an alternate function for PA0.4
8246B–AVR–09/11
ATtiny2313A/4313
1.1.8 XTAL2
Output from the inverting Oscillator amplifier. XTAL2 is an alternate function for PA1.5
8246B–AVR–09/11
ATtiny2313A/4313
2. Overview
The ATtiny2313A/4313 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced
RISC architecture. By executing powerful instructions in a single clock cycle, the
ATtiny2313A/4313 achieves throughputs approaching 1 MIPS per MHz allowing the system
designer to optimize power consumption versus processing speed.
2.1 Block Diagram
Figure 2-1. Block Diagram
PROGRAM
COUNTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
GND
VCC
INSTRUCTION
DECODER
CONTROL
LINES
STACK
POINTER
SRAM
GENERAL
PURPOSE
REGISTER
ALU
STATUS
REGISTER
PROGRAMMING
LOGIC SPI
8-BIT DATA BUS
XTAL1 XTAL2
RESET
INTERNAL
OSCILLATOR
OSCILLATOR
WATCHDOG
TIMER
TIMING AND
CONTROL
MCU CONTROL
REGISTER
MCU STATUS
REGISTER
TIMER/
COUNTERS
INTERRUPT
UNIT
EEPROM
USI
USART
ANALOG
COMPARATOR
DATA REGISTER
PORTB
DATA DIR.
REG. PORTB
DATA REGISTER
PORTA
DATA DIR.
REG. PORTA
PORTB DRIVERS
PB0 - PB7
PORTA DRIVERS
PA0 - PA2
DATA REGISTER
PORTD
DATA DIR.
REG. PORTD
PORTD DRIVERS
PD0 - PD6
ON-CHIP
DEBUGGER
INTERNAL
CALIBRATED
OSCILLATOR6
8246B–AVR–09/11
ATtiny2313A/4313
The AVR core combines a rich instruction set with 32 general purpose working registers. All the
32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times faster than conventional
CISC microcontrollers.
The ATtiny2313A/4313 provides the following features: 2/4K bytes of In-System Programmable
Flash, 128/256 bytes EEPROM, 128/256 bytes SRAM, 18 general purpose I/O lines, 32 general
purpose working registers, a single-wire Interface for On-chip Debugging, two flexible
Timer/Counters with compare modes, internal and external interrupts, a serial programmable
USART, Universal Serial Interface with Start Condition Detector, a programmable Watchdog
Timer with internal Oscillator, and three software selectable power saving modes. The Idle mode
stops the CPU while allowing the SRAM, Timer/Counters, and interrupt system to continue functioning.
The Power-down mode saves the register contents but freezes the Oscillator, disabling
all other chip functions until the next interrupt or hardware reset. In Standby mode, the crystal/resonator
Oscillator is running while the rest of the device is sleeping. This allows very fast
start-up combined with low-power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The
On-chip ISP Flash allows the program memory to be reprogrammed In-System through an SPI
serial interface, or by a conventional non-volatile memory programmer. By combining an 8-bit
RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel
ATtiny2313A/4313 is a powerful microcontroller that provides a highly flexible and cost effective
solution to many embedded control applications.
The ATtiny2313A/4313 AVR is supported with a full suite of program and system development
tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, In-Circuit Emulators,
and Evaluation kits.
2.2 Comparison Between ATtiny2313A and ATtiny4313
The ATtiny2313A and ATtiny4313 differ only in memory sizes. Table 2-1 summarizes the different
memory sizes for the two devices.
Table 2-1. Memory Size Summary
Device Flash EEPROM RAM
ATtiny2313A 2K Bytes 128 Bytes 128 Bytes
ATtiny4313 4K Bytes 256 Bytes 256 Bytes7
8246B–AVR–09/11
ATtiny2313A/4313
3. About
3.1 Resources
A comprehensive set of drivers, application notes, data sheets and descriptions on development
tools are available for download at http://www.atmel.com/avr.
3.2 Code Examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is included before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.
For I/O Registers located in the extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically, this
means “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”. Note that not all
AVR devices include an extended I/O map.
3.3 Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.8
8246B–AVR–09/11
ATtiny2313A/4313
4. CPU Core
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
4.1 Architectural Overview
Figure 4-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
I/O Module 2
I/O Module1
I/O Module n9
8246B–AVR–09/11
ATtiny2313A/4313
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format.
Every program memory address contains a 16- or 32-bit instruction.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
and other I/O functions. The I/O Memory can be accessed directly, or as the Data Space
locations following those of the Register File, 0x20 - 0x5F.
4.2 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.
4.3 Status Register
The Status Register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.10
8246B–AVR–09/11
ATtiny2313A/4313
The AVR Status Register – SREG – is defined as:
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination
for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N ⊕ V
The S-bit is always an exclusive or between the negative flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
Bit 7 6 5 4 3 2 1 0
0x3F (0x5F) I T H S V N Z C SREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 011
8246B–AVR–09/11
ATtiny2313A/4313
4.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 4-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 4-2. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 4-2, each register is also assigned a data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
4.4.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 4-3.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte12
8246B–AVR–09/11
ATtiny2313A/4313
Figure 4-3. The X-, Y-, and Z-registers
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
4.5 Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x60. The Stack Pointer is decremented by one when data is pushed onto the Stack
with the PUSH instruction, and it is decremented by two when the return address is pushed onto
the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is
popped from the Stack with the POP instruction, and it is incremented by two when data is
popped from the Stack with return from subroutine RET or return from interrupt RETI.
The Stack Pointer is implemented as one 8-bit register in the I/O space.
4.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the
chip. No internal clock division is used.
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
15 XH XL 0
X-register 7 07 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 07 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 70 7 0
R31 (0x1F) R30 (0x1E)
Bit 7 6 5 4 3 2 1 0
0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND13
8246B–AVR–09/11
ATtiny2313A/4313
Figure 4-4. The Parallel Instruction Fetches and Instruction Executions
Figure 4-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Figure 4-5. Single Cycle ALU Operation
4.7 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate program vector in the program memory space. All interrupts are
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt.
The lowest addresses in the program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 48. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request
0. Refer to “Interrupts” on page 48 for more information.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
interrupt flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt
flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU14
8246B–AVR–09/11
ATtiny2313A/4313
cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared,
the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared
by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable
bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the Global
Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have interrupt flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence..
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed
before any pending interrupts, as shown in this example.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
__disable_interrupt();
EECR |= (1< xxx
... ... ... ...
9.2 External Interrupts
External Interrupts are triggered by the INT0 or INT1 pin or any of the PCINT17..0 pins. Observe
that, if enabled, the interrupts will trigger even if the INT0, INT1 or PCINT17..0 pins are configured
as outputs. This feature provides a way of generating a software interrupt. Pin change 0
interrupts PCI0 will trigger if any enabled PCINT7..0 pin toggles. Pin change 1 interrupts PCI1
will trigger if any enabled PCINT10..8 pin toggles. Pin change 2 interrupts PCI2 will trigger, if any
enabled PCINT17..11 pin toggles. The PCMSK0, PCMSK1, and PCMSK2 Registers control
which pins contribute to the pin change interrupts. Pin change interrupts on PCINT17..0 are
detected asynchronously, which means that these interrupts can be used for waking the part
also from sleep modes other than Idle mode.
The INT0 and INT1 interrupts can be triggered by a falling or rising edge or a low level. This is
set up as shown in “MCUCR – MCU Control Register” on page 51. When the INT0 or INT1 interrupt
is enabled and configured as level triggered, the interrupt will trigger as long as the pin is
held low. Note that recognition of falling or rising edge interrupts on INT0 or INT1 requires the
presence of an I/O clock, as described in “Clock Sources” on page 27.50
8246B–AVR–09/11
ATtiny2313A/4313
9.2.1 Low Level Interrupt
A low level interrupt on INT0 or INT1 is detected asynchronously. This means that the interrupt
source can be used for waking the part also from sleep modes other than Idle (the I/O clock is
halted in all sleep modes except Idle).
Note that if a level triggered interrupt is used for wake-up from Power-down, the required level
must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If
the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt
will be generated. The start-up time is defined by the SUT and CKSEL fuses, as described
in “Clock System” on page 26.
If the low level on the interrupt pin is removed before the device has woken up then program
execution will not be diverted to the interrupt service routine but continue from the instruction following
the SLEEP command.
9.2.2 Pin Change Interrupt Timing
A timing example of a pin change interrupt is shown in Figure 9-1.
Figure 9-1. Timing of pin change interrupts
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
PCINT(0)
pin_sync
pcint_syn pin_lat D Q
LE
pcint_setflag
PCIF
clk
clk PCINT(0) in PCMSK(x)
pcint_in_(0) 0
x51
8246B–AVR–09/11
ATtiny2313A/4313
9.3 Register Description
9.3.1 MCUCR – MCU Control Register
The External Interrupt Control Register contains control bits for interrupt sense control.
• Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0
The External Interrupt 1 is activated by the external pin INT1 if the SREG I-flag and the corresponding
interrupt mask are set. The level and edges on the external INT1 pin that activate the
interrupt are defined in Table 9-2. The value on the INT1 pin is sampled before detecting edges.
If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate
an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is
selected, the low level must be held until the completion of the currently executing instruction to
generate an interrupt
• Bits 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding
interrupt mask are set. The level and edges on the external INT0 pin that activate the
interrupt are defined in Table 9-3. The value on the INT0 pin is sampled before detecting edges.
If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate
an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is
selected, the low level must be held until the completion of the currently executing instruction to
generate an interrupt.
Bit 7 6 5 4 3 2 1 0
0x35 (0x55) PUD SM1 SE SM0 ISC11 ISC10 ISC01 ISC00 MCUCR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 9-2. Interrupt 1 Sense Control
ISC11 ISC10 Description
0 0 The low level of INT1 generates an interrupt request.
0 1 Any logical change on INT1 generates an interrupt request.
1 0 The falling edge of INT1 generates an interrupt request.
1 1 The rising edge of INT1 generates an interrupt request.
Table 9-3. Interrupt 0 Sense Control
ISC01 ISC00 Description
0 0 The low level of INT0 generates an interrupt request.
0 1 Any logical change on INT0 generates an interrupt request.
1 0 The falling edge of INT0 generates an interrupt request.
1 1 The rising edge of INT0 generates an interrupt request.52
8246B–AVR–09/11
ATtiny2313A/4313
9.3.2 GIMSK – General Interrupt Mask Register
• Bits 2..0 – Res: Reserved Bits
These bits are reserved and will always read as zero.
• Bit 7 – INT1: External Interrupt Request 1 Enable
When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external
pin interrupt is enabled. The Interrupt Sense Control bits (ISC11 and ISC10) in the External
Interrupt Control Register A (EICRA) define whether the external interrupt is activated on rising
and/or falling edge of the INT1 pin or level sensed. Activity on the pin will cause an interrupt
request even if INT1 is configured as an output. The corresponding interrupt of External Interrupt
Request 1 is executed from the INT1 Interrupt Vector.
• Bit 6 – INT0: External Interrupt Request 0 Enable
When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external
pin interrupt is enabled. The Interrupt Sense Control bits (ISC01 and ISC00) in the External
Interrupt Control Register A (EICRA) define whether the external interrupt is activated on rising
and/or falling edge of the INT0 pin or level sensed. Activity on the pin will cause an interrupt
request even if INT0 is configured as an output. The corresponding interrupt of External Interrupt
Request 0 is executed from the INT0 Interrupt Vector.
• Bit 5 – PCIE0: Pin Change Interrupt Enable 0
When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 0 is enabled. Any change on any enabled PCINT7..0 pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt
Vector. PCINT7..0 pins are enabled individually by the PCMSK0 Register.
• Bit 4 – PCIE2: Pin Change Interrupt Enable 2
When the PCIE2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 2 is enabled. Any change on any enabled PCINT17..11 pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI2
Interrupt Vector. PCINT17..11 pins are enabled individually by the PCMSK2 Register.
• Bit 3 – PCIE1: Pin Change Interrupt Enable 1
When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 1 is enabled. Any change on any enabled PCINT10..8 pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1
Interrupt Vector. PCINT10..8 pins are enabled individually by the PCMSK1 Register.
Bit 7 6 5 4 3 2 1 0
0x3B (0x5B) INT1 INT0 PCIE0 PCIE2 PCIE1 – – – GIMSK
Read/Write R/W R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 053
8246B–AVR–09/11
ATtiny2313A/4313
9.3.3 GIFR – General Interrupt Flag Register
• Bits 2..0 – Res: Reserved Bits
These bits are reserved and will always read as zero.
• Bit 7 – INTF1: External Interrupt Flag 1
When an edge or logic change on the INT1 pin triggers an interrupt request, INTF1 becomes set
(one). If the I-bit in SREG and the INT1 bit in GIMSK are set (one), the MCU will jump to the corresponding
Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared
when INT1 is configured as a level interrupt.
• Bit 6 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pin triggers an interrupt request, INTF0 becomes set
(one). If the I-bit in SREG and the INT0 bit in GIMSK are set (one), the MCU will jump to the corresponding
Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared
when INT0 is configured as a level interrupt.
• Bit 5 – PCIF0: Pin Change Interrupt Flag 0
When a logic change on any PCINT7..0 pin triggers an interrupt request, PCIF becomes set
(one). If the I-bit in SREG and the PCIE0 bit in GIMSK are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively,
the flag can be cleared by writing a logical one to it.
• Bit 4 – PCIF2: Pin Change Interrupt Flag 2
When a logic change on any PCINT17..11 pin triggers an interrupt request, PCIF2 becomes set
(one). If the I-bit in SREG and the PCIE2 bit in GIMSK are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively,
the flag can be cleared by writing a logical one to it.
• Bit 3 – PCIF1: Pin Change Interrupt Flag 1
When a logic change on any PCINT10..8 pin triggers an interrupt request, PCIF1 becomes set
(one). If the I-bit in SREG and the PCIE1 bit in GIMSK are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively,
the flag can be cleared by writing a logical one to it.
9.3.4 PCMSK2 – Pin Change Mask Register 2
• Bit 7 – Res: Reserved Bit
These bits are reserved and will always read as zero.
Bit 7 6 5 4 3 2 1 0
0x3A (0x5A) INTF1 INTF0 PCIF0 PCIF2 PCIF1 – – – GIFR
Read/Write R/W R/W R/W R/W R/W R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x05 (0x25) – PCINT17 PCINT16 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 PCMSK2
Read/Write R R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 054
8246B–AVR–09/11
ATtiny2313A/4313
• Bits 6..0 – PCINT17..11: Pin Change Enable Mask 17..11
Each PCINT17..11 bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT17..11 is set and the PCIE1 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin. If PCINT17..11 is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
9.3.5 PCMSK1 – Pin Change Mask Register 1
• Bits 7:3 – Res: Reserved Bits
These bits are reserved and will always read as zero.
• Bits 2..0 – PCINT10..8: Pin Change Enable Mask 10..8
Each PCINT10..8 bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT10..8 is set and the PCIE1 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin. If PCINT10..8 is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
9.3.6 PCMSK0 – Pin Change Mask Register 0
• Bits 7..0 – PCINT7..0: Pin Change Enable Mask 7..0
Each PCINT7..0 bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT7..0 is set and the PCIE0 bit in GIMSK is set, pin change interrupt is enabled on the
corresponding I/O pin. If PCINT7..0 is cleared, pin change interrupt on the corresponding I/O pin
is disabled.
Bit 7 6 5 4 3 2 1 0
0x04 (0x24) – – – – – PCINT10 PCINT9 PCINT8 PCMSK1
Read/Write R R R R R R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x20 (0x40) PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 PCMSK0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 055
8246B–AVR–09/11
ATtiny2313A/4313
10. I/O-Ports
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports.
This means that the direction of one port pin can be changed without unintentionally changing
the direction of any other pin with the SBI and CBI instructions. The same applies when changing
drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as
input). Each output buffer has symmetrical drive characteristics with both high sink and source
capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually
selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have
protection diodes to both VCC and Ground as indicated in Figure 10-1 on page 55. See “Electrical
Characteristics” on page 198 for a complete list of parameters.
Figure 10-1. I/O Pin Equivalent Schematic
All registers and bit references in this section are written in general form. A lower case “x” represents
the numbering letter for the port, and a lower case “n” represents the bit number. However,
when using the register or bit defines in a program, the precise form must be used. For example,
PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers
and bit locations are listed in “Register Description” on page 69.
Three I/O memory address locations are allocated for each port, one each for the Data Register
– PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins
I/O location is read only, while the Data Register and the Data Direction Register are read/write.
However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding
bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR disables the
pull-up function for all pins in all ports when set.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page
56. Most port pins are multiplexed with alternate functions for the peripheral features on the
device. How each alternate function interferes with the port pin is described in “Alternate Port
Functions” on page 60. Refer to the individual module sections for a full description of the alternate
functions.
Note that enabling the alternate function of some of the port pins does not affect the use of the
other pins in the port as general digital I/O.
Cpin
Logic
Rpu
See Figure
"General Digital I/O" for
Details
Pxn56
8246B–AVR–09/11
ATtiny2313A/4313
10.1 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional
description of one I/O-port pin, here generically called Pxn.
Figure 10-2. General Digital I/O(1)
Note: 1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,
SLEEP, and PUD are common to all ports.
10.1.1 Configuring the Pin
Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in “Register
Description” on page 69, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits
at the PORTx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one,
Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input
pin.
If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is
activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin has to
be configured as an output pin. The port pins are tri-stated when reset condition becomes active,
even if no clocks are running.
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven
high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port
pin is driven low (zero).
clk
RPx
RRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
clkI/O: I/O CLOCK
RDx: READ DDRx
D
L
Q
Q
RESET
RESET
Q
D Q
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BUS
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
WPx
0
1
WRx
WPx: WRITE PINx REGISTER57
8246B–AVR–09/11
ATtiny2313A/4313
10.1.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
Note that the SBI instruction can be used to toggle one single bit in a port.
10.1.3 Switching Between Input and Output
When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn}
= 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output
low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable,
as a high-impedant environment will not notice the difference between a strong high driver
and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all
pull-ups in all ports.
Switching between input with pull-up and output low generates the same problem. The user
must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn}
= 0b10) as an intermediate step.
Table 10-1 summarizes the control signals for the pin value.
10.1.4 Reading the Pin Value
Independent of the setting of Data Direction bit DDxn, the port pin can be read through the
PINxn Register bit. As shown in Figure 10-2 on page 56, the PINxn Register bit and the preceding
latch constitute a synchronizer. This is needed to avoid metastability if the physical pin
changes value near the edge of the internal clock, but it also introduces a delay. Figure 10-3
shows a timing diagram of the synchronization when reading an externally applied pin value.
The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
Figure 10-3. Synchronization when Reading an Externally Applied Pin value
Table 10-1. Port Pin Configurations
DDxn PORTxn
PUD
(in MCUCR) I/O Pull-up Comment
0 0 X Input No Tri-state (Hi-Z)
0 1 0 Input Yes Pxn will source current if ext. pulled low
0 1 1 Input No Tri-state (Hi-Z)
1 0 X Output No Output Low (Sink)
1 1 X Output No Output High (Source)
XXX in r17, PINx
0x00 0xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
tpd, max
tpd, min58
8246B–AVR–09/11
ATtiny2313A/4313
Consider the clock period starting shortly after the first falling edge of the system clock. The latch
is closed when the clock is low, and goes transparent when the clock is high, as indicated by the
shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock
goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated
by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed
between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated
in Figure 10-4 on page 58. The out instruction sets the “SYNC LATCH” signal at the
positive edge of the clock. In this case, the delay tpd through the synchronizer is one system
clock period.
Figure 10-4. Synchronization when Reading a Software Assigned Pin Value
10.1.5 Digital Input Enable and Sleep Modes
As shown in Figure 10-2 on page 56, the digital input signal can be clamped to ground at the
input of the schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep
Controller in Power-down and Standby modes to avoid high power consumption if some input
signals are left floating, or have an analog signal level close to VCC/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt
request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various
other alternate functions as described in “Alternate Port Functions” on page 60.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as
“Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt
is not enabled, the corresponding External Interrupt Flag will be set when resuming from the
above mentioned Sleep mode, as the clamping in these sleep mode produces the requested
logic change.
10.1.6 Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even
though most of the digital inputs are disabled in the deep sleep modes as described above, floating
inputs should be avoided to reduce current consumption in all other modes where the digital
inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up.
In this case, the pull-up will be disabled during reset. If low power consumption during reset is
out PORTx, r16 nop in r17, PINx
0xFF
0x00 0xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t pd59
8246B–AVR–09/11
ATtiny2313A/4313
important, it is recommended to use an external pull-up or pulldown. Connecting unused pins
directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is
accidentally configured as an output.
10.1.7 Program Examples
The following code example shows how to set port A pins 0 and 1 high, 2 and 3 low, and define
the port pins from 4 to 7 as input with a pull-up assigned to port pin 4. The resulting pin values
are read back again, but as previously discussed, a nop instruction is included to be able to read
back the value recently assigned to some of the pins.
Note: Two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1 and 4,
until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as
strong high drivers.
Note: 1. See “Code Examples” on page 7.
Assembly Code Example
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1< CSn2:0 > 1). The number of system clock
cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution.
However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
13.3 External Clock Source
An external clock source applied to the T1/T0 pin can be used as Timer/Counter clock
(clkT1/clkT0). The T1/T0 pin is sampled once every system clock cycle by the pin synchronization
logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 13-1
shows a functional equivalent block diagram of the T1/T0 synchronization and edge detector
logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch
is transparent in the high period of the internal system clock.
The edge detector generates one clkT1/clkT0 pulse for each positive (CSn2:0 = 7) or negative
(CSn2:0 = 6) edge it detects.
Figure 13-1. T1/T0 Pin Sampling
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T1/T0 pin to the counter is updated.
Tn_sync
(To Clock
Select Logic)
Synchronization Edge Detector
D Q D Q
LE
Tn D Q
clkI/O119
8246B–AVR–09/11
ATtiny2313A/4313
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least
one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system
clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency
(Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 13-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 13-1 on page 118.
13.4 Register Description
13.4.1 GTCCR – General Timer/Counter Control Register
• Bits 7..1 – Res: Reserved Bits
These bits are reserved bits in the ATtiny2313A/4313 and will always read as zero.
• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0
When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally
cleared immediately by hardware. Note that Timer/Counter1 and Timer/Counter0 share
the same prescaler and a reset of this prescaler will affect both timers.
PSR10
Clear
clkT1 clkT0
T1
T0
clkI/O
Synchronization
Synchronization
Bit 7 6 5 4 3 2 1 0
0x23 (0x43) — — — — — — — PSR10 GTCCR
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0120
8246B–AVR–09/11
ATtiny2313A/4313
14. USART
14.1 Features
• Full Duplex Operation (Independent Serial Receive and Transmit Registers)
• Asynchronous or Synchronous Operation
• Master or Slave Clocked Synchronous Operation
• High Resolution Baud Rate Generator
• Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits
• Odd or Even Parity Generation and Parity Check Supported by Hardware
• Data OverRun Detection
• Framing Error Detection
• Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
• Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete
• Multi-processor Communication Mode
• Double Speed Asynchronous Communication Mode
14.2 Overview
The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a
highly flexible serial communication device.
A simplified block diagram of the USART Transmitter is shown in Figure 14-1. CPU accessible
I/O Registers and I/O pins are shown in bold.
Figure 14-1. USART Block Diagram(1)
Note: 1. Refer to Figure 1-1 on page 2, Table 10-9 on page 68, and Table 10-6 on page 66 for USART
pin placement.
PARITY
GENERATOR
UBRR[H:L]
UDR (Transmit)
UCSRA UCSRB UCSRC
BAUD RATE GENERATOR
TRANSMIT SHIFT REGISTER
RECEIVE SHIFT REGISTER RxD
TxD PIN
CONTROL
UDR (Receive)
PIN
CONTROL
XCK
DATA
RECOVERY
CLOCK
RECOVERY
PIN
CONTROL
TX
CONTROL
RX
CONTROL
PARITY
CHECKER
DATA BUS
OSC
SYNC LOGIC
Clock Generator
Transmitter
Receiver121
8246B–AVR–09/11
ATtiny2313A/4313
The dashed boxes in the block diagram separate the three main parts of the USART (listed from
the top): Clock Generator, Transmitter and Receiver. Control registers are shared by all units.
The Clock Generation logic consists of synchronization logic for external clock input used by
synchronous slave operation, and the baud rate generator. The XCK (Transfer Clock) pin is only
used by synchronous transfer mode. The Transmitter consists of a single write buffer, a serial
Shift Register, Parity Generator and Control logic for handling different serial frame formats. The
write buffer allows a continuous transfer of data without any delay between frames. The
Receiver is the most complex part of the USART module due to its clock and data recovery
units. The recovery units are used for asynchronous data reception. In addition to the recovery
units, the Receiver includes a Parity Checker, Control logic, a Shift Register and a two level
receive buffer (UDR). The Receiver supports the same frame formats as the Transmitter, and
can detect Frame Error, Data OverRun and Parity Errors.
14.2.1 AVR USART vs. AVR UART – Compatibility
The USART is fully compatible with the AVR UART regarding:
• Bit locations inside all USART Registers.
• Baud Rate Generation.
• Transmitter Operation.
• Transmit Buffer Functionality.
• Receiver Operation.
However, the receive buffering has two improvements that will affect the compatibility in some
special cases:
• A second Buffer Register has been added. The two Buffer Registers operate as a circular
FIFO buffer. Therefore the UDR must only be read once for each incoming data! More
important is the fact that the error flags (FE and DOR) and the ninth data bit (RXB8) are
buffered with the data in the receive buffer. Therefore the status bits must always be read
before the UDR Register is read. Otherwise the error status will be lost since the buffer state
is lost.
• The Receiver Shift Register can now act as a third buffer level. This is done by allowing the
received data to remain in the serial Shift Register (see Figure 14-1) if the Buffer Registers
are full, until a new start bit is detected. The USART is therefore more resistant to Data
OverRun (DOR) error conditions.
The following control bits have changed name, but have same functionality and register location:
• CHR9 is changed to UCSZ2.
• OR is changed to DOR.
14.3 Clock Generation
The Clock Generation logic generates the base clock for the Transmitter and Receiver. The
USART supports four modes of clock operation: Normal asynchronous, Double Speed asynchronous,
Master synchronous and Slave synchronous mode. The UMSEL bit in USART
Control and Status Register C (UCSRC) selects between asynchronous and synchronous operation.
Double Speed (asynchronous mode only) is controlled by the U2X found in the UCSRA
Register. When using synchronous mode (UMSEL = 1), the Data Direction Register for the XCK122
8246B–AVR–09/11
ATtiny2313A/4313
pin (DDR_XCK) controls whether the clock source is internal (Master mode) or external (Slave
mode). The XCK pin is only active when using synchronous mode.
Figure 14-2 shows a block diagram of the clock generation logic.
Figure 14-2. Clock Generation Logic, Block Diagram
Signal description:
txclk Transmitter clock (Internal Signal).
rxclk Receiver base clock (Internal Signal).
xcki Input from XCK pin (internal Signal). Used for synchronous slave
operation.
xcko Clock output to XCK pin (Internal Signal). Used for synchronous master
operation.
fosc XTAL pin frequency (System Clock).
14.3.1 Internal Clock Generation – The Baud Rate Generator
Internal clock generation is used for the asynchronous and the synchronous master modes of
operation. The description in this section refers to Figure 14-2.
The USART Baud Rate Register (UBRR) and the down-counter connected to it function as a
programmable prescaler or baud rate generator. The down-counter, running at system clock
(fosc), is loaded with the UBRR value each time the counter has counted down to zero or when
the UBRRL Register is written. A clock is generated each time the counter reaches zero. This
clock is the baud rate generator clock output (= fosc/(UBRR+1)). The Transmitter divides the
baud rate generator clock output by 2, 8 or 16 depending on mode. The baud rate generator output
is used directly by the Receiver’s clock and data recovery units. However, the recovery units
use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the
UMSEL, U2X and DDR_XCK bits.
Table 14-1 contains equations for calculating the baud rate (in bits per second) and for calculating
the UBRR value for each mode of operation using an internally generated clock source.
Prescaling
Down-Counter /2
UBRR
/4 /2
fosc
UBRR+1
Sync
Register
OSC
XCK
Pin
txclk
U2X
UMSEL
DDR_XCK
0
1
0
1
xcki
xcko
DDR_XCK rxclk 0
1
1
0
Edge
Detector
UCPOL123
8246B–AVR–09/11
ATtiny2313A/4313
Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps)
BAUD Baud rate (in bits per second, bps)
fOSC System Oscillator clock frequency
UBRR Contents of the UBRRH and UBRRL Registers, (0-4095)
Some examples of UBRR values for some system clock frequencies are found in Table 14-9
(see page 142).
14.3.2 Double Speed Operation (U2X)
The transfer rate can be doubled by setting the U2X bit in UCSRA. Setting this bit only has effect
for the asynchronous operation. Set this bit to zero when using synchronous operation.
Setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling
the transfer rate for asynchronous communication. Note however that the Receiver will in this
case only use half the number of samples (reduced from 16 to 8) for data sampling and clock
recovery, and therefore a more accurate baud rate setting and system clock are required when
this mode is used. For the Transmitter, there are no downsides.
14.3.3 External Clock
External clocking is used by the synchronous slave modes of operation. The description in this
section refers to Figure 14-2 for details.
External clock input from the XCK pin is sampled by a synchronization register to minimize the
chance of meta-stability. The output from the synchronization register must then pass through
an edge detector before it can be used by the Transmitter and Receiver. This process introduces
a two CPU clock period delay and therefore the maximum external XCK clock frequency
is limited by the following equation:
Note that fosc depends on the stability of the system clock source. It is therefore recommended to
add some margin to avoid possible loss of data due to frequency variations.
Table 14-1. Equations for Calculating Baud Rate Register Setting
Operating Mode
Equation for Calculating
Baud Rate(1)
Equation for Calculating
UBRR Value
Asynchronous Normal
mode (U2X = 0)
Asynchronous Double
Speed mode (U2X = 1)
Synchronous Master
mode
BAUD f
OSC
16( ) UBRR + 1 = -------------------------------------- UBRR f
OSC
16BAUD = ------------------------ – 1
BAUD f
OSC
8( ) UBRR + 1 = ----------------------------------- UBRR f
OSC
8BAUD = -------------------- – 1
BAUD f
OSC
2( ) UBRR + 1 = ----------------------------------- UBRR f
OSC
2BAUD = -------------------- – 1
f
XCK
f
OSC
4 < -----------124
8246B–AVR–09/11
ATtiny2313A/4313
14.3.4 Synchronous Clock Operation
When synchronous mode is used (UMSEL = 1), the XCK pin will be used as either clock input
(Slave) or clock output (Master). The dependency between the clock edges and data sampling
or data change is the same. The basic principle is that data input (on RxD) is sampled at the
opposite XCK clock edge of the edge the data output (TxD) is changed.
Figure 14-3. Synchronous Mode XCK Timing.
The UCPOL bit UCRSC selects which XCK clock edge is used for data sampling and which is
used for data change. As Figure 14-3 shows, when UCPOL is zero the data will be changed at
rising XCK edge and sampled at falling XCK edge. If UCPOL is set, the data will be changed at
falling XCK edge and sampled at rising XCK edge.
14.4 Frame Formats
A serial frame is defined to be one character of data bits with synchronization bits (start and stop
bits), and optionally a parity bit for error checking. The USART accepts all 30 combinations of
the following as valid frame formats:
• 1 start bit
• 5, 6, 7, 8, or 9 data bits
• no, even or odd parity bit
• 1 or 2 stop bits
A frame starts with the start bit followed by the least significant data bit. Then the next data bits,
up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit
is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can
be directly followed by a new frame, or the communication line can be set to an idle (high) state.
Figure 14-4 illustrates the possible combinations of the frame formats. Bits inside brackets are
optional.
Figure 14-4. Frame Formats
RxD / TxD
XCK
RxD / TxD
UCPOL = 0 XCK
UCPOL = 1
Sample
Sample
(IDLE) St Sp1 [Sp2] 0 2 3 4 [5] [6] [7] [8] [P] 1 (St / IDLE)
FRAME125
8246B–AVR–09/11
ATtiny2313A/4313
St Start bit, always low.
(n) Data bits (0 to 8).
P Parity bit. Can be odd or even.
Sp Stop bit, always high.
IDLE No transfers on the communication line (RxD or TxD). An IDLE line must
be high.
The frame format used by the USART is set by the UCSZ2:0, UPM1:0 and USBS bits in UCSRB
and UCSRC. The Receiver and Transmitter use the same setting. Note that changing the setting
of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter.
The USART Character SiZe (UCSZ2:0) bits select the number of data bits in the frame. The
USART Parity mode (UPM1:0) bits enable and set the type of parity bit. The selection between
one or two stop bits is done by the USART Stop Bit Select (USBS) bit. The Receiver ignores the
second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first
stop bit is zero.
14.4.1 Parity Bit Calculation
The parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity is used, the
result of the exclusive or is inverted. The relation between the parity bit and data bits is as
follows:
Peven Parity bit using even parity
Podd Parity bit using odd parity
dn Data bit n of the character
If used, the parity bit is located between the last data bit and first stop bit of a serial frame.
14.5 USART Initialization
The USART has to be initialized before any communication can take place. The initialization process
normally consists of setting the baud rate, setting frame format and enabling the
Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the
Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the
initialization.
Before doing a re-initialization with changed baud rate or frame format, be sure that there are no
ongoing transmissions during the period the registers are changed. The TXC flag can be used to
check that the Transmitter has completed all transfers, and the RXC flag can be used to check
that there are no unread data in the receive buffer. Note that the TXC flag must be cleared
before each transmission (before UDR is written) if it is used for this purpose.
Peven dn – 1 … d3 d2 d1 d0 0
Podd
⊕⊕⊕⊕⊕⊕
dn – 1 … d3 d2 d1 d0 ⊕⊕⊕⊕⊕⊕ 1
=
=126
8246B–AVR–09/11
ATtiny2313A/4313
The following simple USART initialization code examples show one assembly and one C function
that are equal in functionality. The examples assume asynchronous operation using polling
(no interrupts enabled) and a fixed frame format. The baud rate is given as a function parameter.
For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16
Registers.
Note: 1. See “Code Examples” on page 7.
More advanced initialization routines can be made that include frame format as parameters, disable
interrupts and so on. However, many applications use a fixed setting of the baud and
control registers, and for these types of applications the initialization code can be placed directly
in the main routine, or be combined with initialization code for other I/O modules.
14.6 Data Transmission – The USART Transmitter
The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB
Register. When the Transmitter is enabled, the normal port operation of the TxD pin is overridden
by the USART and given the function as the Transmitter’s serial output. The baud rate,
mode of operation and frame format must be set up once before doing any transmissions. If synchronous
operation is used, the clock on the XCK pin will be overridden and used as
transmission clock.
Assembly Code Example(1)
USART_Init:
; Set baud rate
out UBRRH, r17
out UBRRL, r16
; Enable receiver and transmitter
ldi r16, (1<>8);
UBRRL = (unsigned char)baud;
/* Enable receiver and transmitter */
UCSRB = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}132
8246B–AVR–09/11
ATtiny2313A/4313
The receive function example reads all the I/O Registers into the Register File before any computation
is done. This gives an optimal receive buffer utilization since the buffer location read will
be free to accept new data as early as possible.
14.7.3 Receive Compete Flag and Interrupt
The USART Receiver has one flag that indicates the Receiver state.
The Receive Complete (RXC) flag indicates if there are unread data present in the receive buffer.
This flag is one when unread data exist in the receive buffer, and zero when the receive
buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXEN = 0),
the receive buffer will be flushed and consequently the RXC bit will become zero.
When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive
Complete interrupt will be executed as long as the RXC flag is set (provided that global interrupts
are enabled). When interrupt-driven data reception is used, the receive complete routine
must read the received data from UDR in order to clear the RXC flag, otherwise a new interrupt
will occur once the interrupt routine terminates.
14.7.4 Receiver Error Flags
The USART Receiver has three error flags: Frame Error (FE), Data OverRun (DOR) and Parity
Error (UPE). All can be accessed by reading UCSRA. Common for the error flags is that they are
located in the receive buffer together with the frame for which they indicate the error status. Due
to the buffering of the error flags, the UCSRA must be read before the receive buffer (UDR),
since reading the UDR I/O location changes the buffer read location. Another equality for the
error flags is that they can not be altered by software doing a write to the flag location. However,
all flags must be set to zero when the UCSRA is written for upward compatibility of future
USART implementations. None of the error flags can generate interrupts.
The Frame Error (FE) flag indicates the state of the first stop bit of the next readable frame
stored in the receive buffer. The FE flag is zero when the stop bit was correctly read (as one),
and the FE flag will be one when the stop bit was incorrect (zero). This flag can be used for
detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE flag
is not affected by the setting of the USBS bit in UCSRC since the Receiver ignores all, except for
the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to
UCSRA.
The Data OverRun (DOR) flag indicates data loss due to a receiver buffer full condition. A Data
OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in
the Receive Shift Register, and a new start bit is detected. If the DOR flag is set there was one
or more serial frame lost between the frame last read from UDR, and the next frame read from
UDR. For compatibility with future devices, always write this bit to zero when writing to UCSRA.
The DOR flag is cleared when the frame received was successfully moved from the Shift Register
to the receive buffer.
The Parity Error (UPE) Flag indicates that the next frame in the receive buffer had a Parity Error
when received. If Parity Check is not enabled the UPE bit will always be read zero. For compatibility
with future devices, always set this bit to zero when writing to UCSRA. For more details see
“Parity Bit Calculation” on page 125 and “Parity Checker” on page 132.
14.7.5 Parity Checker
The Parity Checker is active when the high USART Parity mode (UPM1) bit is set. Type of Parity
Check to be performed (odd or even) is selected by the UPM0 bit. When enabled, the Parity133
8246B–AVR–09/11
ATtiny2313A/4313
Checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. The result of the check is stored in the receive buffer together
with the received data and stop bits. The Parity Error (UPE) flag can then be read by software to
check if the frame had a Parity Error.
The UPE bit is set if the next character that can be read from the receive buffer had a Parity
Error when received and the Parity Checking was enabled at that point (UPM1 = 1). This bit is
valid until the receive buffer (UDR) is read.
14.7.6 Disabling the Receiver
In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing
receptions will therefore be lost. When disabled (i.e., the RXEN is set to zero) the Receiver will
no longer override the normal function of the RxD port pin. The Receiver buffer FIFO will be
flushed when the Receiver is disabled. Remaining data in the buffer will be lost
14.7.7 Flushing the Receive Buffer
The receiver buffer FIFO will be flushed when the Receiver is disabled, i.e., the buffer will be
emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal
operation, due to for instance an error condition, read the UDR I/O location until the RXC flag is
cleared. The following code example shows how to flush the receive buffer.
Note: 1. See “Code Examples” on page 7.
14.8 Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data
reception. The clock recovery logic is used for synchronizing the internally generated baud rate
clock to the incoming asynchronous serial frames at the RxD pin. The data recovery logic samples
and low pass filters each incoming bit, thereby improving the noise immunity of the
Receiver. The asynchronous reception operational range depends on the accuracy of the internal
baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
14.8.1 Asynchronous Clock Recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 14-5
illustrates the sampling process of the start bit of an incoming frame. The sample rate is 16 times
Assembly Code Example(1)
USART_Flush:
sbis UCSRA, RXC
ret
in r16, UDR
rjmp USART_Flush
C Code Example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRA & (1<
MSB
MSB
6 5 4 3 2 1 LSB
1 2 3 4 5 6 7 8
6 5 4 3 2 1 LSB
USCK
USCK
DO
DI
A B C D E
CYCLE ( Reference )159
8246B–AVR–09/11
ATtiny2313A/4313
SPITransfer_loop:
out USICR,r17
in r16, USISR
sbrs r16, USIOIF
rjmp SPITransfer_loop
in r16,USIDR
ret
The code is size optimized using only eight instructions (plus return). The code example
assumes that the DO and USCK pins have been enabled as outputs in DDRA. The value stored
in register r16 prior to the function is called is transferred to the slave device, and when the
transfer is completed the data received from the slave is stored back into the register r16.
The second and third instructions clear the USI Counter Overflow Flag and the USI counter
value. The fourth and fifth instructions set three-wire mode, positive edge clock, count at USITC
strobe, and toggle USCK. The loop is repeated 16 times.
The following code demonstrates how to use the USI as an SPI master with maximum speed
(fSCK = fCK/2):
SPITransfer_Fast:
out USIDR,r16
ldi r16,(1< 2 CPU clock cycles
– When fck >= 12MHz: 3 CPU clock cycles
• Minimum high period of serial clock:
– When fck < 12MHz: > 2 CPU clock cycles
– When fck >= 12MHz: 3 CPU clock cycles
VCC
GND
XTAL1
SCK
MISO
MOSI
RESET
+1.8 - 5.5V195
8246B–AVR–09/11
ATtiny2313A/4313
21.3.1 Pin Mapping
The pin mapping is listed in Table 21-7. Note that not all parts use the SPI pins dedicated for the
internal SPI interface.
21.3.2 Programming Algorithm
When writing serial data to the ATtiny2313A/4313, data is clocked on the rising edge of SCK.
When reading data from the ATtiny2313A/4313, data is clocked on the falling edge of SCK. See
Figure 22-6 on page 205 and Figure 22-7 on page 205 for timing details.
To program and verify the ATtiny2313A/4313 in the serial programming mode, the following
sequence is recommended (See Table 21-8, “Serial Programming Instruction Set,” on
page 196):
1. Power-up sequence: apply power between VCC and GND while RESET and SCK are
set to “0”
– In some systems, the programmer can not guarantee that SCK is held low during
power-up. In this case, RESET must be given a positive pulse after SCK has been
set to '0'. The duration of the pulse must be at least tRST plus two CPU clock cycles.
See Table 22-3 on page 201 for definition of minimum pulse width on RESET pin,
tRST
2. Wait for at least 20 ms and then enable serial programming by sending the Programming
Enable serial instruction to the MOSI pin
3. The serial programming instructions will not work if the communication is out of synchronization.
When in sync, the second byte (0x53) will echo back when issuing the
third byte of the Programming Enable instruction
– Regardless if the echo is correct or not, all four bytes of the instruction must be
transmitted
– If the 0x53 did not echo back, give RESET a positive pulse and issue a new
Programming Enable command
4. The Flash is programmed one page at a time. The memory page is loaded one byte at
a time by supplying the 4 LSB of the address and data together with the Load Program
Memory Page instruction.
– To ensure correct loading of the page, the data low byte must be loaded before data
high byte is applied for a given address
– The Program Memory Page is stored by loading the Write Program Memory Page
instruction with the 6 MSB of the address
– If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH before issuing
the next page. (See Table 21-9 on page 197). Accessing the serial programming
interface before the Flash write operation completes can result in incorrect
programming.
5. The EEPROM can be programmed one byte or one page at a time.
Table 21-7. Pin Mapping Serial Programming
Symbol Pins I/O Description
MOSI PB5 I Serial Data in
MISO PB6 O Serial Data out
SCK PB7 I Serial Clock196
8246B–AVR–09/11
ATtiny2313A/4313
– A: Byte programming. The EEPROM array is programmed one byte at a time by
supplying the address and data together with the Write instruction. EEPROM
memory locations are automatically erased before new data is written. If polling
(RDY/BSY) is not used, the user must wait at least tWD_EEPROM before issuing the
next byte (See Table 21-9). In a chip erased device, no 0xFFs in the data file(s) need
to be programmed
– B: Page programming (the EEPROM array is programmed one page at a time). The
memory page is loaded one byte at a time by supplying the 6 LSB of the address
and data together with the Load EEPROM Memory Page instruction. The EEPROM
memory page is stored by loading the Write EEPROM Memory Page Instruction with
the 7 MSB of the address. When using EEPROM page access only byte locations
loaded with the Load EEPROM Memory Page instruction are altered and the
remaining locations remain unchanged. If polling (RDY/BSY) is not used, the user
must wait at least tWD_EEPROM before issuing the next byte (See Table 21-9). In a chip
erased device, no 0xFF in the data file(s) need to be programmed
6. Any memory location can be verified by using the Read instruction, which returns the
content at the selected address at the serial output pin (MISO)
7. At the end of the programming session, RESET can be set high to commence normal
operation
8. Power-off sequence (if required): set RESET to “1”, and turn VCC power off
21.3.3 Programming Instruction Set
The instruction set for serial programming is described in Table 21-8.
Table 21-8. Serial Programming Instruction Set
Instruction
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4 Operation
Programming Enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable Serial Programming after
RESET goes low.
Chip Erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip Erase EEPROM and Flash.
Read Program Memory 0010 H000 0000 00aa bbbb bbbb oooo oooo Read H (high or low) data o from
Program memory at word address a:b.
Load Program Memory Page 0100 H000 000x xxxx xxxx bbbb iiii iiii
Write H (high or low) data i to Program
Memory page at word address b. Data
low byte must be loaded before Data
high byte is applied within the same
address.
Write Program Memory Page 0100 1100 0000 00aa bbbb xxxx xxxx xxxx Write Program Memory Page at
address a:b.
Read EEPROM Memory 1010 0000 000x xxxx xbbb bbbb oooo oooo Read data o from EEPROM memory at
address b.
Write EEPROM Memory 1100 0000 000x xxxx xbbb bbbb iiii iiii Write data i to EEPROM memory at
address b.
Load EEPROM Memory
Page (page access) 1100 0001 0000 0000 0000 00bb iiii iiii
Load data i to EEPROM memory page
buffer. After data is loaded, program
EEPROM page.197
8246B–AVR–09/11
ATtiny2313A/4313
Note: a = address high bits, b = address low bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in, x = don’t care
If the LSB of RDY/BSY data byte out is ‘1’, a programming operation is still pending. Wait until
this bit returns ‘0’ before the next instruction is carried out.
Within the same page, the low data byte must be loaded prior to the high data byte.
After data is loaded to the page buffer, program the EEPROM page.
21.4 Programming Time for Flash and EEPROM
Flash and EEPROM wait times are listed in Table 21-9.
Write EEPROM Memory
Page (page access) 1100 0010 00xx xxxx xbbb bb00 xxxx xxxx Write EEPROM page at address b.
Read Lock bits 0101 1000 0000 0000 xxxx xxxx xxoo oooo
Read Lock bits. “0” = programmed, “1”
= unprogrammed. See Table 20-1 on
page 178 for details.
Write Lock bits 1010 1100 111x xxxx xxxx xxxx 11ii iiii
Write Lock bits. Set bits = “0” to
program Lock bits. See Table 20-1 on
page 178 for details.
Read Signature Byte 0011 0000 000x xxxx xxxx xxbb oooo oooo Read Signature Byte o at address b.
Write Fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram.
Write Fuse High bits 1010 1100 1010 1000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram.
Write Extended Fuse Bits 1010 1100 1010 0100 xxxx xxxx xxxx xxxi Set bits = “0” to program, “1” to
unprogram.
Read Fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo Read Fuse bits. “0” = programmed, “1”
= unprogrammed.
Read Fuse High bits 0101 1000 0000 1000 xxxx xxxx oooo oooo Read Fuse High bits. “0” = programmed,
“1” = unprogrammed.
Read Extended Fuse Bits 0101 0000 0000 1000 xxxx xxxx oooo oooo Read Extended Fuse bits. “0” = programmed,
“1” = unprogrammed.
Read Calibration Byte 0011 1000 000x xxxx 0000 000b oooo oooo Read Calibration Byte at address b.
Poll RDY/BSY 1111 0000 0000 0000 xxxx xxxx xxxx xxxo
If o = “1”, a programming operation is
still busy. Wait until this bit returns to
“0” before applying another command.
Table 21-8. Serial Programming Instruction Set
Instruction
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4 Operation
Table 21-9. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FLASH 4.5 ms
tWD_EEPROM 4.0 ms
tWD_ERASE 9.0 ms
tWD_FUSE 4.5 ms198
8246B–AVR–09/11
ATtiny2313A/4313
22. Electrical Characteristics
22.1 Absolute Maximum Ratings*
22.2 DC Characteristics
Operating Temperature.................................. -55°C to +125°C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ............................................... 40.0 mA
DC Current VCC and GND Pins................................ 200.0 mA
TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min. Typ. Max. Units
VIL
Input Low Voltage except
XTAL1 and RESET pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V -0.5 0.2VCC
0.3VCC
V
VIH
Input High-voltage except
XTAL1 and RESET pins
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.7VCC
(1)
0.6VCC
(1) VCC +0.5 (2) V
VIL1
Input Low Voltage
XTAL1 pin
VCC = 1.8V - 5.5V -0.5 0.1VCC V
VIH1
Input High-voltage
XTAL1 pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.8VCC
(1)
0.7VCC
(1) VCC +0.5 (2) V
VIL2
Input Low Voltage
RESET pin VCC = 1.8V - 5.5V -0.5 0.2VCC V
VIH2
Input High-voltage
RESET pin VCC = 1.8V - 5.5V 0.9VCC
(1) VCC +0.5 (2) V
VIL3
Input Low Voltage
RESET pin as I/O
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V -0.5 0.2VCC
0.3VCC
V
VIH3
Input High-voltage
RESET pin as I/O
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.7VCC
(1)
0.6VCC
(1) VCC +0.5 (2) V
VOL
Output Low Voltage(3)
(Except Reset Pin)(5)
IOL = 20 mA, VCC = 5V
IOL = 10mA, VCC = 3V
0.8
0.6
V
V
VOH
Output High-voltage(4)
(Except Reset Pin)(5)
IOH = -20 mA, VCC = 5V
IOH = -10 mA, VCC = 3V
4.2
2.4
V
V
I
IL
Input Leakage
Current I/O Pin
VCC = 5.5V, pin low
(absolute value) 1(6) µA
IIH
Input Leakage
Current I/O Pin
VCC = 5.5V, pin high
(absolute value) 1(6) µA
RRST Reset Pull-up Resistor 30 60 kΩ
Rpu I/O Pin Pull-up Resistor 20 50 kΩ199
8246B–AVR–09/11
ATtiny2313A/4313
Notes: 1. “Min” means the lowest value where the pin is guaranteed to be read as high.
2. “Max” means the highest value where the pin is guaranteed to be read as low.
3. Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
1] The sum of all IOL, for all ports, should not exceed 60 mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20 mA at VCC = 5V, 10 mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
1] The sum of all IOH, for all ports, should not exceed 60 mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
5. The RESET pin must tolerate high voltages when entering and operating in programming modes and, as a consequence,
has a weak drive strength as compared to regular I/O pins. See Figure 23-29 and Figure 23-30.
6. These are test limits, which account for leakage currents of the test environment. Actual device leakage currents are lower.
7. Values using methods described in “Minimizing Power Consumption” on page 36. Power Reduction is enabled (PRR =
0xFF), the external clock is selected (CKSEL = 0000), and there is no I/O drive.
8. BOD Disabled.
I
CC
Power Supply Current
Active 1MHz, VCC = 2V(7) 0.2 0.55 mA
Active 4MHz, VCC = 3V(7) 1.3 2.5 mA
Active 8MHz, VCC = 5V(7) 3.9 7 mA
Idle 1MHz, VCC = 2V(7) 0.03 0.15 mA
Idle 4MHz, VCC = 3V(7) 0.25 0.6 mA
Idle 8MHz, VCC = 5V(7) 1 2 mA
Power-down mode
WDT enabled, VCC = 3V(8) 4 10 µA
WDT disabled, VCC = 3V(8) < 0.15 2 µA
TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted) (Continued)
Symbol Parameter Condition Min. Typ. Max. Units200
8246B–AVR–09/11
ATtiny2313A/4313
22.3 Speed
The maximum operating frequency of the device is dependent on supply voltage, VCC . The relationship
between supply voltage and maximum operating frequency is piecewise linear, as
shown in Figure 22-1.
Figure 22-1. Maximum Frequency vs. VCC
22.4 Clock Characteristics
22.4.1 Calibrated Internal RC Oscillator Accuracy
It is possible to manually calibrate the internal oscillator to be more accurate than default factory
calibration. Note that the oscillator frequency depends on temperature and voltage. Voltage and
temperature characteristics can be found in Figure 23-46 on page 229, and Figure 23-47 on
page 230.
Notes: 1. Accuracy of oscillator frequency at calibration point (fixed temperature and fixed voltage).
4 MHz
1.8V 5.5V 4.5V
20 MHz
2.7V
10 MHz
Table 22-1. Calibration Accuracy of Internal RC Oscillator
Calibration
Method Target Frequency VCC Temperature
Accuracy at given Voltage
& Temperature(1)
Factory
Calibration 4.0 / 8.0MHz 3V 25°C ±10%
User
Calibration
Fixed frequency within:
3.1 – 4.7 MHz /
7.3 – 9.1MHz
Fixed voltage within:
1.8V – 5.5V
Fixed temperature
within:
-40°C – 85°C
±2%201
8246B–AVR–09/11
ATtiny2313A/4313
22.4.2 External Clock Drive
Figure 22-2. External Clock Drive Waveform
22.5 System and Reset Characteristics
Notes: 1. When RESET pin used as reset (not as I/O).
2. Not tested in production.
VIL1
VIH1
Table 22-2. External Clock Drive
Symbol Parameter
VCC = 1.8 - 5.5V VCC = 2.7 - 5.5V VCC = 4.5 - 5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL Clock Frequency 0 4 0 10 0 20 MHz
tCLCL Clock Period 250 100 50 ns
tCHCX High Time 100 40 20 ns
tCLCX Low Time 100 40 20 ns
tCLCH Rise Time 2.0 1.6 0.5 µs
tCHCL Fall Time 2.0 1.6 0.5 µs
ΔtCLCL Change in period from one clock cycle to the next 2 2 2 %
Table 22-3. Reset, Brown-out, and Internal Voltage Characteristics
Symbol Parameter Condition Min Typ Max Units
VRST
RESET Pin Threshold
Voltage 0.2 VCC 0.8VCC V
t
RST
Minimum pulse width on
RESET Pin (1)(2) VCC = 1.8 - 5.5V 2.5 µs
VHYST
Brown-out Detector
Hysteresis (2) 50 mV
tBOD
Min Pulse Width on
Brown-out Reset (2) 2 µs
VBG
Internal bandgap reference
voltage
VCC = 2.7V
TA = 25°C 1.0 1.1 1.2 V
tBG
Internal bandgap reference
start-up time (2)
VCC = 2.7V
TA = 25°C 40 70 µs
IBG
Internal bandgap reference
current consumption (2)
VCC = 2.7V
TA = 25°C 15 µA202
8246B–AVR–09/11
ATtiny2313A/4313
22.5.1 Enhanced Power-On Reset
Notes: 1. Values are guidelines, only.
2. Threshold where device is released from reset when voltage is rising.
3. The Power-on Reset will not work unless the supply voltage has been below VPOA.
22.5.2 Brown-Out Detection
Note: 1. VBOT may be below nominal minimum operating voltage for some devices. For devices where
this is the case, the device is tested down to VCC = VBOT during the production test. This guarantees
that a Brown-out Reset will occur before VCC drops to a voltage where correct
operation of the microcontroller is no longer guaranteed.
22.6 Analog Comparator Characteristics
Note: All parameters are based on simulation results and they are not tested in production
Table 22-4. Characteristics of Enhanced Power-On Reset. TA = -40 – 85°C
Symbol Parameter Min(1) Typ(1) Max(1) Units
VPOR Release threshold of power-on reset (2) 1.1 1.4 1.6 V
VPOA Activation threshold of power-on reset (3) 0.6 1.3 1.6 V
SRON Power-On Slope Rate 0.01 V/ms
Table 22-5. VBOT vs. BODLEVEL Fuse Coding
BODLEVEL [1:0] Fuses Min(1) Typ(1) Max(1) Units
11 BOD Disabled
10 1.7 1.8 2.0
01 2.5 2.7 2.9 V
00 4.1 4.3 4.5
Table 22-6. Analog Comparator Characteristics, TA = -40°C - 85°C
Symbol Parameter Condition Min Typ Max Units
VACIO Input Offset Voltage VCC = 5V, VIN = VCC / 2 < 10 40 mV
IACLK Input Leakage Current VCC = 5V, VIN = VCC / 2 -50 50 nA
tACPD
Analog Propagation Delay
(from saturation to slight overdrive)
VCC = 2.7V 750
ns
VCC = 4.0V 500
Analog Propagation Delay
(large step change)
VCC = 2.7V 100
VCC = 4.0V 75
tDPD Digital Propagation Delay VCC = 1.8V - 5.5 1 2 CLK203
8246B–AVR–09/11
ATtiny2313A/4313
22.7 Parallel Programming Characteristics
Notes: 1. tWLRH is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits
commands.
2. tWLRH_CE is valid for the Chip Erase command.
Table 22-7. Parallel Programming Characteristics, VCC = 5V ± 10%
Symbol Parameter Min Typ Max Units
VPP Programming Enable Voltage 11.5 12.5 V
I
PP Programming Enable Current 250 μA
t
DVXH Data and Control Valid before XTAL1 High 67 ns
tXLXH XTAL1 Low to XTAL1 High 200 ns
tXHXL XTAL1 Pulse Width High 150 ns
tXLDX Data and Control Hold after XTAL1 Low 67 ns
tXLWL XTAL1 Low to WR Low 0 ns
tXLPH XTAL1 Low to PAGEL high 0 ns
tPLXH PAGEL low to XTAL1 high 150 ns
tBVPH BS1 Valid before PAGEL High 67 ns
tPHPL PAGEL Pulse Width High 150 ns
tPLBX BS1 Hold after PAGEL Low 67 ns
tWLBX BS2/1 Hold after WR Low 67 ns
tPLWL PAGEL Low to WR Low 67 ns
tBVWL BS1 Valid to WR Low 67 ns
tWLWH WR Pulse Width Low 150 ns
tWLRL WR Low to RDY/BSY Low 0 1 μs
t
WLRH WR Low to RDY/BSY High(1) 3.7 4.5 ms
tWLRH_CE WR Low to RDY/BSY High for Chip Erase(2) 7.5 9 ms
tXLOL XTAL1 Low to OE Low 0 ns
tBVDV BS1 Valid to DATA valid 0 1000 ns
tOLDV OE Low to DATA Valid 1000 ns
t
OHDZ OE High to DATA Tri-stated 1000 ns204
8246B–AVR–09/11
ATtiny2313A/4313
Figure 22-3. Parallel Programming Timing, Including some General Timing Requirements
Figure 22-4. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
Note: 1. The timing requirements shown in Figure 22-3 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading
operation.
Figure 22-5. Parallel Programming Timing, Reading Sequence (within the Same Page) with
Timing Requirements(1)
Note: 1. The timing requirements shown in Figure 22-3 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading
operation.
Data & Contol
(DATA, XA0/1, BS1, BS2)
XTAL1 t
XHXL
t
WLWH
t
DVXH t
XLDX
t
PLWL
t
WLRH
WR
RDY/BSY
PAGEL t
PHPL
t
PLBX t
BVPH
t
XLWL
t
WLBX
tBVWL
WLRL
XTAL1
PAGEL
t XLXH PLXH t t
XLPH
DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
LOAD DATA
(LOW BYTE)
LOAD DATA
(HIGH BYTE)
LOAD DATA LOAD ADDRESS
(LOW BYTE)
XTAL1
OE
DATA ADDR0 (Low Byte) DATA (Low Byte) DATA (High Byte) ADDR1 (Low Byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
READ DATA
(LOW BYTE)
READ DATA
(HIGH BYTE)
LOAD ADDRESS
(LOW BYTE)
t
BVDV
t
OLDV
t
XLOL
t
OHDZ205
8246B–AVR–09/11
ATtiny2313A/4313
22.8 Serial Programming Characteristics
Figure 22-6. Serial Programming Timing
Note: 2 tCLCL for fck < 12 MHz, 3 tCLCL for fck >= 12 MHz
Figure 22-7. Serial Programming Waveform
Table 22-8. Serial Programming Characteristics, TA = -40°C to 85°C, VCC = 1.8 - 5.5V (Unless
Otherwise Noted)
Symbol Parameter Min Typ Max Units
1/tCLCL Oscillator Frequency (ATtiny2313A/4313) 0 4 MHz
tCLCL Oscillator Period (ATtiny2313A/4313) 250 ns
1/tCLCL
Oscillator Frequency (ATtiny2313A/4313, VCC =
4.5V - 5.5V) 0 20 MHz
t
CLCL
Oscillator Period (ATtiny2313A/4313, VCC =
4.5V - 5.5V) 50 ns
tSHSL SCK Pulse Width High 2 tCLCL* ns
tSLSH SCK Pulse Width Low 2 tCLCL* ns
tOVSH MOSI Setup to SCK High tCLCL ns
t
SHOX MOSI Hold after SCK High 2 tCLCL ns
tSLIV SCK Low to MISO Valid 100 ns
MOSI
MISO
SCK
t
OVSH
t
SHSL
t t
SHOX SLSH
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT206
8246B–AVR–09/11
ATtiny2313A/4313
23. Typical Characteristics
The data contained in this section is largely based on simulations and characterization of similar
devices in the same process and design methods. Thus, the data should be treated as indications
of how the part will behave.
The following charts show typical behavior. These figures are not tested during manufacturing.
During characterisation devices are operated at frequencies higher than test limits but they are
not guaranteed to function properly at frequencies higher than the ordering code indicates.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. Current consumption is a function of several factors such as operating
voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed
and ambient temperature. The dominating factors are operating voltage and frequency.
A sine wave generator with rail-to-rail output is used as clock source but current consumption in
Power-Down mode is independent of clock selection. The difference between current consumption
in Power-Down mode with Watchdog Timer enabled and Power-Down mode with Watchdog
Timer disabled represents the differential current drawn by the Watchdog Timer.
The current drawn from pins with a capacitive load may be estimated (for one pin) as follows:
where VCC = operating voltage, CL = load capacitance and fSW = average switching frequency of
I/O pin.
23.1 Effect of Power Reduction
Peripheral modules are enabled and disabled via control bits in the Power Reduction Register.
See “Power Reduction Register” on page 35 for details.
I
CP VCC CL × × f
SW ≈
Table 23-1. Additional Current Consumption (Absolute) for Peripherals of ATtiny2313A/4313
PRR bit
Typical numbers
VCC = 2V, f = 1MHz VCC = 3V, f = 4MHz VCC = 5V, f = 8MHz
PRTIM0 2 µA 11 µA 50 µA
PRTIM1 5 µA 30 µA 120 µA
PRUSI 2 µA 11 µA 50 µA
PRUSART 4 µA 22 µA 95 µA207
8246B–AVR–09/11
ATtiny2313A/4313
23.2 ATtiny2313A
23.2.1 Current Consumption in Active Mode
Figure 23-1. Active Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
Figure 23-2. Active Supply Current vs. Frequency (1 - 20 MHz)
ACTIVE SUPPLY CURRENT vs. LOW FREQUENCY (ATtiny2313A)
(PRR=0xFF)
5.5 V
5.0 V
4.5 V
3.3 V
2.7 V
1.8 V
0
0,2
0,4
0,6
0,8
1
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
ACTIVE SUPPLY CURRENT vs. FREQUENCY (ATtiny2313A)
(PRR=0xFF)
0
2
4
6
8
10
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
1.8V
2.7V
3.3V
4.5V
5.0V
5.5V208
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-3. Active Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
Figure 23-4. Active Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 8 MHz
85 °C
25 °C
-40 °C
0
1
2
3
4
5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 1 MHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)209
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-5. Active Supply Current vs. VCC (Internal RC Oscillator, 128 KHz)
23.2.2 Current Consumption in Idle Mode
Figure 23-6. Idle Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 128 KHz
85 °C
25 °C
-40 °C
0
0,02
0,04
0,06
0,08
0,1
0,12
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
IDLE SUPPLY CURRENT vs. LOW FREQUENCY (ATtiny2313A)
(PRR=0xFF)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0,16
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)210
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-7. Idle Supply Current vs. Frequency (1 - 20 MHz)
Figure 23-8. Idle Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
IDLE SUPPLY CURRENT vs. FREQUENCY (ATtiny2313A)
(PRR=0xFF)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,5
1
1,5
2
2,5
3
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
IDLE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 8 MHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)211
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-9. Idle Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
Figure 23-10. Idle Supply Current vs. VCC (Internal RC Oscillator, 128 KHz)
IDLE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 1 MHz
85 °C
25 °C
-40 °C
0
0,05
0,1
0,15
0,2
0,25
0,3
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
IDLE SUPPLY CURRENT vs. VCC (ATtiny2313A)
INTERNAL RC OSCILLATOR, 128 KHz
85 °C
25 °C
-40 °C
0
0,005
0,01
0,015
0,02
0,025
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)212
8246B–AVR–09/11
ATtiny2313A/4313
23.2.3 Current Consumption in Power-down Mode
Figure 23-11. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
Figure 23-12. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
POWER-DOWN SUPPLY CURRENT vs. VCC (ATtiny2313A)
WATCHDOG TIMER DISABLED
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
POWER-DOWN SUPPLY CURRENT vs. VCC (ATtiny2313A)
WATCHDOG TIMER ENABLED
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
7
8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)213
8246B–AVR–09/11
ATtiny2313A/4313
23.2.4 Current Consumption in Reset
Figure 23-13. Reset Supply Current vs. VCC (0.1 - 1.0 MHz, Excluding Current Through The
Reset Pull-up)
Figure 23-14. Reset Supply Current vs. VCC (1 - 20 MHz, Excluding Current Through The Reset
Pull-up)
RESET SUPPLY CURRENT vs. VCC (ATtiny2313A)
EXCLUDING CURRENT THROUGH THE RESET PULLUP
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
RESET SUPPLY CURRENT vs. VCC (ATtiny2313A)
EXCLUDING CURRENT THROUGH THE RESET PULLUP
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,8
2
2,2
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)214
8246B–AVR–09/11
ATtiny2313A/4313
23.2.5 Current Consumption of Peripheral Units
Figure 23-15. Brownout Detector Current vs. VCC
Figure 23-16. Programming Current vs. VCC (ATtiny2313A)
Note: Above programming current based on simulation and characterisation of similar device
(ATtiny24A).
BROWNOUT DETECTOR CURRENT vs. VCC (ATtiny2313A)
BOD level = 1.8V
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
PROGRAMMING CURRENT vs. VCC
85 °C
25 °C
-40 °C
0
1000
2000
3000
4000
5000
6000
7000
8000
9000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)215
8246B–AVR–09/11
ATtiny2313A/4313
23.2.6 Pull-up Resistors
Figure 23-17. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 1.8V)
Figure 23-18. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 2.7V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny2313A)
0
10
20
30
40
50
60
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C
85 °C
25 °C
-40 °C
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny2313A)
0
10
20
30
40
50
60
70
80
90
0 0,5 1 1,5 2 2,5 3
VOP (V)
IOP (uA)216
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-19. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 5V)
Figure 23-20. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 1.8V)
85 °C
25 °C
-40 °C
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny2313A)
0
20
40
60
80
100
120
140
160
0 1 2 3 4 5 6
VOP (V)
IOP (uA)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny2313A)
-40 °C
25 °C
85 °C 0
5
10
15
20
25
30
35
40
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VRESET (V)
IRESET (uA)217
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-21. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
Figure 23-22. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
-40 °C
25 °C
85 °C
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny2313A)
0
10
20
30
40
50
60
0 0,5 1 1,5 2 2,5 3
VRESET (V)
IRESET (uA)
-40 °C
25 °C
85 °C
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny2313A)
0
20
40
60
80
100
120
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
VRESET (V)
IRESET (uA)218
8246B–AVR–09/11
ATtiny2313A/4313
23.2.7 Output Driver Strength
Figure 23-23. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 1.8V)
Figure 23-24. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 3V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny2313A)
Vcc = 1.8V
85 °C
25 °C
-40 °C
0
0,05
0,1
0,15
0,2
0,25
0,3
0,35
0,4
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOL (mA)
VOL (V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny2313A)
Vcc = 3V
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0 2 4 6 8 10
IOL (mA)
VOL (V)219
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-25. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 5V)
Figure 23-26. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 1.8V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny2313A)
Vcc = 5V
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
VOL (V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny2313A)
Vcc = 1.8V
85 °C
25 °C
-40 °C
1,2
1,3
1,4
1,5
1,6
1,7
1,8
1,9
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOH (mA)
VOH (V)220
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-27. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 3V)
Figure 23-28. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 5V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny2313A)
Vcc = 3V
85 °C
25 °C
-40 °C
2,5
2,6
2,7
2,8
2,9
3
3,1
0 2 4 6 8 10
IOH (mA)
VOH (V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny2313A)
Vcc = 5V
85 °C
25 °C
-40 °C
4,3
4,5
4,7
4,9
5,1
0 5 10 15 20
IOH (mA)
VOH (V)221
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-29. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, T = 25°C)
Figure 23-30. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, T = 25°C)
RESET AS I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny2313A)
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
0 1 2 3 4
IOL (mA)
VOL (V)
5.0 V
1.8 V 3.0 V
RESET AS I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny2313A)
5.0 V
3.0 V
1.8 V
0
1
2
3
4
5
0 0,2 0,4 0,6 0,8 1
IOH (mA)
VOH (V)222
8246B–AVR–09/11
ATtiny2313A/4313
23.2.8 Input Thresholds and Hysteresis (for I/O Ports)
Figure 23-31. VIH: Input Threshold Voltage vs. VCC (I/O Pin Read as ‘1’)
Figure 23-32. VIL: Input Threshold Voltage vs. VCC (I/O Pin, Read as ‘0’)
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIH, IO PIN READ AS '1'
0
0,5
1
1,5
2
2,5
3
3,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIL, IO PIN READ AS '0'
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C223
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-33. VIH-VIL: Input Hysteresis vs. VCC (I/O Pin)
Figure 23-34. VIH: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘1’)
I/O PIN INPUT HYSTERESIS vs. VCC (ATtiny2313A)
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
RESET PIN AS I/O THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIH, RESET READ AS '1'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)224
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-35. VIL: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘0’)
Figure 23-36. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin as I/O)
RESET PIN AS I/O THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIL, RESET READ AS '0'
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
RESET PIN AS IO, INPUT HYSTERESIS vs. VCC (ATtiny2313A)
VIL, IO PIN READ AS "0"
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)225
8246B–AVR–09/11
ATtiny2313A/4313
23.2.9 BOD, Bandgap and Reset
Figure 23-37. BOD Thresholds vs. Temperature (BOD Level is 4.3V)
Figure 23-38. BOD Thresholds vs. Temperature (BOD Level is 2.7V)
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 4.3V) (ATtiny2313A)
BODLEVEL = 4.3V
4,22
4,24
4,26
4,28
4,3
4,32
4,34
4,36
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (C)
Threshold (V)
VCC RISING
VCC FALLING
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 2.7V) (ATtiny2313A)
BODLEVEL = 2.7V
2,66
2,68
2,7
2,72
2,74
2,76
2,78
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
VCC RISING
VCC FALLING226
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-39. BOD Thresholds vs. Temperature (BOD Level is 1.8V)
Figure 23-40. Bandgap Voltage vs. Supply Voltage
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 1.8V) (ATtiny2313A)
BODLEVEL = 1.8V
1,78
1,79
1,8
1,81
1,82
1,83
1,84
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
VCC RISING
VCC FALLING
BANDGAP VOLTAGE vs. VCC (ATtiny2313A)
CALIBRATED
0,95
1
1,05
1,1
1,15
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
Vcc (V)
Bandgap Voltage (V)227
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-41. Bandgap Voltage vs. Temperature
Figure 23-42. VIH: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘1’)
BANDGAP VOLTAGE vs. TEMP (ATtiny2313A)
(Vcc=5V)
CALIBRATED
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
1,16
-40 -20 0 20 40 60 80 100
Temperature
Bandgap Voltage (V)
RESET INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIH, IO PIN READ AS '1'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)228
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-43. VIL: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘0’)
Figure 23-44. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin)
RESET INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny2313A)
VIL, IO PIN READ AS '0'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
RESET PIN INPUT HYSTERESIS vs. VCC (ATtiny2313A)
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
85 °C
25 °C
-40 °C229
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-45. Minimum Reset Pulse Width vs. VCC
23.2.10 Internal Oscillator Speed
Figure 23-46. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
MINIMUM RESET PULSE WIDTH vs. VCC (ATtiny2313A)
85 °C
25 °C
-40 °C
0
200
400
600
800
1000
1200
1400
1600
1800
2000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Pulsewidth (ns)
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. OPERATING VOLTAGE (ATtiny2313A)
7
7,2
7,4
7,6
7,8
8
8,2
8,4
8,6
8,8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (MHz)
85 °C
25 °C
-40 °C230
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-47. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature
Figure 23-48. Calibrated 8 MHz RC Oscillator Frequency vs. Osccal Value
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE (ATtiny2313A)
5.0 V
3.0 V
1.8 V
7
7,5
8
8,5
9
-40 -20 0 20 40 60 80 100
Temperature
FRC (MHz)
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE (ATtiny2313A)
(Vcc=3V)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
0 16 32 48 64 80 96 112
OSCCAL (X1)
FRC (MHz)231
8246B–AVR–09/11
ATtiny2313A/4313
23.3 ATtiny4313
23.3.1 Current Consumption in Active Mode
Figure 23-49. Active Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
Figure 23-50. Active Supply Current vs. Frequency (1 - 20 MHz)
ACTIVE SUPPLY CURRENT vs. LOW FREQUENCY (ATtiny4313)
(PRR=0xFF)
5.5 V
5.0 V
4.5 V
3.3 V
2.7 V
1.8 V
0
0,2
0,4
0,6
0,8
1
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
ACTIVE SUPPLY CURRENT vs. FREQUENCY (ATtiny4313)
(PRR=0xFF)
0
2
4
6
8
10
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
1.8V
2.7V
3.3V
4.5V
5.0V
5.5V232
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-51. Active Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
Figure 23-52. Active Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 8 MHz
85 °C
25 °C
-40 °C
0
1
2
3
4
5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 1 MHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)233
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-53. Active Supply Current vs. VCC (Internal RC Oscillator, 128 KHz)
23.3.2 Current Consumption in Idle Mode
Figure 23-54. Idle Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
ACTIVE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 128 KHz
85 °C
25 °C
-40 °C
0
0,02
0,04
0,06
0,08
0,1
0,12
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
IDLE SUPPLY CURRENT vs. LOW FREQUENCY (ATtiny4313)
(PRR=0xFF)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0,16
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)234
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-55. Idle Supply Current vs. Frequency (1 - 20 MHz)
Figure 23-56. Idle Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
IDLE SUPPLY CURRENT vs. FREQUENCY (ATtiny4313)
(PRR=0xFF)
0
0,5
1
1,5
2
2,5
3
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
IDLE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 8 MHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)235
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-57. Idle Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
Figure 23-58. Idle Supply Current vs. VCC (Internal RC Oscillator, 128 KHz)
IDLE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 1 MHz
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
IDLE SUPPLY CURRENT vs. VCC (ATtiny4313)
INTERNAL RC OSCILLATOR, 128 KHz
85 °C
25 °C
-40 °C
0
0,005
0,01
0,015
0,02
0,025
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)236
8246B–AVR–09/11
ATtiny2313A/4313
23.3.3 Current Consumption in Power-down Mode
Figure 23-59. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
Figure 23-60. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
POWER-DOWN SUPPLY CURRENT vs. VCC (ATtiny4313)
WATCHDOG TIMER DISABLED
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
POWER-DOWN SUPPLY CURRENT vs. VCC (ATtiny4313)
WATCHDOG TIMER ENABLED
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
7
8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)237
8246B–AVR–09/11
ATtiny2313A/4313
23.3.4 Current Consumption in Reset
Figure 23-61. Reset Supply Current vs. VCC (0.1 - 1.0 MHz, Excluding Current Through The
Reset Pull-up)
Figure 23-62. Reset Supply Current vs. VCC (1 - 20 MHz, Excluding Current Through The Reset
Pull-up)
RESET SUPPLY CURRENT vs. VCC (ATtiny4313)
EXCLUDING CURRENT THROUGH THE RESET PULLUP
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
RESET SUPPLY CURRENT vs. VCC (ATtiny4313)
EXCLUDING CURRENT THROUGH THE RESET PULLUP
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,8
2
2,2
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V238
8246B–AVR–09/11
ATtiny2313A/4313
23.3.5 Current Consumption of Peripheral Units
Figure 23-63. Brownout Detector Current vs. VCC
Figure 23-64. Programming Current vs. VCC (ATtiny4313)
Note: Above programming current based on simulation and characterisation of similar device
(ATtiny44A).
BROWNOUT DETECTOR CURRENT vs. VCC (ATtiny4313)
BOD level = 1.8V
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
PROGRAMMING CURRENT vs. VCC
85 °C
25 °C
-40 °C
0
2000
4000
6000
8000
10000
12000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)239
8246B–AVR–09/11
ATtiny2313A/4313
23.3.6 Pull-up Resistors
Figure 23-65. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 1.8V)
Figure 23-66. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 2.7V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny4313)
0
10
20
30
40
50
60
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny4313)
0
10
20
30
40
50
60
70
80
0 0,5 1 1,5 2 2,5 3
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C240
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-67. Pull-up Resistor Current vs. Input Voltage (I/O Pin, VCC = 5V)
Figure 23-68. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 1.8V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE (ATtiny4313)
0
20
40
60
80
100
120
140
160
0 1 2 3 4 5 6
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny4313)
0
5
10
15
20
25
30
35
40
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C241
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-69. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
Figure 23-70. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny4313)
0
10
20
30
40
50
60
0 0,5 1 1,5 2 2,5 3
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE (ATtiny4313)
0
20
40
60
80
100
120
0 1 2 3 4 5 6
VRESET (V)
IRESET (uA)242
8246B–AVR–09/11
ATtiny2313A/4313
23.3.7 Output Driver Strength
Figure 23-71. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 1.8V)
Figure 23-72. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 3V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny4313)
0
0,05
0,1
0,15
0,2
0,25
0,3
0,35
0,4
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOL (mA)
VOL (V)
VCC = 1.8V
85 °C
25 °C
-40 °C
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny4313)
0
0,1
0,2
0,3
0,4
0,5
0,6
0 2 4 6 8 10
IOL (mA)
VOL (V)
VCC = 3V
85 °C
25 °C
-40 °C243
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-73. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 5V)
Figure 23-74. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 1.8V)
I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny4313)
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
VOL (V)
VCC = 5V
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny4313)
1
1,2
1,4
1,6
1,8
2
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOH (mA)
VOH (V)
VCC = 1.8V
85 °C
25 °C
-40 °C244
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-75. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 3V)
Figure 23-76. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 5V)
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny4313)
2,5
2,6
2,7
2,8
2,9
3
3,1
0 2 4 6 8 10
IOH (mA)
VOH (V)
VCC = 3V
85 °C
25 °C
-40 °C
I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny4313)
85 °C
25 °C
-40 °C
4,3
4,5
4,7
4,9
5,1
0 5 10 15 20
IOH (mA)
VOH (V)
VCC = 5V245
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-77. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, T = 25°C)
Figure 23-78. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, T = 25°C)
RESET AS I/O PIN OUTPUT VOLTAGE vs. SINK CURRENT (ATtiny4313)
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
0 1 2 3 4
IOL (mA)
VOL (V)
5.0 V
1.8 V 3.0 V
RESET AS I/O PIN OUTPUT VOLTAGE vs. SOURCE CURRENT (ATtiny4313)
0
1
2
3
4
5
0 0,2 0,4 0,6 0,8 1
IOH (mA)
VOH (V)
5.0V
3.0V
1.8V246
8246B–AVR–09/11
ATtiny2313A/4313
23.3.8 Input Thresholds and Hysteresis (for I/O Ports)
Figure 23-79. VIH: Input Threshold Voltage vs. VCC (I/O Pin Read as ‘1’)
Figure 23-80. VIL: Input Threshold Voltage vs. VCC (I/O Pin, Read as ‘0’)
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIH, IO PIN READ AS '1'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
3,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIL, IO PIN READ AS '0'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)247
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-81. VIH-VIL: Input Hysteresis vs. VCC (I/O Pin)
Figure 23-82. VIH: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘1’)
I/O PIN INPUT HYSTERESIS vs. VCC (ATtiny4313)
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
RESET PIN AS I/O THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIH, RESET READ AS '1'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)248
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-83. VIL: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as ‘0’)
Figure 23-84. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin as I/O)
RESET PIN AS I/O THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIL, RESET READ AS '0'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
RESET PIN AS IO, INPUT HYSTERESIS vs. VCC (ATtiny4313)
VIL, IO PIN READ AS "0"
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)249
8246B–AVR–09/11
ATtiny2313A/4313
23.3.9 BOD, Bandgap and Reset
Figure 23-85. BOD Thresholds vs. Temperature (BOD Level is 4.3V)
Figure 23-86. BOD Thresholds vs. Temperature (BOD Level is 2.7V)
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 4.3V) (ATtiny4313)
BOD Level = 4.3V
4,16
4,18
4,2
4,22
4,24
4,26
4,28
4,3
4,32
4,34
4,36
4,38
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (C)
Threshold (V)
VCC RISING
VCC FALLING
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 2.7V) (ATtiny4313)
BOD Level = 2.7V
2,62
2,64
2,66
2,68
2,7
2,72
2,74
2,76
2,78
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
VCC RISING
VCC FALLING250
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-87. BOD Thresholds vs. Temperature (BOD Level is 1.8V)
Figure 23-88. Bandgap Voltage vs. Supply Voltage
1,76
1,77
1,78
1,79
1,8
1,81
1,82
1,83
1,84
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
BOD THRESHOLDS vs. TEMPERATURE (BOD Level set to 1.8V) (ATtiny4313)
BOD Level = 1.8V
VCC RISING
VCC FALLING
BANDGAP VOLTAGE vs. VCC (ATtiny4313)
CALIBRATED
0,95
1
1,05
1,1
1,15
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Bandgap Voltage (V)251
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-89. Bandgap Voltage vs. Temperature
Figure 23-90. VIH: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘1’)
BANDGAP VOLTAGE vs. TEMP (ATtiny4313)
(Vcc=5V)
CALIBRATED
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
-40 -20 0 20 40 60 80 100
Temperature
Bandgap Voltage (V)
RESET INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIH, IO PIN READ AS '1'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)252
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-91. VIL: Input Threshold Voltage vs. VCC (Reset Pin, Read as ‘0’)
Figure 23-92. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin)
RESET INPUT THRESHOLD VOLTAGE vs. VCC (ATtiny4313)
VIL, IO PIN READ AS '0'
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
RESET PIN INPUT HYSTERESIS vs. VCC (ATtiny4313)
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)253
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-93. Minimum Reset Pulse Width vs. VCC
23.3.10 Internal Oscillator Speed
Figure 23-94. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
MINIMUM RESET PULSE WIDTH vs. VCC (ATtiny4313)
85 °C
25 °C
-40 °C
0
200
400
600
800
1000
1200
1400
1600
1800
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Pulsewidth (ns)
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. OPERATING VOLTAGE (ATtiny4313)
7,2
7,4
7,6
7,8
8
8,2
8,4
8,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (MHz)
85 °C
25 °C
-40 °C254
8246B–AVR–09/11
ATtiny2313A/4313
Figure 23-95. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature
Figure 23-96. Calibrated 8 MHz RC Oscillator Frequency vs. Osccal Value
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE (ATtiny4313)
5.0 V
3.0 V
1.8 V
7,4
7,6
7,8
8
8,2
8,4
8,6
-40 -20 0 20 40 60 80 100
Temperature
FRC (MHz)
CALIBRATED 8.0MHz RC OSCILLATOR FREQUENCY vs. OSCCAL VALUE (ATtiny4313)
(Vcc=3V)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
0 16 32 48 64 80 96 112
OSCCAL (X1)
FRC (MHz)255
8246B–AVR–09/11
ATtiny2313A/4313
24. Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x3F (0x5F) SREG I T H S V N Z C 9
0x3E (0x5E) Reserved – – – – – – – –
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 12
0x3C (0x5C) OCR0B Timer/Counter0 – Compare Register B 86
0x3B (0x5B) GIMSK INT1 INT0 PCIE0 PCIE2 PCIE1 – – – 52
0x3A (0x5A) GIFR INTF1 INTF0 PCIF0 PCIF2 PCIF1 – – – 53
0x39 (0x59) TIMSK TOIE1 OCIE1A OCIE1B – ICIE1 OCIE0B TOIE0 OCIE0A 87, 116
0x38 (0x58) TIFR TOV1 OCF1A OCF1B – ICF1 OCF0B TOV0 OCF0A 87, 117
0x37 (0x57) SPMCSR – – RSIG CTPB RFLB PGWRT PGERS SPMEN 176
0x36 (0x56) OCR0A Timer/Counter0 – Compare Register A 86
0x35 (0x55) MCUCR PUD SM1 SE SM0 ISC11 ISC10 ISC01 ISC00 37, 51, 69
0x34 (0x54) MCUSR – – – – WDRF BORF EXTRF PORF 45
0x33 (0x53) TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00 85
0x32 (0x52) TCNT0 Timer/Counter0 (8-bit) 86
0x31 (0x51) OSCCAL – CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 32
0x30 (0x50) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 82
0x2F (0x4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 111
0x2E (0x4E) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 113
0x2D (0x4D) TCNT1H Timer/Counter1 – Counter Register High Byte 115
0x2C (0x4C) TCNT1L Timer/Counter1 – Counter Register Low Byte 115
0x2B (0x4B) OCR1AH Timer/Counter1 – Compare Register A High Byte 115
0x2A (0x4A) OCR1AL Timer/Counter1 – Compare Register A Low Byte 115
0x29 (0x49) OCR1BH Timer/Counter1 – Compare Register B High Byte 115
0x28 (0x48) OCR1BL Timer/Counter1 – Compare Register B Low Byte 115
0x27 (0x47) Reserved – – – – – – – –
0x26 (0x46) CLKPR CLKPCE – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 32
0x25 (0x45) ICR1H Timer/Counter1 - Input Capture Register High Byte 116
0x24 (0x44) ICR1L Timer/Counter1 - Input Capture Register Low Byte 116
0x23 (0x43) GTCCR – – – – – – – PSR10 119
0x22 (ox42) TCCR1C FOC1A FOC1B – – – – – – 114
0x21 (0x41) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 45
0x20 (0x40) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 54
0x1F (0x3F) Reserved – – – – – – – –
0x1E (0x3E) EEAR – EEPROM Address Register 24
0x1D (0x3D) EEDR EEPROM Data Register 23
0x1C (0x3C) EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE 24
0x1B (0x3B) PORTA – – – – – PORTA2 PORTA1 PORTA0 69
0x1A (0x3A) DDRA – – – – – DDA2 DDA1 DDA0 69
0x19 (0x39) PINA – – – – – PINA2 PINA1 PINA0 70
0x18 (0x38) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 70
0x17 (0x37) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 70
0x16 (0x36) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 70
0x15 (0x35) GPIOR2 General Purpose I/O Register 2 25
0x14 (0x34) GPIOR1 General Purpose I/O Register 1 25
0x13 (0x33) GPIOR0 General Purpose I/O Register 0 25
0x12 (0x32) PORTD – PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 70
0x11 (0x31) DDRD – DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 70
0x10 (0x30) PIND – PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 70
0x0F (0x2F) USIDR USI Data Register 166
0x0E (0x2E) USISR USISIF USIOIF USIPF USIDC USICNT3 USICNT2 USICNT1 USICNT0 165
0x0D (0x2D) USICR USISIE USIOIE USIWM1 USIWM0 USICS1 USICS0 USICLK USITC 163
0x0C (0x2C) UDR UART Data Register (8-bit) 137
0x0B (0x2B) UCSRA RXC TXC UDRE FE DOR UPE U2X MPCM 138
0x0A (0x2A) UCSRB RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 139
0x09 (0x29) UBRRL UBRRH[7:0] 141
0x08 (0x28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 168
0x07 (0x27) BODCR – – – – – – BODS BODSE 38
0x06 (0x26) PRR – – – – PRTIM1 PRTIM0 PRUSI PRUSART 37
0x05 (0x25) PCMSK2 – PCINT17 PCINT16 PCINT15 PCINT14 PCINT13 PCINT12 PCINT11 53
0x04 (0x24) PCMSK1 – – – – – PCINT10 PCINT9 PCINT8 54
0x03 (0x23) UCSRC UMSEL1 UMSEL0 UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL 140
0x02 (0x22) UBRRH – – – – UBRRH[11:8] 141
0x01 (0x21) DIDR – – – – – – AIN1D AIN0D 169
0x00 (0x20) USIBR USI Buffer Register 167256
8246B–AVR–09/11
ATtiny2313A/4313
Notes: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the status flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used. When addressing I/O
Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. 257
8246B–AVR–09/11
ATtiny2313A/4313
25. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd ← Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd ← Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd ← Rd • Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd ← Rd • K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd ← Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd ← Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd ← Rd ⊕ Rr Z,N,V 1
COM Rd One’s Complement Rd ← 0xFF − Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd ← 0x00 − Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd ← Rd • (0xFF - K) Z,N,V 1
INC Rd Increment Rd ← Rd + 1 Z,N,V 1
DEC Rd Decrement Rd ← Rd − 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V 1
SER Rd Set Register Rd ← 0xFF None 1
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC ← PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC ← Z None 2
RCALL k Relative Subroutine Call PC ← PC + k + 1 None 3
ICALL Indirect Call to (Z) PC ← Z None 3
RET Subroutine Return PC ← STACK None 4
RETI Interrupt Return PC ← STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd − Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd − Rr − C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd − K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2
LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z,C,N,V 1258
8246B–AVR–09/11
ATtiny2313A/4313
ROR Rd Rotate Right Through Carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1
BSET s Flag Set SREG(s) ← 1 SREG(s) 1
BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) ← T None 1
SEC Set Carry C ← 1 C1
CLC Clear Carry C ← 0 C 1
SEN Set Negative Flag N ← 1 N1
CLN Clear Negative Flag N ← 0 N 1
SEZ Set Zero Flag Z ← 1 Z1
CLZ Clear Zero Flag Z ← 0 Z 1
SEI Global Interrupt Enable I ← 1 I1
CLI Global Interrupt Disable I ← 0 I 1
SES Set Signed Test Flag S ← 1 S1
CLS Clear Signed Test Flag S ← 0 S 1
SEV Set Twos Complement Overflow. V ← 1 V1
CLV Clear Twos Complement Overflow V ← 0 V 1
SET Set T in SREG T ← 1 T1
CLT Clear T in SREG T ← 0 T 1
SEH Set Half Carry Flag in SREG H ← 1 H1
CLH Clear Half Carry Flag in SREG H ← 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd ← Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd ← Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd ← K None 1
LD Rd, X Load Indirect Rd ← (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd ← (X), X ← X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X ← X - 1, Rd ← (X) None 2
LD Rd, Y Load Indirect Rd ← (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd ← (Y), Y ← Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y ← Y - 1, Rd ← (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd ← (Y + q) None 2
LD Rd, Z Load Indirect Rd ← (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd ← (Z), Z ← Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z ← Z - 1, Rd ← (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd ← (k) None 2
ST X, Rr Store Indirect (X) ← Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) ← Rr, X ← X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X ← X - 1, (X) ← Rr None 2
ST Y, Rr Store Indirect (Y) ← Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) ← Rr, Y ← Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y ← Y - 1, (Y) ← Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) ← Rr None 2
ST Z, Rr Store Indirect (Z) ← Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) ← Rr, Z ← Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z ← Z - 1, (Z) ← Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2
STS k, Rr Store Direct to SRAM (k) ← Rr None 2
LPM Load Program Memory R0 ← (Z) None 3
LPM Rd, Z Load Program Memory Rd ← (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd ← (Z), Z ← Z+1 None 3
SPM Store Program Memory (Z) ← R1:R0 None -
IN Rd, P In Port Rd ← P None 1
OUT P, Rr Out Port P ← Rr None 1
PUSH Rr Push Register on Stack STACK ← Rr None 2
POP Rd Pop Register from Stack Rd ← STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #Clocks259
8246B–AVR–09/11
ATtiny2313A/4313
26. Ordering Information
Notes: 1. For speed vs. supply voltage, see section 22.3 “Speed” on page 200.
2. All packages are Pb-free, halide-free and fully green, and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– U or N: matte tin
– R: tape & reel
4. Can also be supplied in wafer form. Contact your local Atmel sales office for ordering information and minimum quantities.
5. NiPdAu finish
6. Topside markings :
– 1st Line: T2313
– 2nd Line: Axx
– 3rd Line: xxx
26.1 ATtiny2313A
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
20 1.8 – 5.5 Industrial
(-40°C to +85°C) (4)
20P3 ATtiny2313A-PU
20S
ATtiny2313A-SU
ATtiny2313A-SUR
20M1
ATtiny2313A-MU
ATtiny2313A-MUR
20M2 (5)(6) ATtiny2313A-MMH
ATtiny2313A-MMHR
Package Type
20P3 20-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
20S 20-lead, 0.300" Wide, Plastic Gull Wing Small Outline Package (SOIC)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead / Micro Lead Frame Package (MLF)
20M2 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)260
8246B–AVR–09/11
ATtiny2313A/4313
Notes: 1. For speed vs. supply voltage, see section 22.3 “Speed” on page 200.
2. All packages are Pb-free, halide-free and fully green, and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– U or N: matte tin
– R: tape & reel
4. Can also be supplied in wafer form. Contact your local Atmel sales office for ordering information and minimum quantities.
5. NiPdAu finish
6. Topside markings:
– 1st Line: T4313
– 2nd Line: Axx
– 3rd Line: xxx
26.2 ATtiny4313
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
20 1.8 – 5.5 Industrial
(-40°C to +85°C) (4)
20P3 ATtiny4313-PU
20S
ATtiny4313-SU
ATtiny4313-SUR
20M1
ATtiny4313-MU
ATtiny4313-MUR
20M2 (5)(6) ATtiny4313-MMH
ATtiny4313-MMHR
Package Type
20P3 20-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
20S 20-lead, 0.300" Wide, Plastic Gull Wing Small Outline Package (SOIC)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No-Lead/Micro Lead Frame Package (MLF)
20M2 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)261
8246B–AVR–09/11
ATtiny2313A/4313
27. Packaging Information
27.1 20P3
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
20P3, 20-lead (0.300"/7.62 mm Wide) Plastic Dual
Inline Package (PDIP) 20P3 D
2010-10-19
PIN
1
E1
A1
B
E
B1
C
L
SEATING PLANE
A
D
e
eB
eC
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A – – 5.334
A1 0.381 – –
D 25.493 – 25.984 Note 2
E 7.620 – 8.255
E1 6.096 – 7.112 Note 2
B 0.356 – 0.559
B1 1.270 – 1.551
L 2.921 – 3.810
C 0.203 – 0.356
eB – – 10.922
eC 0.000 – 1.524
e 2.540 TYP
Notes:
1. This package conforms to JEDEC reference MS-001, Variation AD.
2. Dimensions D and E1 do not include mold Flash or Protrusion.
Mold Flash or Protrusion shall not exceed 0.25 mm (0.010"). 262
8246B–AVR–09/11
ATtiny2313A/4313
27.2 20S263
8246B–AVR–09/11
ATtiny2313A/4313
27.3 20M1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
20M1, 20-pad, 4 x 4 x 0.8 mm Body, Lead Pitch 0.50 mm, 20M1 A
10/27/04
2.6 mm Exposed Pad, Micro Lead Frame Package (MLF)
A 0.70 0.75 0.80
A1 – 0.01 0.05
A2 0.20 REF
b 0.18 0.23 0.30
D 4.00 BSC
D2 2.45 2.60 2.75
E 4.00 BSC
E2 2.45 2.60 2.75
e 0.50 BSC
L 0.35 0.40 0.55
SIDE VIEW
Pin 1 ID
Pin #1
Notch
(0.20 R)
BOTTOM VIEW
TOP VIEW
Note: Reference JEDEC Standard MO-220, Fig. 1 (SAW Singulation) WGGD-5.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D
E
e
A2
A1
A
D2
E2
0.08 C
L
1
2
3
b
1
2
3264
8246B–AVR–09/11
ATtiny2313A/4313
27.4 20M2
TITLE GPC DRAWING NO. REV.
Package Drawing Contact:
packagedrawings@atmel.com ZFC B 20M2
20M2, 20-pad, 3 x 3 x 0.85 mm Body, Lead Pitch 0.45 mm,
1.55 x 1.55 mm Exposed Pad, Thermally Enhanced
Plastic Very Thin Quad Flat No Lead Package (VQFN)
10/24/08
15
14
13
12
11
1
2
3
4
5
16 17 18 19 20
10 9 8 7 6
D2
E2
e
b
L K
Pin #1 Chamfer
(C 0.3)
D
E SIDE VIEW
A1
y
Pin 1 ID
BOTTOM VIEW
TOP VIEW
A
C
C0.18 (8X)
0.3 Ref (4x)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A 0.75 0.80 0.85
A1 0.00 0.02 0.05
b 0.17 0.22 0.27
C 0.152
D 2.90 3.00 3.10
D2 1.40 1.55 1.70
E 2.90 3.00 3.10
E2 1.40 1.55 1.70
e – 0.45 –
L 0.35 0.40 0.45
K 0.20 – –
y 0.00 – 0.08 265
8246B–AVR–09/11
ATtiny2313A/4313
28. Errata
The revision letters in this section refer to the revision of the corresponding ATtiny2313A/4313
device.
28.1 ATtiny2313A
28.1.1 Rev. D
No known errata.
28.1.2 Rev. A – C
These device revisions were referred to as ATtiny2313/ATtiny2313V.
28.2 ATtiny4313
28.2.1 Rev. A
No known errata.266
8246B–AVR–09/11
ATtiny2313A/4313
29. Datasheet Revision History
29.1 Rev. 8246B – 10/11
1. Updated device status from Preliminary to Final.
2. Updated document template.
3. Added order codes for tape&reel devices, on page 259 and page 260
4. Updated figures:
– Figure 23-33 on page 223
– Figure 23-44 on page 228
– Figure 23-81 on page 247
– Figure 23-92 on page 252
5. Updated sections:
– Section 5. “Memories” on page 16
– Section 19. “Self-Programming” on page 173
– Section 20. “Lock Bits, Fuse Bits and Device Signature” on page 178
– Section 21. “External Programming” on page 184
– Section 26. “Ordering Information” on page 259
29.2 Rev. 8246A – 11/09
1. Initial revision. Created from document 2543_t2313.
2. Updated datasheet template.
3. Added VQFN in the Pinout Figure 1-1 on page 2.
4. Added Section 7.2 “Software BOD Disable” on page 35.
5. Added Section 7.3 “Power Reduction Register” on page 35.
6. Updated Table 7-2, “Sleep Mode Select,” on page 37.
7. Added Section 7.5.3 “BODCR – Brown-Out Detector Control Register” on page 38.
8. Added reset disable function in Figure 8-1 on page 39.
9. Added pin change interrupts PCINT1 and PCINT2 in Table 9-1 on page 48.
10. Added PCINT17..8 and PCMSK2..1 in Section 9.2 “External Interrupts” on page 49.
11. Added Section 9.3.4 “PCMSK2 – Pin Change Mask Register 2” on page 53.
12. Added Section 9.3.5 “PCMSK1 – Pin Change Mask Register 1” on page 54.
13. Updated Section 10.2.1 “Alternate Functions of Port A” on page 62.
14. Updated Section 10.2.2 “Alternate Functions of Port B” on page 63.
15. Updated Section 10.2.3 “Alternate Functions of Port D” on page 67.
16. Added UMSEL1 and UMSEL0 in Section 14.10.4 “UCSRC – USART Control and Status
Register C” on page 140.
17. Added Section 15. “USART in SPI Mode” on page 146.
18. Added USI Buffer Register (USIBR) in Section 16.2 “Overview” on page 156 and in Figure
16-1 on page 156.
19. Added Section 16.5.4 “USIBR – USI Buffer Register” on page 167.
20. Updated Section 19.6.3 “Reading Device Signature Imprint Table from Firmware” on
page 175.267
8246B–AVR–09/11
ATtiny2313A/4313
21. Updated Section 19.7.1 “SPMCSR – Store Program Memory Control and Status Register”
on page 176.
22. Added Section 20.3 “Device Signature Imprint Table” on page 180.
23. Updated Section 20.3.1 “Calibration Byte” on page 181.
24. Changed BS to BS1 in Section 20.6.13 “Reading the Signature Bytes” on page 189.
25. Updated Section 22.2 “DC Characteristics” on page 198.
26. Added Section 23.1 “Effect of Power Reduction” on page 206.
27. Updated characteristic plots in Section 23. “Typical Characteristics” for ATtiny2313A
(pages 207 - 230), and added plots for ATtiny4313 (pages 231 - 254).
28. Updated Section 24. “Register Summary” on page 255 .
29. Updated Section 26. “Ordering Information” on page 259, added the package type
20M2 and the ordering code -MMH (VQFN), and added the topside marking note.268
8246B–AVR–09/11
ATtiny2313A/4313i
8246B–AVR–09/11
ATtiny2313A/4313
Table of Contents
Features ..................................................................................................... 1
1 Pin Configurations ................................................................................... 2
1.1 Pin Descriptions .................................................................................................3
2 Overview ................................................................................................... 5
2.1 Block Diagram ...................................................................................................5
2.2 Comparison Between ATtiny2313A and ATtiny4313 ........................................6
3 About ......................................................................................................... 7
3.1 Resources .........................................................................................................7
3.2 Code Examples .................................................................................................7
3.3 Data Retention ...................................................................................................7
4 CPU Core .................................................................................................. 8
4.1 Architectural Overview .......................................................................................8
4.2 ALU – Arithmetic Logic Unit ...............................................................................9
4.3 Status Register ..................................................................................................9
4.4 General Purpose Register File ........................................................................10
4.5 Stack Pointer ...................................................................................................12
4.6 Instruction Execution Timing ...........................................................................12
4.7 Reset and Interrupt Handling ...........................................................................13
5 Memories ................................................................................................ 15
5.1 Program Memory (Flash) .................................................................................15
5.2 Data Memory (SRAM) and Register Files .......................................................16
5.3 Data Memory (EEPROM) ................................................................................17
5.4 Register Description ........................................................................................22
6 Clock System ......................................................................................... 25
6.1 Clock Subsystems ...........................................................................................25
6.2 Clock Sources .................................................................................................26
6.3 System Clock Prescaler ..................................................................................30
6.4 Clock Output Buffer .........................................................................................31
6.5 Register Description ........................................................................................31
7 Power Management and Sleep Modes ................................................. 33
7.1 Sleep Modes ....................................................................................................33
7.2 Software BOD Disable .....................................................................................34ii
8246B–AVR–09/11
ATtiny2313A/4313
7.3 Power Reduction Register ...............................................................................34
7.4 Minimizing Power Consumption ......................................................................35
7.5 Register Description ........................................................................................36
8 System Control and Reset .................................................................... 38
8.1 Resetting the AVR ...........................................................................................38
8.2 Reset Sources .................................................................................................39
8.3 Internal Voltage Reference ..............................................................................41
8.4 Watchdog Timer ..............................................................................................41
8.5 Register Description ........................................................................................44
9 Interrupts ................................................................................................ 47
9.1 Interrupt Vectors ..............................................................................................47
9.2 External Interrupts ...........................................................................................48
9.3 Register Description ........................................................................................50
10 I/O-Ports .................................................................................................. 54
10.1 Ports as General Digital I/O .............................................................................55
10.2 Alternate Port Functions ..................................................................................59
10.3 Register Description ........................................................................................68
11 8-bit Timer/Counter0 with PWM ............................................................ 70
11.1 Features ..........................................................................................................70
11.2 Overview ..........................................................................................................70
11.3 Clock Sources .................................................................................................71
11.4 Counter Unit ....................................................................................................71
11.5 Output Compare Unit .......................................................................................72
11.6 Compare Match Output Unit ............................................................................74
11.7 Modes of Operation .........................................................................................75
11.8 Timer/Counter Timing Diagrams .....................................................................79
11.9 Register Description ........................................................................................81
12 16-bit Timer/Counter1 ............................................................................ 88
12.1 Features ..........................................................................................................88
12.2 Overview ..........................................................................................................88
12.3 Timer/Counter Clock Sources .........................................................................90
12.4 Counter Unit ....................................................................................................90
12.5 Input Capture Unit ...........................................................................................91
12.6 Output Compare Units .....................................................................................93iii
8246B–AVR–09/11
ATtiny2313A/4313
12.7 Compare Match Output Unit ............................................................................95
12.8 Modes of Operation .........................................................................................96
12.9 Timer/Counter Timing Diagrams ...................................................................104
12.10 Accessing 16-bit Registers ............................................................................106
12.11 Register Description ......................................................................................110
13 Timer/Counter0 and Timer/Counter1 Prescalers .............................. 117
13.1 Internal Clock Source ....................................................................................117
13.2 Prescaler Reset .............................................................................................117
13.3 External Clock Source ...................................................................................117
13.4 Register Description ......................................................................................118
14 USART ................................................................................................... 119
14.1 Features ........................................................................................................119
14.2 Overview ........................................................................................................119
14.3 Clock Generation ...........................................................................................120
14.4 Frame Formats ..............................................................................................123
14.5 USART Initialization .......................................................................................124
14.6 Data Transmission – The USART Transmitter ..............................................125
14.7 Data Reception – The USART Receiver .......................................................129
14.8 Asynchronous Data Reception ......................................................................132
14.9 Multi-processor Communication Mode ..........................................................135
14.10 Register Description ......................................................................................136
14.11 Examples of Baud Rate Setting .....................................................................141
15 USART in SPI Mode ............................................................................. 145
15.1 Features ........................................................................................................145
15.2 Overview ........................................................................................................145
15.3 Clock Generation ...........................................................................................145
15.4 SPI Data Modes and Timing ..........................................................................146
15.5 Frame Formats ..............................................................................................147
15.6 Data Transfer .................................................................................................149
15.7 AVR USART MSPIM vs. AVR SPI ................................................................151
15.8 Register Description ......................................................................................152
16 USI – Universal Serial Interface .......................................................... 155
16.1 Features ........................................................................................................155
16.2 Overview ........................................................................................................155
16.3 Functional Descriptions .................................................................................156iv
8246B–AVR–09/11
ATtiny2313A/4313
16.4 Alternative USI Usage ...................................................................................162
16.5 Register Description ......................................................................................162
17 Analog Comparator ............................................................................. 167
17.1 Register Description ......................................................................................167
18 debugWIRE On-chip Debug System .................................................. 169
18.1 Features ........................................................................................................169
18.2 Overview ........................................................................................................169
18.3 Physical Interface ..........................................................................................169
18.4 Software Break Points ...................................................................................170
18.5 Limitations of debugWIRE .............................................................................170
18.6 Register Description ......................................................................................171
19 Self-Programming ................................................................................ 172
19.1 Features ........................................................................................................172
19.2 Overview ........................................................................................................172
19.3 Lock Bits ........................................................................................................172
19.4 Self-Programming the Flash ..........................................................................172
19.5 Preventing Flash Corruption ..........................................................................175
19.6 Programming Time for Flash when Using SPM ............................................175
19.7 Register Description ......................................................................................175
20 Lock Bits, Fuse Bits and Device Signature ....................................... 177
20.1 Lock Bits ........................................................................................................177
20.2 Fuse Bits ........................................................................................................178
20.3 Device Signature Imprint Table .....................................................................179
20.4 Reading Lock Bits, Fuse Bits and Signature Data from Software .................180
21 External Programming ........................................................................ 183
21.1 Memory Parametrics .....................................................................................183
21.2 Parallel Programming ....................................................................................183
21.3 Serial Programming .......................................................................................192
21.4 Programming Time for Flash and EEPROM .................................................196
22 Electrical Characteristics .................................................................... 198
22.1 Absolute Maximum Ratings* .........................................................................198
22.2 DC Characteristics .........................................................................................198
22.3 Speed ............................................................................................................199
22.4 Clock Characteristics .....................................................................................200v
8246B–AVR–09/11
ATtiny2313A/4313
22.5 System and Reset Characteristics ................................................................201
22.6 Analog Comparator Characteristics ...............................................................202
22.7 Parallel Programming Characteristics ...........................................................203
22.8 Serial Programming Characteristics ..............................................................205
23 Typical Characteristics ........................................................................ 206
23.1 Effect of Power Reduction .............................................................................206
23.2 ATtiny2313A ..................................................................................................207
23.3 ATtiny4313 ....................................................................................................231
24 Register Summary ............................................................................... 255
25 Instruction Set Summary .................................................................... 257
26 Ordering Information ........................................................................... 259
26.1 ATtiny2313A ..................................................................................................259
26.2 ATtiny4313 ....................................................................................................260
27 Packaging Information ........................................................................ 261
27.1 20P3 ..............................................................................................................261
27.2 20S ................................................................................................................262
27.3 20M1 ..............................................................................................................263
27.4 20M2 ..............................................................................................................264
28 Errata ..................................................................................................... 265
28.1 ATtiny2313A ..................................................................................................265
28.2 ATtiny4313 ....................................................................................................265
29 Datasheet Revision History ................................................................ 266
29.1 Rev. 8246B – 10/11 .......................................................................................266
29.2 Rev. 8246A – 11/09 .......................................................................................2668246B–AVR–09/11
Headquarters International
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: 1(408) 441-0311
Fax: 1(408) 487-2600
Atmel Asia Limited
Unit 01-5 & 16, 19/F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (852) 2245-6100
Fax: (852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan
9F, Tonetsu Shinkawa Bldg.
1-24-8 Shinkawa
Chuo-ku, Tokyo 104-0033
JAPAN
Tel: (81) 3-3523-3551
Fax: (81) 3-3523-7581
Product Contact
Web Site
www.atmel.com
Technical Support
avr@atmel.com
Sales Contact
www.atmel.com/contacts
Literature Requests
www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any
intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND CONDITIONS
OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY
WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL
DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF
THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications
and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided
otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel’s products are not intended, authorized, or warranted for use
as components in applications intended to support or sustain life.
© 2011 Atmel Corporation. All rights reserved. Atmel®, logo and combinations thereof, AVR® and others are registered trademarks or trademarks
of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
Features
• High Performance, Low Power AVR® 8-bit Microcontroller
• Advanced RISC Architecture
– 120 Powerful Instructions – Most Single Clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
• High Endurance, Non-volatile Memory Segments
– 2K/4K/8K Bytes of In-System, Self-programmable Flash Program Memory
• Endurance: 10,000 Write/Erase Cycles
– 128/256/512 Bytes of In-System Programmable EEPROM
• Endurance: 100,000 Write/Erase Cycles
– 128/256/512 Bytes of Internal SRAM
– Data Retention: 20 years at 85°C / 100 years at 25°C
– Programming Lock for Self-programming Flash & EEPROM Data Security
• Peripheral Features
– One 8-bit and One 16-bit Timer/Counter with Two PWM Channels, Each
– 10-bit ADC
• 8 Single-ended Channels
• 12 Differential ADC Channel Pairs with Programmable Gain (1x / 20x)
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
– Universal Serial Interface
• Special Microcontroller Features
– debugWIRE On-chip Debug System
– In-System Programmable via SPI Port
– Internal and External Interrupt Sources
• Pin Change Interrupt on 12 Pins
– Low Power Idle, ADC Noise Reduction, Standby and Power-down Modes
– Enhanced Power-on Reset Circuit
– Programmable Brown-out Detection Circuit with Software Disable Function
– Internal Calibrated Oscillator
– On-chip Temperature Sensor
• I/O and Packages
– Available in 20-pin QFN/MLF/VQFN, 14-pin SOIC, 14-pin PDIP and 15-ball UFBGA
– Twelve Programmable I/O Lines
• Operating Voltage:
– 1.8 – 5.5V
• Speed Grade:
– 0 – 4 MHz @ 1.8 – 5.5V
– 0 – 10 MHz @ 2.7 – 5.5V
– 0 – 20 MHz @ 4.5 – 5.5V
• Industrial Temperature Range: -40°C to +85°C
• Low Power Consumption
– Active Mode:
• 210 µA at 1.8V and 1 MHz
– Idle Mode:
• 33 µA at 1.8V and 1 MHz
– Power-down Mode:
• 0.1 µA at 1.8V and 25°C
8-bit
Microcontroller
with 2K/4K/8K
Bytes In-System
Programmable
Flash
ATtiny24A
ATtiny44A
ATtiny84A
Rev. 8183F–AVR–06/122
8183F–AVR–06/12
ATtiny24A/44A/84A
1. Pin Configurations
Figure 1-1. Pinout of ATtiny24A/44A/84A
Table 1-1. UFBGA - Pinout ATtiny24A/44A/84A (top view)
1234
A PA5 PA6 PB2
B PA4 PA7 PB1 PB3
C PA3 PA2 PA1 PB0
D PA0 GND GND VCC
1
2
3
4
5
6
7
14
13
12
11
10
9
8
VCC
(PCINT8/XTAL1/CLKI) PB0
(PCINT9/XTAL2) PB1
(PCINT11/RESET/dW) PB3
(PCINT10/INT0/OC0A/CKOUT) PB2
(PCINT7/ICP/OC0B/ADC7) PA7
(PCINT6/OC1A/SDA/MOSI/DI/ADC6) PA6
GND
PA0 (ADC0/AREF/PCINT0)
PA1 (ADC1/AIN0/PCINT1)
PA2 (ADC2/AIN1/PCINT2)
PA3 (ADC3/T0/PCINT3)
PA4 (ADC4/USCK/SCL/T1/PCINT4)
PA5 (ADC5/DO/MISO/OC1B/PCINT5)
PDIP/SOIC
1
2
3
4
5
QFN/MLF/VQFN
15
14
13
12
11
20
19
18
17
16
6
7
8
9
10
NOTE
Bottom pad should be
soldered to ground.
DNC: Do Not Connect
DNC
DNC
GND
VCC
DNC
PA7 (PCINT7/ICP/OC0B/ADC7)
PB2 (PCINT10/INT0/OC0A/CKOUT)
PB3 (PCINT11/RESET/dW)
PB1 (PCINT9/XTAL2)
PB0 (PCINT8/XTAL1/CLKI)
PA5
DNC
DNC
DNC
PA6
Pin 16: PA6 (PCINT6/OC1A/SDA/MOSI/DI/ADC6)
Pin 20: PA5 (ADC5/DO/MISO/OC1B/PCINT5)
(ADC4/USCK/SCL/T1/PCINT4) PA4
(ADC3/T0/PCINT3) PA3
(ADC2/AIN1/PCINT2) PA2
(ADC1/AIN0/PCINT1) PA1
(ADC0/AREF/PCINT0) PA03
8183F–AVR–06/12
ATtiny24A/44A/84A
1.1 Pin Descriptions
1.1.1 VCC
Supply voltage.
1.1.2 GND
Ground.
1.1.3 Port B (PB3:PB0)
Port B is a 4-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability except PB3 which has the RESET capability. To use pin PB3 as an I/O pin, instead of
RESET pin, program (‘0’) RSTDISBL fuse. As inputs, Port B pins that are externally pulled low
will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
Port B also serves the functions of various special features of the ATtiny24A/44A/84A as listed
in Section 10.2 “Alternate Port Functions” on page 58.
1.1.4 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running and provided the reset pin has not been disabled. The minimum
pulse length is given in Table 20-4 on page 176. Shorter pulses are not guaranteed to
generate a reset.
The reset pin can also be used as a (weak) I/O pin.
1.1.5 Port A (PA7:PA0)
Port A is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port A output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port A pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port A pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port A has alternate functions as analog inputs for the ADC, analog comparator, timer/counter,
SPI and pin change interrupt as described in “Alternate Port Functions” on page 58.4
8183F–AVR–06/12
ATtiny24A/44A/84A
2. Overview
ATtiny24A/44A/84A are low-power CMOS 8-bit microcontrollers based on the AVR enhanced
RISC architecture. By executing powerful instructions in a single clock cycle, the
ATtiny24A/44A/84A achieves throughputs approaching 1 MIPS per MHz allowing the system
designer to optimize power consumption versus processing speed.
Figure 2-1. Block Diagram
The AVR core combines a rich instruction set with 32 general purpose working registers. All 32
registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times faster than conventional
CISC microcontrollers.
WATCHDOG
TIMER
MCU CONTROL
REGISTER
TIMER/
COUNTER0
DATA DIR.
REG.PORT A
DATA REGISTER
PORT A
PROGRAMMING
LOGIC
TIMING AND
CONTROL
MCU STATUS
REGISTER
PORT A DRIVERS
PA[7:0]
VCC
GND
+
_
ANALOG
COMPARATOR
8-BIT DATABUS
ADC
ISP INTERFACE
INTERRUPT
UNIT
EEPROM
INTERNAL
OSCILLATOR
OSCILLATORS
CALIBRATED
OSCILLATOR
INTERNAL
DATA DIR.
REG.PORT B
DATA REGISTER
PORT B
PORT B DRIVERS
PB[3:0]
PROGRAM
COUNTER
STACK
POINTER
PROGRAM
FLASH SRAM
GENERAL
PURPOSE
REGISTERS
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
STATUS
REGISTER
Z
Y
X
ALU CONTROL
LINES
TIMER/
COUNTER15
8183F–AVR–06/12
ATtiny24A/44A/84A
The ATtiny24A/44A/84A provides the following features: 2K/4K/8K byte of In-System Programmable
Flash, 128/256/512 bytes EEPROM, 128/256/512 bytes SRAM, 12 general purpose I/O
lines, 32 general purpose working registers, an 8-bit Timer/Counter with two PWM channels, a
16-bit timer/counter with two PWM channels, Internal and External Interrupts, a 8-channel 10-bit
ADC, programmable gain stage (1x, 20x) for 12 differential ADC channel pairs, a programmable
Watchdog Timer with internal oscillator, internal calibrated oscillator, and four software selectable
power saving modes. Idle mode stops the CPU while allowing the SRAM, Timer/Counter,
ADC, Analog Comparator, and Interrupt system to continue functioning. ADC Noise Reduction
mode minimizes switching noise during ADC conversions by stopping the CPU and all I/O modules
except the ADC. In Power-down mode registers keep their contents and all chip functions
are disbaled until the next interrupt or hardware reset. In Standby mode, the crystal/resonator
oscillator is running while the rest of the device is sleeping, allowing very fast start-up combined
with low power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The onchip
ISP Flash allows the Program memory to be re-programmed in-system through an SPI
serial interface, by a conventional non-volatile memory programmer or by an on-chip boot code
running on the AVR core.
The ATtiny24A/44A/84A AVR is supported with a full suite of program and system development
tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators and Evaluation
kits.6
8183F–AVR–06/12
ATtiny24A/44A/84A
3. General Information
3.1 Resources
A comprehensive set of drivers, application notes, data sheets and descriptions on development
tools are available for download at http://www.atmel.com/avr.
3.2 Code Examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is included before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.
For I/O Registers located in the extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically, this
means “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”. Note that not all
AVR devices include an extended I/O map.
3.3 Capacitive Touch Sensing
Atmel QTouch Library provides a simple to use solution for touch sensitive interfaces on Atmel
AVR microcontrollers. The QTouch Library includes support for QTouch® and QMatrix® acquisition
methods.
Touch sensing is easily added to any application by linking the QTouch Library and using the
Application Programming Interface (API) of the library to define the touch channels and sensors.
The application then calls the API to retrieve channel information and determine the state of the
touch sensor.
The QTouch Library is free and can be downloaded from the Atmel website. For more information
and details of implementation, refer to the QTouch Library User Guide – also available from
the Atmel website.
3.4 Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.
3.5 Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of
other AVR microcontrollers manufactured on the same process technology. Min and Max values
will be available after the device has been characterized.7
8183F–AVR–06/12
ATtiny24A/44A/84A
4. CPU Core
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
4.1 Architectural Overview
Figure 4-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the Program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the Program memory. This concept enables instructions to be executed
in every clock cycle. The Program memory is In-System Reprogrammable Flash memory.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
Watchdog
Timer
Analog
Comparator
Timer/Counter 0
Timer/Counter 1
Universal
Serial Interface
ADC8
8183F–AVR–06/12
ATtiny24A/44A/84A
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash Program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, capable of
directly addressing the whole address space. Most AVR instructions have a single 16-bit word
format but 32-bit wide instructions also exist. The actual instruction set varies, as some devices
only implement a part of the instruction set.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
SPI, and other I/O functions. The I/O memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F.
4.2 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction Set” section for a detailed description.
4.3 Status Register
The Status Register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.9
8183F–AVR–06/12
ATtiny24A/44A/84A
The Status Register is neither automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt. This must be handled by software.
4.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 4-2 below shows the structure of the 32 general purpose working registers in the CPU.
Figure 4-2. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 4-2, each register is also assigned a Data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
4.4.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 4-3 below.
Figure 4-3. The X-, Y-, and Z-registers
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte
15 XH XL 010
8183F–AVR–06/12
ATtiny24A/44A/84A
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
4.5 Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x60. The Stack Pointer is decremented by one when data is pushed onto the Stack
with the PUSH instruction, and it is decremented by two when the return address is pushed onto
the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is
popped from the Stack with the POP instruction, and it is incremented by two when data is
popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations
of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
4.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the
chip. No internal clock division is used.
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
X-register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 7 0 7 0
R31 (0x1F) R30 (0x1E)11
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 4-4. The Parallel Instruction Fetches and Instruction Executions
Figure 4-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Figure 4-5. Single Cycle ALU Operation
4.7 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate Program Vector in the Program memory space. All interrupts are
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt.
The lowest addresses in the Program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 47. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt
Request 0.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s)
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU12
8183F–AVR–06/12
ATtiny24A/44A/84A
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt
Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
Note: See “Code Examples” on page 6.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1<
... ...
9.2 External Interrupts
External Interrupts are triggered by the INT0 pin or any of the PCINT[11:0] pins. Observe that, if
enabled, the interrupts will trigger even if the INT0 or PCINT[11:0] pins are configured as outputs.
This feature provides a way of generating a software interrupt. Pin change 0 interrupts
PCI0 will trigger if any enabled PCINT[7:0] pin toggles. Pin change 1 interrupts PCI1 will trigger
if any enabled PCINT[11:8] pin toggles. The PCMSK0 and PCMSK1 Registers control which
pins contribute to the pin change interrupts. Pin change interrupts on PCINT[11:0] are detected
asynchronously, which means that these interrupts can be used for waking the part also from
sleep modes other than Idle mode.
The INT0 interrupt can be triggered by a falling or rising edge or a low level. This is set up as
shown in “MCUCR – MCU Control Register” on page 50. When the INT0 interrupt is enabled
and configured as level triggered, the interrupt will trigger as long as the pin is held low. Note
that recognition of falling or rising edge interrupts on INT0 requires the presence of an I/O clock,
as described in “Clock Sources” on page 25.
9.2.1 Low Level Interrupt
A low level interrupt on INT0 is detected asynchronously. This means that the interrupt source
can be used for waking the part also from sleep modes other than Idle (the I/O clock is halted in
all sleep modes except Idle).49
8183F–AVR–06/12
ATtiny24A/44A/84A
Note that if a level triggered interrupt is used for wake-up from Power-down, the required level
must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If
the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt
will be generated. The start-up time is defined by the SUT and CKSEL fuses, as described
in “Clock System” on page 24.
If the low level on the interrupt pin is removed before the device has woken up then program
execution will not be diverted to the interrupt service routine but continue from the instruction following
the SLEEP command.
9.2.2 Pin Change Interrupt Timing
A timing example of a pin change interrupt is shown in Figure 9-1.
Figure 9-1. Timing of pin change interrupts
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
PCINT(0)
pin_sync
pcint_syn pin_lat D Q
LE
pcint_setflag
PCIF
clk
clk PCINT(0) in PCMSK(x)
pcint_in_(0) 0
x50
8183F–AVR–06/12
ATtiny24A/44A/84A
9.3 Register Description
9.3.1 MCUCR – MCU Control Register
The External Interrupt Control Register A contains control bits for interrupt sense control.
• Bits 1:0 – ISC0[1:0]: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding
interrupt mask are set. The level and edges on the external INT0 pin that activate the
interrupt are defined in Table 9-2. The value on the INT0 pin is sampled before detecting edges.
If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate
an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is
selected, the low level must be held until the completion of the currently executing instruction to
generate an interrupt.
9.3.2 GIMSK – General Interrupt Mask Register
• Bits 7, 3:0 – Res: Reserved Bits
These bits are reserved in the ATtiny24A/44A and will always read as zero.
• Bit 6 – INT0: External Interrupt Request 0 Enable
When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external
pin interrupt is enabled. The Interrupt Sense Control bits (ISC01 and ISC00) in the External
Interrupt Control Register A (EICRA) define whether the external interrupt is activated on rising
and/or falling edge of the INT0 pin or level sensed. Activity on the pin will cause an interrupt
request even if INT0 is configured as an output. The corresponding interrupt of External Interrupt
Request 0 is executed from the INT0 Interrupt Vector.
• Bit 5 – PCIE1: Pin Change Interrupt Enable 1
When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 1 is enabled. Any change on any enabled PCINT[11:8] pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1
Interrupt Vector. PCINT[11:8] pins are enabled individually by the PCMSK1 Register.
Bit 7 6 5 4 3 2 1 0
0x35 (0x55) BODS PUD SE SM1 SM0 BODSE ISC01 ISC00 MCUCR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 9-2. Interrupt 0 Sense Control
ISC01 ISC00 Description
0 0 The low level of INT0 generates an interrupt request.
0 1 Any logical change on INT0 generates an interrupt request.
1 0 The falling edge of INT0 generates an interrupt request.
1 1 The rising edge of INT0 generates an interrupt request.
Bit 7 6 5 4 3 2 1 0
0x3B (0x5B) – INT0 PCIE1 PCIE0 – – – – GIMSK
Read/Write R R/W R/W R/W1 R R R R
Initial Value 0 0 0 0 0 0 0 051
8183F–AVR–06/12
ATtiny24A/44A/84A
• Bit 4 – PCIE0: Pin Change Interrupt Enable 0
When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin
change interrupt 0 is enabled. Any change on any enabled PCINT[7:0] pin will cause an interrupt.
The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0
Interrupt Vector. PCINT[7:0] pins are enabled individually by the PCMSK0 Register.
9.3.3 GIFR – General Interrupt Flag Register
• Bits 7, 3:0 – Res: Reserved Bits
These bits are reserved in the ATtiny24A/44A and will always read as zero.
• Bit 6 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pin triggers an interrupt request, INTF0 becomes set
(one). If the I-bit in SREG and the INT0 bit in GIMSK are set (one), the MCU will jump to the corresponding
Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared
when INT0 is configured as a level interrupt.
• Bit 5 – PCIF1: Pin Change Interrupt Flag 1
When a logic change on any PCINT[11:8] pin triggers an interrupt request, PCIF1 becomes set
(one). If the I-bit in SREG and the PCIE1 bit in GIMSK are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively,
the flag can be cleared by writing a logical one to it.
• Bit 4 – PCIF0: Pin Change Interrupt Flag 0
When a logic change on any PCINT[7:0] pin triggers an interrupt request, PCIF becomes set
(one). If the I-bit in SREG and the PCIE0 bit in GIMSK are set (one), the MCU will jump to the
corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively,
the flag can be cleared by writing a logical one to it.
9.3.4 PCMSK1 – Pin Change Mask Register 1
• Bits 7:4 – Res: Reserved Bits
These bits are reserved in the ATtiny24A/44A and will always read as zero.
• Bits 3:0 – PCINT[11:8]: Pin Change Enable Mask 11:8
Each PCINT[11:8] bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT[11:8] is set and the PCIE1 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin. If PCINT[11:8] is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
Bit 7 6 5 4 3 2 1 0
0x3A (0x5A) – INTF0 PCIF1 PCIF0 – – – – GIFR
Read/Write R R/W R/W R/W R R R R
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x20 (0x40) – – – – PCINT11 PCINT10 PCINT9 PCINT8 PCMSK1
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 052
8183F–AVR–06/12
ATtiny24A/44A/84A
9.3.5 PCMSK0 – Pin Change Mask Register 0
• Bits 7:0 – PCINT[7:0]: Pin Change Enable Mask 7:0
Each PCINT[7:0] bit selects whether pin change interrupt is enabled on the corresponding I/O
pin. If PCINT[7:0] is set and the PCIE0 bit in GIMSK is set, pin change interrupt is enabled on
the corresponding I/O pin. If PCINT[7:0] is cleared, pin change interrupt on the corresponding
I/O pin is disabled.
Bit 7 6 5 4 3 2 1 0
0x12 (0x32) PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 PCMSK0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 053
8183F–AVR–06/12
ATtiny24A/44A/84A
10. I/O Ports
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports.
This means that the direction of one port pin can be changed without unintentionally changing
the direction of any other pin with the SBI and CBI instructions. The same applies when changing
drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as
input). Each output buffer has symmetrical drive characteristics with both high sink and source
capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually
selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have
protection diodes to both VCC and Ground as indicated in Figure 10-1 on page 53. See “Electrical
Characteristics” on page 173 for a complete list of parameters.
Figure 10-1. I/O Pin Equivalent Schematic
All registers and bit references in this section are written in general form. A lower case “x” represents
the numbering letter for the port, and a lower case “n” represents the bit number. However,
when using the register or bit defines in a program, the precise form must be used. For example,
PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers
and bit locations are listed in “Register Description” on page 66.
Three I/O memory address locations are allocated for each port, one each for the Data Register
– PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins
I/O location is read only, while the Data Register and the Data Direction Register are read/write.
However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding
bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR disables the
pull-up function for all pins in all ports when set.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page
54. Most port pins are multiplexed with alternate functions for the peripheral features on the
device. How each alternate function interferes with the port pin is described in “Alternate Port
Functions” on page 58. Refer to the individual module sections for a full description of the alternate
functions.
Note that enabling the alternate function of some of the port pins does not affect the use of the
other pins in the port as general digital I/O.
Cpin
Logic
Rpu
See Figure
"General Digital I/O" for
Details
Pxn54
8183F–AVR–06/12
ATtiny24A/44A/84A
10.1 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional
description of one I/O-port pin, here generically called Pxn.
Figure 10-2. General Digital I/O(1)
Note: 1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O,
SLEEP, and PUD are common to all ports.
10.1.1 Configuring the Pin
Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in “Register
Description” on page 66, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits
at the PORTx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one,
Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input
pin.
If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is
activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin has to
be configured as an output pin. The port pins are tri-stated when reset condition becomes active,
even if no clocks are running.
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven
high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port
pin is driven low (zero).
clk
RPx
RRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
clkI/O: I/O CLOCK
RDx: READ DDRx
D
L
Q
Q
RESET
RESET
Q
D Q
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BU
S
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
WPx
0
1
WRx
WPx: WRITE PINx REGISTER55
8183F–AVR–06/12
ATtiny24A/44A/84A
10.1.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
Note that the SBI instruction can be used to toggle one single bit in a port.
10.1.3 Switching Between Input and Output
When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn}
= 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output
low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable,
as a high-impedant environment will not notice the difference between a strong high driver
and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all
pull-ups in all ports.
Switching between input with pull-up and output low generates the same problem. The user
must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn}
= 0b10) as an intermediate step.
Table 10-1 summarizes the control signals for the pin value.
10.1.4 Reading the Pin Value
Independent of the setting of Data Direction bit DDxn, the port pin can be read through the
PINxn Register bit. As shown in Figure 10-2 on page 54, the PINxn Register bit and the preceding
latch constitute a synchronizer. This is needed to avoid metastability if the physical pin
changes value near the edge of the internal clock, but it also introduces a delay. Figure 10-3
shows a timing diagram of the synchronization when reading an externally applied pin value.
The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
Figure 10-3. Synchronization when Reading an Externally Applied Pin value
Table 10-1. Port Pin Configurations
DDxn PORTxn
PUD
(in MCUCR) I/O Pull-up Comment
0 0 X Input No Tri-state (Hi-Z)
0 1 0 Input Yes Pxn will source current if ext. pulled low
0 1 1 Input No Tri-state (Hi-Z)
1 0 X Output No Output Low (Sink)
1 1 X Output No Output High (Source)
XXX in r17, PINx
0x00 0xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
tpd, max
tpd, min56
8183F–AVR–06/12
ATtiny24A/44A/84A
Consider the clock period starting shortly after the first falling edge of the system clock. The latch
is closed when the clock is low, and goes transparent when the clock is high, as indicated by the
shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock
goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated
by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed
between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated
in Figure 10-4 on page 56. The out instruction sets the “SYNC LATCH” signal at the
positive edge of the clock. In this case, the delay tpd through the synchronizer is one system
clock period.
Figure 10-4. Synchronization when Reading a Software Assigned Pin Value
10.1.5 Digital Input Enable and Sleep Modes
As shown in Figure 10-2 on page 54, the digital input signal can be clamped to ground at the
input of the schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep
Controller in Power-down and Standby modes to avoid high power consumption if some input
signals are left floating, or have an analog signal level close to VCC/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt
request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various
other alternate functions as described in “Alternate Port Functions” on page 58.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as
“Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt
is not enabled, the corresponding External Interrupt Flag will be set when resuming from the
above mentioned Sleep mode, as the clamping in these sleep mode produces the requested
logic change.
10.1.6 Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even
though most of the digital inputs are disabled in the deep sleep modes as described above, floating
inputs should be avoided to reduce current consumption in all other modes where the digital
inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up.
In this case, the pull-up will be disabled during reset. If low power consumption during reset is
out PORTx, r16 nop in r17, PINx
0xFF
0x00 0xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t pd57
8183F–AVR–06/12
ATtiny24A/44A/84A
important, it is recommended to use an external pull-up or pulldown. Connecting unused pins
directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is
accidentally configured as an output.
10.1.7 Program Examples
The following code example shows how to set port A pins 0 and 1 high, 2 and 3 low, and define
the port pins from 4 to 5 as input with a pull-up assigned to port pin 4. The resulting pin values
are read back again, but as previously discussed, a nop instruction is included to be able to read
back the value recently assigned to some of the pins.
Note: Two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1 and 4,
until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as
strong high drivers.
Note: See “Code Examples” on page 6.
Assembly Code Example
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1<
MSB
MSB
6 5 4 3 2 1 LSB
1 2 3 4 5 6 7 8
6 5 4 3 2 1 LSB
USCK
USCK
DO
DI
A B C D E
CYCLE ( Reference )119
8183F–AVR–06/12
ATtiny24A/44A/84A
SPITransfer_loop:
out USICR,r17
in r16, USISR
sbrs r16, USIOIF
rjmp SPITransfer_loop
in r16,USIDR
ret
The code is size optimized using only eight instructions (plus return). The code example
assumes that the DO and USCK pins have been enabled as outputs in DDRA. The value stored
in register r16 prior to the function is called is transferred to the slave device, and when the
transfer is completed the data received from the slave is stored back into the register r16.
The second and third instructions clear the USI Counter Overflow Flag and the USI counter
value. The fourth and fifth instructions set three-wire mode, positive edge clock, count at USITC
strobe, and toggle USCK. The loop is repeated 16 times.
The following code demonstrates how to use the USI as an SPI master with maximum speed
(fSCK = fCK/2):
SPITransfer_Fast:
out USIDR,r16
ldi r16,(1< 2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
• High:> 2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
19.5.1 Serial Programming Algorithm
When writing serial data to the ATtiny24A/44A/84A, data is clocked on the rising edge of SCK.
When reading, data is clocked on the falling edge of SCK. See Figure 20-3 and Figure 20-4 for
timing details.
To program and verify the ATtiny24A/44A/84A in the Serial Programming mode, the following
sequence is recommended (see four byte instruction formats in Table 19-12):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
the programmer can not guarantee that SCK is held low during power-up. In this
case, RESET must be given a positive pulse after SCK has been set to '0'. The duration
of the pulse must be at least tRST (the minimum pulse width on RESET pin, see Table
20-4 on page 176) plus two CPU clock cycles.
2. Wait for at least 20 ms and enable serial programming by sending the Programming
Enable serial instruction to pin MOSI.
3. The serial programming instructions will not work if the communication is out of synchronization.
When in sync. the second byte (0x53), will echo back when issuing the
third byte of the Programming Enable instruction. Whether the echo is correct or not, all
four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give
RESET a positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The memory page is loaded one byte at
a time by supplying the 5 LSB of the address and data together with the Load Program
memory Page instruction. To ensure correct loading of the page, the data low byte must
be loaded before data high byte is applied for a given address. The Program memory
Page is stored by loading the Write Program memory Page instruction with the 3 MSB
of the address. If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH
before issuing the next page. (See Table 19-11 on page 164.) Accessing the serial programming
interface before the Flash write operation completes can result in incorrect
programming.
5. A: The EEPROM array is programmed one byte at a time by supplying the address and
data together with the appropriate Write instruction. An EEPROM memory location is
first automatically erased before new data is written. If polling (RDY/BSY) is not used,
the user must wait at least tWD_EEPROM before issuing the next byte. (See Table 19-11
on page 164.) In a chip erased device, no 0xFFs in the data file(s) need to be programmed.
B: The EEPROM array is programmed one page at a time. The Memory page is loaded
one byte at a time by supplying the 2 LSB of the address and data together with the
Load EEPROM Memory Page instruction. The EEPROM Memory Page is stored by
loading the Write EEPROM Memory Page Instruction with the 4 MSB of the address.
When using EEPROM page access only byte locations loaded with the Load EEPROM
Memory Page instruction is altered. The remaining locations remain unchanged. If polling
(RDY/BSY) is not used, the used must wait at least tWD_EEPROM before issuing the
next page (See Table 19-11 on page 164). In a chip erased device, no 0xFF in the data
file(s) need to be programmed.
6. Any memory location can be verified by using the Read instruction which returns the
content at the selected address at serial output MISO.164
8183F–AVR–06/12
ATtiny24A/44A/84A
7. At the end of the programming session, RESET can be set high to commence normal
operation.
8. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off.
19.5.2 Serial Programming Instruction set
The instruction set is described in Table 19-12 and Figure 19-2 on page 165.
Table 19-11. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FLASH 4.5 ms
tWD_EEPROM 4.0 ms
tWD_ERASE 9.0 ms
tWD_FUSE 4.5 ms
Table 19-12. Serial Programming Instruction Set
Instruction/Operation(1)
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4
Programming Enable $AC $53 $00 $00
Chip Erase (Program Memory/EEPROM) $AC $80 $00 $00
Poll RDY/BSY $F0 $00 $00 data byte out
Load Instructions
Load Extended Address byte $4D $00 Extended adr $00
Load Program Memory Page, High byte $48 adr MSB adr LSB high data byte in
Load Program Memory Page, Low byte $40 adr MSB adr LSB low data byte in
Load EEPROM Memory Page (page access) $C1 $00 adr LSB data byte in
Read Instructions
Read Program Memory, High byte $28 adr MSB adr LSB high data byte out
Read Program Memory, Low byte $20 adr MSB adr LSB low data byte out
Read EEPROM Memory $A0 $00 adr LSB data byte out
Read Lock bits $58 $00 $00 data byte out
Read Signature Byte $30 $00 adr LSB data byte out
Read Fuse bits $50 $00 $00 data byte out
Read Fuse High bits $58 $08 $00 data byte out
Read Extended Fuse Bits $50 $08 $00 data byte out
Read Calibration Byte $38 $00 $00 data byte out
Write Instructions(6)
Write Program Memory Page $4C adr MSB adr LSB $00
Write EEPROM Memory $C0 $00 adr LSB data byte in
Write EEPROM Memory Page (page access) $C2 $00 adr LSB $00165
8183F–AVR–06/12
ATtiny24A/44A/84A
Notes: 1. Not all instructions are applicable for all parts.
2. a = address
3. Bits are programmed ‘0’, unprogrammed ‘1’.
4. To ensure future compatibility, unused Fuses and Lock bits should be unprogrammed (‘1’) .
5. Refer to the correspondig section for Fuse and Lock bits, Calibration and Signature bytes and Page size.
6. Instructions accessing program memory use a word address. This address may be random within the page range.
7. See http://www.atmel.com/avr for Application Notes regarding programming and programmers.
Figure 19-2. Serial Programming Instruction example
If the LSB in RDY/BSY data byte out is ‘1’, a programming operation is still pending. Wait until
this bit returns ‘0’ before the next instruction is carried out.
Within the same page, the low data byte must be loaded prior to the high data byte.
Write Lock bits $AC $E0 $00 data byte in
Write Fuse bits $AC $A0 $00 data byte in
Write Fuse High bits $AC $A8 $00 data byte in
Write Extended Fuse Bits $AC $A4 $00 data byte in
Table 19-12. Serial Programming Instruction Set (Continued)
Instruction/Operation(1)
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4
Byte 1 Byte 2 Byte 3 Byte 4
Adr MSB Adr LSB
Bit 15 B 0
Serial Programming Instruction
Program Memory/
EEPROM Memory
Page 0
Page 1
Page 2
Page N-1
Page Buffer
Write Program Memory Page/
Write EEPROM Memory Page
Load Program Memory Page (High/Low Byte)/
Load EEPROM Memory Page (page access)
Byte 1 Byte 2 Byte 3 Byte 4
Bit 15 B 0
Adr MSB Adr LSB
Page Offset
Page Number
Adr MSB Adr LSB166
8183F–AVR–06/12
ATtiny24A/44A/84A
After data is loaded to the page buffer, program the EEPROM page, see Figure 19-2 on page
165.
19.6 High-voltage Serial Programming
This section describes how to program and verify Flash Program memory, EEPROM Data memory,
Lock bits and Fuse bits in the ATtiny24A/44A/84A.
Figure 19-3. High-voltage Serial Programming
The minimum period for the Serial Clock Input (SCI) during High-voltage Serial Programming is
220 ns.
19.7 High-Voltage Serial Programming Algorithm
To program and verify the ATtiny24A/44A/84A in the High-voltage Serial Programming mode,
the following sequence is recommended (See instruction formats in Table 19-16 on page 170):
Table 19-13. Pin Name Mapping
Signal Name in High-voltage
Serial Programming Mode Pin Name I/O Function
SDI PA6 I Serial Data Input
SII PA5 I Serial Instruction Input
SDO PA4 O Serial Data Output
SCI PB0 I Serial Clock Input (min. 220ns period)
Table 19-14. Pin Values Used to Enter Programming Mode
Pin Symbol Value
PA0 Prog_enable[0] 0
PA1 Prog_enable[1] 0
PA2 Prog_enable[2] 0
VCC
GND
SDO
SII
SDI
(RESET)
+4.5 - 5.5V
PA6
PA5
PA4
PB3
+11.5 - 12.5V
SCI PB0
PA2:0167
8183F–AVR–06/12
ATtiny24A/44A/84A
19.7.1 Enter High-voltage Serial Programming Mode
The following algorithm puts the device in High-voltage Serial Programming mode:
1. Set Prog_enable pins listed in Table 19-14 on page 166 to “000”, RESET pin and VCC
to 0V.
2. Apply 4.5 - 5.5V between VCC and GND. Ensure that VCC reaches at least 1.8V within
the next 20 µs.
3. Wait 20 - 60 µs, and apply 11.5 - 12.5V to RESET.
4. Keep the Prog_enable pins unchanged for at least 10 µs after the High-voltage has
been applied to ensure the Prog_enable Signature has been latched.
5. Release the Prog_enable[2] pin after tHVRST has elapsed.
6. Wait at least 300 µs before giving any serial instructions on SDI/SII.
7. Exit Programming mode by power the device down or by bringing RESET pin to 0V.
If the rise time of the VCC is unable to fulfill the requirements listed above, the following alternative
algorithm can be used:
1. Set Prog_enable pins listed in Table 19-14 on page 166 to “000”, RESET pin and VCC
to 0V.
2. Apply 4.5 - 5.5V between VCC and GND.
3. Monitor VCC, and as soon as VCC reaches 0.9 - 1.1V, apply 11.5 - 12.5V to RESET.
4. Keep the Prog_enable pins unchanged for at least 10 µs after the High-voltage has
been applied to ensure the Prog_enable Signature has been latched.
5. Release the Prog_enable[2] pin to avoid drive contention on the Prog_enable[2]/SDO
pin.
6. Wait until VCC actually reaches 4.5 - 5.5V before giving any serial instructions on
SDI/SII.
7. Exit Programming mode by power the device down or by bringing RESET pin to 0V.
Table 19-15. High-voltage Reset Characteristics
Supply Voltage RESET Pin High-voltage Threshold
Minimum High-voltage Period for
Latching Prog_enable
VCC VHVRST tHVRST
4.5V 11.5V 100 ns
5.5V 11.5V 100 ns168
8183F–AVR–06/12
ATtiny24A/44A/84A
19.7.2 Considerations for Efficient Programming
The loaded command and address are retained in the device during programming. For efficient
programming, the following should be considered.
• The command needs only be loaded once when writing or reading multiple memory
locations.
• Skip writing the data value 0xFF that is the contents of the entire EEPROM (unless the
EESAVE Fuse is programmed) and Flash after a Chip Erase.
• Address High byte needs only be loaded before programming or reading a new 256 word
window in Flash or 256 byte EEPROM. This consideration also applies to Signature bytes
reading.
19.7.3 Chip Erase
The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are
not reset until the Program memory has been completely erased. The Fuse bits are not
changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.
1. Load command “Chip Erase” (see Table 19-16 on page 170).
2. Wait after Instr. 3 until SDO goes high for the “Chip Erase” cycle to finish.
3. Load Command “No Operation”.
Note: 1. The EEPROM memory is preserved during Chip Erase if the EESAVE Fuse is programmed.
19.7.4 Programming the Flash
The Flash is organized in pages, see “Page Size” on page 161. When programming the Flash,
the program data is latched into a page buffer. This allows one page of program data to be programmed
simultaneously. The following procedure describes how to program the entire Flash
memory:
1. Load Command “Write Flash” (see Table 19-16 on page 170).
2. Load Flash Page Buffer.
3. Load Flash High Address and Program Page. Wait after Instr. 3 until SDO goes high
for the “Page Programming” cycle to finish.
4. Repeat 2 through 3 until the entire Flash is programmed or until all data has been
programmed.
5. End Page Programming by Loading Command “No Operation”.
When writing or reading serial data to the ATtiny24A/44A/84A, data is clocked on the rising edge
of the serial clock, see Figure 20-5 on page 181, Figure 19-3 on page 166 and Table 20-12 on
page 181 for details.169
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 19-4. Addressing the Flash which is Organized in Pages
Figure 19-5. High-voltage Serial Programming Waveforms
19.7.5 Programming the EEPROM
The EEPROM is organized in pages, see Table 20-11 on page 180. When programming the
EEPROM, the data is latched into a page buffer. This allows one page of data to be programmed
simultaneously. The programming algorithm for the EEPROM Data memory is as
follows (refer to Table 19-16 on page 170):
1. Load Command “Write EEPROM”.
2. Load EEPROM Page Buffer.
3. Program EEPROM Page. Wait after Instr. 2 until SDO goes high for the “Page Programming”
cycle to finish.
4. Repeat 2 through 3 until the entire EEPROM is programmed or until all data has been
programmed.
5. End Page Programming by Loading Command “No Operation”.
PROGRAM MEMORY
WORD ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE FLASH
INSTRUCTION WORD
PAGE PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
PAGE
PCPAGE PCWORD
PCMSB PAGEMSB
PROGRAM
COUNTER
MSB
MSB
MSB LSB
LSB
LSB
0 1 2 3 4 5 6 7 8 9 10
SDI
PA6
SII
PA5
SDO
PA4
SCI
PB0170
8183F–AVR–06/12
ATtiny24A/44A/84A
19.7.6 Reading the Flash
The algorithm for reading the Flash memory is as follows (refer to Table 19-16 on page 170):
1. Load Command "Read Flash".
2. Read Flash Low and High Bytes. The contents at the selected address are available at
serial output SDO.
19.7.7 Reading the EEPROM
The algorithm for reading the EEPROM memory is as follows (refer to Table 19-16 on page
170):
1. Load Command “Read EEPROM”.
2. Read EEPROM Byte. The contents at the selected address are available at serial output
SDO.
19.7.8 Programming and Reading the Fuse and Lock Bits
The algorithms for programming and reading the Fuse Low/High bits and Lock bits are shown in
Table 19-16 on page 170.
19.7.9 Reading the Signature Bytes and Calibration Byte
The algorithms for reading the Signature bytes and Calibration byte are shown in Table 19-16 on
page 170.
19.7.10 Power-off sequence
Set SCI to “0”. Set RESET to “1”. Turn VCC power off.
Table 19-16. High-voltage Serial Programming Instruction Set for ATtiny24A/44A/84A
Instruction
Instruction Format
Instr.1/5 Instr.2/6 Instr.3/7 Instr.4 Operation Remarks
Chip Erase
SDI
SII
SDO
0_1000_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Wait after Instr.3 until SDO
goes high for the Chip Erase
cycle to finish.
Load “Write
Flash”
Command
SDI
SII
SDO
0_0001_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
Enter Flash Programming code.
Load Flash
Page Buffer
SDI
SII
SDO
0_ bbbb_bbbb _00
0_0000_1100_00
x_xxxx_xxxx_xx
0_eeee_eeee_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1101_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Repeat after Instr. 1 - 7until the
entire page buffer is filled or
until all data within the page is
filled.(2)
SDI
SII
SDO
0_dddd_dddd_00
0_0011_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1101_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1100_00
x_xxxx_xxxx_xx
Instr 5-7.
Load Flash
High Address
and Program
Page
SDI
SII
SDO
0_0000_000a_00
0_0001_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Wait after Instr 3 until SDO
goes high. Repeat Instr. 2 - 3
for each loaded Flash Page
until the entire Flash or all data
is programmed. Repeat Instr. 1
for a new 256 byte page.(2)171
8183F–AVR–06/12
ATtiny24A/44A/84A
Load “Read
Flash”
Command
SDI
SII
SDO
0_0000_0010_00
0_0100_1100_00
x_xxxx_xxxx_xx
Enter Flash Read mode.
Read Flash
Low and High
Bytes
SDI
SII
SDO
0_bbbb_bbbb_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_0000_000a_00
0_0001_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
q_qqqq_qqqx_xx
Repeat Instr. 1, 3 - 6 for each
new address. Repeat Instr. 2 for
a new 256 byte page.
SDI
SII
SDO
0_0000_0000_00
0_0111_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1100_00
p_pppp_pppx_xx
Instr 5 - 6.
Load “Write
EEPROM”
Command
SDI
SII
SDO
0_0001_0001_00
0_0100_1100_00
x_xxxx_xxxx_xx
Enter EEPROM Programming
mode.
Load
EEPROM
Page Buffer
SDI
SII
SDO
0_bbbb_bbbb_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_aaaa_aaaa_00
0_0001_1100_00
x_xxxx_xxxx_xx
0_eeee_eeee_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1101_00
x_xxxx_xxxx_xx
Repeat Instr. 1 - 5 until the
entire page buffer is filled or
until all data within the page is
filled.(3)
SDI
SII
SDO
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Program
EEPROM
Page
SDI
SII
SDO
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Wait after Instr. 2 until SDO
goes high. Repeat Instr. 1 - 2
for each loaded EEPROM page
until the entire EEPROM or all
data is programmed.
Write
EEPROM
Byte
SDI
SII
SDO
0_bbbb_bbbb_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_aaaa_aaaa_00
0_0001_1100_00
x_xxxx_xxxx_xx
0_eeee_eeee_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1101_00
x_xxxx_xxxx_xx
Repeat Instr. 1 - 6 for each new
address. Wait after Instr. 6 until
SDO goes high.(4)
SDI
SII
SDO
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Instr. 5-6
Load “Read
EEPROM”
Command
SDI
SII
SDO
0_0000_0011_00
0_0100_1100_00
x_xxxx_xxxx_xx
Enter EEPROM Read mode.
Read
EEPROM
Byte
SDI
SII
SDO
0_bbbb_bbbb_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_aaaa_aaaa_00
0_0001_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
q_qqqq_qqq0_00
Repeat Instr. 1, 3 - 4 for each
new address. Repeat Instr. 2 for
a new 256 byte page.
Write Fuse
Low Bits
SDI
SII
SDO
0_0100_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_A987_6543_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Wait after Instr. 4 until SDO
goes high. Write A - 3 = “0” to
program the Fuse bit.
Write Fuse
High Bits
SDI
SII
SDO
0_0100_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_IHGF_EDCB_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1100_00
x_xxxx_xxxx_xx
Wait after Instr. 4 until SDO
goes high. Write F - B = “0” to
program the Fuse bit.
Write Fuse
Extended Bits
SDI
SII
SDO
0_0100_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_000J_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_0110_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1110_00
x_xxxx_xxxx_xx
Wait after Instr. 4 until SDO
goes high. Write J = “0” to
program the Fuse bit.
Table 19-16. High-voltage Serial Programming Instruction Set for ATtiny24A/44A/84A (Continued)
Instruction
Instruction Format
Instr.1/5 Instr.2/6 Instr.3/7 Instr.4 Operation Remarks172
8183F–AVR–06/12
ATtiny24A/44A/84A
Notes: 1. a = address high bits, b = address low bits, d = data in high bits, e = data in low bits, p = data out high bits, q = data out low
bits, x = don’t care, 1 = Lock Bit1, 2 = Lock Bit2, 3 = CKSEL0 Fuse, 4 = CKSEL1 Fuse, 5 = CKSEL2 Fuse, 6 = CKSEL3
Fuse, 7 = SUT0 Fuse, 8 = SUT1 Fuse, 9 = CKOUT Fuse, A = CKDIV8 Fuse, B = BODLEVEL0 Fuse, C = BODLEVEL1
Fuse, D= BODLEVEL2 Fuse, E = EESAVE Fuse, F = WDTON Fuse, G = SPIEN Fuse, H = DWEN Fuse, I = RSTDISBL
Fuse, J = SELFPRGEN Fuse
2. For page sizes less than 256 words, parts of the address (bbbb_bbbb) will be parts of the page address.
3. For page sizes less than 256 bytes, parts of the address (bbbb_bbbb) will be parts of the page address.
4. The EEPROM is written page-wise. But only the bytes that are loaded into the page are actually written to the EEPROM.
Page-wise EEPROM access is more efficient when multiple bytes are to be written to the same page. Note that auto-erase
of EEPROM is not available in High-voltage Serial Programming, only in SPI Programming.
Write Lock
Bits
SDI
SII
SDO
0_0010_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0021_00
0_0010_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_0100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_xxxx_xx
Wait after Instr. 4 until SDO
goes high. Write 2 - 1 = “0” to
program the Lock Bit.
Read Fuse
Low Bits
SDI
SII
SDO
0_0000_0100_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
A_9876_543x_xx
Reading A - 3 = “0” means the
Fuse bit is programmed.
Read Fuse
High Bits
SDI
SII
SDO
0_0000_0100_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1010_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1100_00
I_HGFE_DCBx_xx
Reading F - B = “0” means the
Fuse bit is programmed.
Read Fuse
Extended Bits
SDI
SII
SDO
0_0000_0100_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1010_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1110_00
x_xxxx_xxJx_xx
Reading J = “0” means the
Fuse bit is programmed.
Read Lock
Bits
SDI
SII
SDO
0_0000_0100_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
x_xxxx_x21x_xx
Reading 2, 1 = “0” means the
Lock bit is programmed.
Read
Signature
Bytes
SDI
SII
SDO
0_0000_1000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_00bb_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0110_1100_00
q_qqqq_qqqx_xx
Repeats Instr 2 4 for each
signature byte address.
Read
Calibration
Byte
SDI
SII
SDO
0_0000_1000_00
0_0100_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0000_1100_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1000_00
x_xxxx_xxxx_xx
0_0000_0000_00
0_0111_1100_00
p_pppp_pppx_xx
Load “No
Operation”
Command
SDI
SII
SDO
0_0000_0000_00
0_0100_1100_00
x_xxxx_xxxx_xx
Table 19-16. High-voltage Serial Programming Instruction Set for ATtiny24A/44A/84A (Continued)
Instruction
Instruction Format
Instr.1/5 Instr.2/6 Instr.3/7 Instr.4 Operation Remarks173
8183F–AVR–06/12
ATtiny24A/44A/84A
20. Electrical Characteristics
20.1 Absolute Maximum Ratings*
20.2 DC Characteristics
Operating Temperature.................................. -55°C to +125°C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ............................................... 40.0 mA
DC Current VCC and GND Pins ................................ 200.0 mA
Table 20-1. DC Characteristics. TA = -40°C to +85°C
Symbol Parameter Condition Min Typ(1) Max Units
VIL
Input Low Voltage
VCC = 1.8V - 2.4V -0.5 0.2VCC(3) V
VCC = 2.4V - 5.5V -0.5 0.3VCC(3) V
Input Low Voltage,
RESET Pin as Reset (4) VCC = 1.8V - 5.5 -0.5 0.2VCC(3)
VIH
Input High-voltage
Except RESET pin
VCC = 1.8V - 2.4V 0.7VCC(2) VCC +0.5 V
VCC = 2.4V - 5.5V 0.6VCC(2) VCC +0.5 V
Input High-voltage
RESET pin as Reset (4) VCC = 1.8V to 5.5V 0.9VCC(2) VCC +0.5 V
VOL
Output Low Voltage (5)
Except RESET pin (7)
IOL = 10 mA, VCC = 5V 0.6 V
IOL = 5 mA, VCC = 3V 0.5 V
VOH
Output High-voltage (6)
Except RESET pin (7)
IOH = -10 mA, VCC = 5V 4.3 V
IOH = -5 mA, VCC = 3V 2.5 V
ILIL
Input Leakage
Current I/O Pin
VCC = 5.5V, pin low
(absolute value) < 0.05 1(8) µA
ILIH
Input Leakage
Current I/O Pin
VCC = 5.5V, pin high
(absolute value) < 0.05 1(8) µA
RPU
Pull-up Resistor, I/O Pin VCC = 5.5V, input low 20 50 kΩ
Pull-up Resistor, Reset Pin VCC = 5.5V, input low 30 60 kΩ174
8183F–AVR–06/12
ATtiny24A/44A/84A
Notes: 1. Typical values at 25°C.
2. “Min” means the lowest value where the pin is guaranteed to be read as high.
3. “Max” means the highest value where the pin is guaranteed to be read as low.
4. Not tested in production.
5. Although each I/O port can sink more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state
conditions (non-transient), the sum of all IOL (for all ports) should not exceed 60 mA. If IOL exceeds the test conditions, VOL
may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.
6. Although each I/O port can source more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state
conditions (non-transient), the sum of all IOH (for all ports) should not exceed 60 mA. If IOH exceeds the test condition, VOH
may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition.
7. The RESET pin must tolerate high voltages when entering and operating in programming modes and, as a consequence,
has a weak drive strength as compared to regular I/O pins. See Figure 21-87, Figure 21-88, Figure 21-89, and Figure 21-90
(starting on page 226).
8. These are test limits, which account for leakage currents of the test environment. Actual device leakage currents are lower.
9. Values are with external clock using methods described in “Minimizing Power Consumption” on page 35. Power Reduction
is enabled (PRR = 0xFF) and there is no I/O drive.
10. BOD Disabled.
20.3 Speed
The maximum operating frequency of the device depends on VCC. As shown in Figure 20-1, the
relationship between maximum frequency and VCC is linear in the region 1.8V < VCC < 4.5V.
Figure 20-1. Maximum Frequency vs. VCC
ICC
Supply Current,
Active Mode (9)
f = 1 MHz, VCC = 2V 0.25 0.5 mA
f = 4 MHz, VCC = 3V 1.2 2 mA
f = 8 MHz, VCC = 5V 4.4 7 mA
Supply Current,
Idle Mode (9)
f = 1 MHz, VCC = 2V 0.04 0.2 mA
f = 4 MHz, VCC = 3V 0.25 0.6 mA
f = 8 MHz, VCC = 5V 1.3 2 mA
Supply Current,
Power-Down Mode (10)
WDT enabled, VCC = 3V 4 10 µA
WDT disabled, VCC = 3V 0.13 2 µA
Table 20-1. DC Characteristics. TA = -40°C to +85°C (Continued)
Symbol Parameter Condition Min Typ(1) Max Units
4 MHz
1.8V 5.5V 4.5V
20 MHz175
8183F–AVR–06/12
ATtiny24A/44A/84A
20.4 Clock Characteristics
20.4.1 Accuracy of Calibrated Internal Oscillator
It is possible to manually calibrate the internal oscillator to be more accurate than default factory
calibration. Note that the oscillator frequency depends on temperature and voltage. Voltage and
temperature characteristics can be found in Figure 21-109 on page 237 and Figure 21-110 on
page 238.
Notes: 1. Accuracy of oscillator frequency at calibration point (fixed temperature and fixed voltage).
20.4.2 External Clock Drive
Figure 20-2. External Clock Drive Waveform
Table 20-2. Calibration Accuracy of Internal RC Oscillator
Calibration
Method Target Frequency VCC Temperature
Accuracy at given voltage
& temperature (1)
Factory
Calibration 8.0 MHz 3V 25°C ±10%
User
Calibration
Fixed frequency within:
7.3 – 8.1 MHz
Fixed voltage within:
1.8V – 5.5V
Fixed temperature
within:
-40°C to +85°C
±1%
VIL1
VIH1
Table 20-3. External Clock Drive Characteristics
Symbol Parameter
VCC = 1.8 - 5.5V VCC = 2.7 - 5.5V VCC = 4.5 - 5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL Clock Frequency 0 4 0 10 0 20 MHz
tCLCL Clock Period 250 100 50 ns
tCHCX High Time 100 40 20 ns
tCLCX Low Time 100 40 20 ns
tCLCH Rise Time 2.0 1.6 0.5 µs
tCHCL Fall Time 2.0 1.6 0.5 µs
ΔtCLCL Change in period from one clock cycle to the next 2 2 2 %176
8183F–AVR–06/12
ATtiny24A/44A/84A
20.5 System and Reset Characteristics
Note: 1. Values are guidelines, only
20.5.1 Power-On Reset
Note: 1. Values are guidelines, only
2. Threshold where device is released from reset when voltage is rising
3. The Power-on Reset will not work unless the supply voltage has been below VPOA
20.5.2 Brown-Out Detection
Note: 1. VBOT may be below nominal minimum operating voltage for some devices. For devices where
this is the case, the device is tested down to VCC = VBOT during the production test. This guarantees
that a Brown-out Reset will occur before VCC drops to a voltage where correct
operation of the microcontroller is no longer guaranteed.
Table 20-4. Reset, Brown-out, and Internal Voltage Characteristics
Symbol Parameter Condition Min(1) Typ(1) Max(1) Units
VRST RESET pin threshold voltage 0.2 VCC 0.9VCC V
tRST
Minimum pulse width on
RESET pin
VCC = 1.8V
VCC = 3V
VCC = 5V
2000
700
400
ns
VHYST Brown-out Detector hysteresis 50 mV
tBOD
Minimum pulse width on
Brown-out Reset 2 µs
VBG
Internal bandgap reference
voltage
VCC = 5V
TA = 25°C 1.0 1.1 1.2 V
tBG
Internal bandgap reference
start-up time
VCC = 5V
TA = 25°C 40 70 µs
IBG
Internal bandgap reference
current consumption
VCC = 5V
TA = 25°C 15 µA
Table 20-5. Characteristics of Enhanced Power-On Reset. TA = = -40°C to +85°C
Symbol Parameter Min(1) Typ(1) Max(1) Units
VPOR Release threshold of power-on reset (2) 1.1 1.4 1.6 V
VPOA Activation threshold of power-on reset (3) 0.6 1.3 1.6 V
SRON Power-On Slope Rate 0.01 V/ms
Table 20-6. VBOT vs. BODLEVEL Fuse Coding
BODLEVEL[2:0] Fuses Min(1) Typ(1) Max(1) Units
111 BOD Disabled
110 1.7 1.8 2.0
101 2.5 2.7 2.9 V
100 4.1 4.3 4.5
0XX Reserved177
8183F–AVR–06/12
ATtiny24A/44A/84A
20.6 ADC Characteristics
Table 20-7. ADC Characteristics, Single Ended Channels. T = -40°C to +85°C
Symbol Parameter Condition Min Typ Max Units
Resolution 10 Bits
Absolute accuracy
(Including INL, DNL, and
Quantization, Gain and Offset
Errors)
VREF = 4V, VCC = 4V,
ADC clock = 200 kHz 2.0 LSB
VREF = 4V, VCC = 4V,
ADC clock = 1 MHz 2.5 LSB
VREF = 4V, VCC = 4V,
ADC clock = 200 kHz
Noise Reduction Mode
1.5 LSB
VREF = 4V, VCC = 4V,
ADC clock = 1 MHz
Noise Reduction Mode
2.0 LSB
Integral Non-Linearity (INL)
(Accuracy after Offset and
Gain Calibration)
VREF = 4V, VCC = 4V,
ADC clock = 200 kHz 1.0 LSB
Differential Non-linearity
(DNL)
VREF = 4V, VCC = 4V,
ADC clock = 200 kHz 0.5 LSB
Gain Error VREF = 4V, VCC = 4V,
ADC clock = 200 kHz 2.0 LSB
Offset Error (Absolute) VREF = 4V, VCC = 4V,
ADC clock = 200 kHz 1.5 LSB
Conversion Time Free Running Conversion 14 280 µs
Clock Frequency 50 1000 kHz
VIN Input Voltage GND VREF V
Input Bandwidth 38.5 kHz
AREF External Voltage Reference 2.0 VCC V
VINT Internal Voltage Reference 1.0 1.1 1.2 V
RREF Reference Input Resistance 32 kΩ
RAIN Analog Input Resistance 100 MΩ
ADC Conversion Output 0 1023 LSB178
8183F–AVR–06/12
ATtiny24A/44A/84A
Table 20-8. ADC Characteristics, Differential Channels (Unipolar Mode), TA = -40°C to +85°C
Symbol Parameter Condition Min Typ Max Units
Resolution
Gain = 1x 10 Bits
Gain = 20x 10 Bits
Absolute accuracy
(Including INL, DNL, and Quantization, Gain
and Offset Errors)
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
10 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
15 LSB
Integral Non-Linearity (INL)
(Accuracy after Offset and Gain Calibration)
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
4 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
10 LSB
Gain Error
Gain = 1x 10 LSB
Gain = 20x 15 LSB
Offset Error
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
3 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
4 LSB
Conversion Time Free Running Conversion 70 280 µs
Clock Frequency 50 200 kHz
VIN Input Voltage GND VCC V
VDIFF Input Differential Voltage VREF/Gain V
Input Bandwidth 4 kHz
AREF External Reference Voltage 2.0 VCC - 1.0 V
VINT Internal Voltage Reference 1.0 1.1 1.2 V
RREF Reference Input Resistance 32 kΩ
RAIN Analog Input Resistance 100 MΩ
ADC Conversion Output 0 1023 LSB179
8183F–AVR–06/12
ATtiny24A/44A/84A
Table 20-9. ADC Characteristics, Differential Channels (Bipolar Mode), TA = -40°C to +85°C
Symbol Parameter Condition Min Typ Max Units
Resolution
Gain = 1x 10 Bits
Gain = 20x 10 Bits
Absolute accuracy
(Including INL, DNL, and Quantization, Gain
and Offset Errors)
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
8 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
8 LSB
Integral Non-Linearity (INL)
(Accuracy after Offset and Gain Calibration)
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
4 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
5 LSB
Gain Error
Gain = 1x 4 LSB
Gain = 20x 5 LSB
Offset Error
Gain = 1x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
3 LSB
Gain = 20x
VREF = 4V, VCC = 5V
ADC clock = 50 - 200 kHz
4 LSB
Conversion Time Free Running Conversion 70 280 µs
Clock Frequency 50 200 kHz
VIN Input Voltage GND VCC V
VDIFF Input Differential Voltage VREF/Gain V
Input Bandwidth 4 kHz
AREF External Reference Voltage 2.0 VCC - 1.0 V
VINT Internal Voltage Reference 1.0 1.1 1.2 V
RREF Reference Input Resistance 32 kΩ
RAIN Analog Input Resistance 100 MΩ
ADC Conversion Output -512 511 LSB180
8183F–AVR–06/12
ATtiny24A/44A/84A
20.7 Analog Comparator Characteristics
Note: All parameters are based on simulation results and are not tested in production
20.8 Serial Programming Characteristics
Figure 20-3. Serial Programming Timing
Figure 20-4. Serial Programming Waveform
Table 20-10. Analog Comparator Characteristics, TA = -40°C to +85°C
Symbol Parameter Condition Min Typ Max Units
VAIO Input Offset Voltage VCC = 5V, VIN = VCC / 2 < 10 40 mV
ILAC Input Leakage Current VCC = 5V, VIN = VCC / 2 -50 50 nA
tAPD
Analog Propagation Delay
(from saturation to slight overdrive)
VCC = 2.7V 750
ns
VCC = 4.0V 500
Analog Propagation Delay
(large step change)
VCC = 2.7V 100
VCC = 4.0V 75
tDPD Digital Propagation Delay VCC = 1.8V - 5.5 1 2 CLK
Table 20-11. Serial Programming Characteristics, TA = -40°C to +85°C, VCC = 1.8 - 5.5V
(Unless Otherwise Noted)
Symbol Parameter Min Typ Max Units
1/tCLCL Oscillator Frequency 0 4 MHz
tCLCL Oscillator Period 250 ns
1/tCLCL Oscillator Freq. (VCC = 4.5V - 5.5V) 0 20 MHz
MOSI
MISO
SCK
t
OVSH
t
SHSL
t t
SHOX SLSH
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT181
8183F–AVR–06/12
ATtiny24A/44A/84A
Note: 1. 2 tCLCL for fck < 12 MHz, 3 tCLCL for fck >= 12 MHz
20.9 High-Voltage Serial Programming Characteristics
Figure 20-5. High-voltage Serial Programming Timing
tCLCL Oscillator Period (VCC = 4.5V - 5.5V) 50 ns
tSHSL SCK Pulse Width High 2 tCLCL(1) ns
tSLSH SCK Pulse Width Low 2 tCLCL(1) ns
tOVSH MOSI Setup to SCK High tCLCL ns
tSHOX MOSI Hold after SCK High 2 tCLCL ns
Table 20-11. Serial Programming Characteristics, TA = -40°C to +85°C, VCC = 1.8 - 5.5V
(Unless Otherwise Noted)
Symbol Parameter Min Typ Max Units
Table 20-12. High-voltage Serial Programming Characteristics
TA = 25°C, VCC = 5V (Unless otherwise noted)
Symbol Parameter Min Typ Max Units
tSHSL SCI (PB0) Pulse Width High 125 ns
tSLSH SCI (PB0) Pulse Width Low 125 ns
tIVSH SDI (PA6), SII (PB1) Valid to SCI (PB0) High 50 ns
tSHIX SDI (PA6), SII (PB1) Hold after SCI (PB0) High 50 ns
tSHOV SCI (PB0) High to SDO (PA4) Valid 16 ns
tWLWH_PFB Wait after Instr. 3 for Write Fuse Bits 2.5 ms
SDI (PA6), SII (PA5)
SDO (PA4)
SCI (PB0)
t
IVSH
t
SHSL
t t
SHIX SLSH
t
SHOV182
8183F–AVR–06/12
ATtiny24A/44A/84A
21. Typical Characteristics
The data contained in this section is largely based on simulations and characterization of similar
devices in the same process and design methods. Thus, the data should be treated as indications
of how the part will behave.
The following charts show typical behavior. These figures are not tested during manufacturing.
During characterisation devices are operated at frequencies higher than test limits but they are
not guaranteed to function properly at frequencies higher than the ordering code indicates.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. Current consumption is a function of several factors such as operating
voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed
and ambient temperature. The dominating factors are operating voltage and frequency.
A sine wave generator with rail-to-rail output is used as clock source but current consumption in
Power-Down mode is independent of clock selection. The difference between current consumption
in Power-Down mode with Watchdog Timer enabled and Power-Down mode with Watchdog
Timer disabled represents the differential current drawn by the Watchdog Timer.
The current drawn from pins with a capacitive load may be estimated (for one pin) as follows:
where VCC = operating voltage, CL = load capacitance and fSW = average switching frequency of
I/O pin.
21.1 Supply Current of I/O Modules
The tables and formulas below can be used to calculate the additional current consumption for
the different I/O modules in Active and Idle mode. The enabling or disabling of the I/O modules
is controlled by the Power Reduction Register. See “Power Reduction Register” on page 35 for
details.
Table 21-2 below can be used for calculating typical current consumption for other supply voltages
and frequencies than those mentioned in the Table 21-1 above.
I
CP VCC CL × × f
SW ≈
Table 21-1. Additional Current Consumption for the different I/O modules (absolute values)
PRR bit
Typical numbers
VCC = 2V, f = 1 MHz VCC = 3V, f = 4 MHz VCC = 5V, f = 8 MHz
PRTIM1 1.6 µA 11 µA 48 µA
PRTIM0 4.4 µA 29 µA 120 µA
PRUSI 1.6 µA 11 µA 48 µA
PRADC 8.0 µA 55 µA 240 µA183
8183F–AVR–06/12
ATtiny24A/44A/84A
21.1.1 Example
Calculate the expected current consumption in idle mode with USI, TIMER0, and ADC enabled
at VCC = 2.0V and f = 1 MHz. From Table 21-2 on page 183, third column, we see that we need
to add 5% for the USI, 10% for TIMER0, and 20% for the ADC. Reading from Figure 21-61 on
page 213, we find that current consumption in idle mode at 2V and 1 MHz is about 0.04 mA. The
total current consumption in idle mode with USI, TIMER0, and ADC enabled is therefore:
21.2 ATtiny24A
21.2.1 Current Consumption in Active Mode
Figure 21-1. Active Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
Table 21-2. Additional Current Consumption (percentage) in Active and Idle mode
PRR bit
Current consumption additional to
active mode with external clock
(see Figure 21-56 and Figure 21-57)
Current consumption additional to
idle mode with external clock
(see Figure 21-61 and Figure 21-62)
PRTIM1 1 % 5 %
PRTIM0 3 % 10 %
PRUSI 1 % 5 %
PRADC 5 % 20 %
ICCTOT ≈ ≈ 0,05mA × ( ) 1 0,05 0,10 0,20 +++ 0,06mA
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,2
0,4
0,6
0,8
1
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)184
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-2. Active Supply Current vs. Frequency
1 - 20 MHz, PRR = 0xFF
Figure 21-3. Active Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
0
2
4
6
8
10
12
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)185
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-4. Active Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
Figure 21-5. Active Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)186
8183F–AVR–06/12
ATtiny24A/44A/84A
21.2.2 Current Consumption in Idle Mode
Figure 21-6. Idle Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
Figure 21-7. Idle Supply Current vs. Frequency
1 - 20 MHz, PRR = 0xFF
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
0
0,5
1
1,5
2
2,5
3
3,5
4
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V187
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-8. Idle Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
Figure 21-9. Idle Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,8
2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0,05
0,1
0,15
0,2
0,25
0,3
0,35
0,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)188
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-10. Idle Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
21.2.3 Current Consumption in Power-down Mode
Figure 21-11. Power-down Supply Current vs. VCC
Watchdog Timer Disabled
85 °C
25 °C
-40 °C
0
0,005
0,01
0,015
0,02
0,025
0,03
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)189
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-12. Power-down Supply Current vs. VCC
Watchdog Timer Enabled
21.2.4 Current Consumption in Reset
Figure 21-13. Reset Supply Current vs. VCC
0.1 - 1.0 MHz, Excluding Current through Reset Pull-up
85 °C
25 °C
-40 °C
0
2
4
6
8
10
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0,16
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)190
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-14. Reset Supply Current vs. VCC
1 - 20 MHz, Excluding Current through Reset Pull-up
21.2.5 Current Consumption of Peripheral Units
Figure 21-15. ADC Current vs. VCC
4 MHz Frequency
0
0,5
1
1,5
2
2,5
3
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
100
200
300
400
500
600
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)191
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-16. AREF Pin Current vs. Pin Voltage
Figure 21-17. Analog Comparator Current vs. VCC
4 MHz Frequency
0
20
40
60
80
100
120
140
160
180
200
1,5 2 2,5 3 3,5 4 4,5 5 5,5
AREF (V)
AREF pin current (uA)
0
20
40
60
80
100
120
140
160
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)192
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-18. Programming Current vs. VCC
Figure 21-19. Brownout Detector Current vs. VCC
BOD Level = 1.8V
85 °C
25 °C
-40 °C
0
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
1,5 2,5 3,5 4,5 5,5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
40
45
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)193
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-20. Watchdog Timer Current vs. VCC
21.2.6 Pull-up Resistors
Figure 21-21. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 1.8V
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
7
8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
85 °C
-40 °C
25 °C
0
10
20
30
40
50
60
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VOP (V)
IOP (uA)194
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-22. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 2.7V
Figure 21-23. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 5V
0
10
20
30
40
50
60
70
80
0 0,5 1 1,5 2 2,5 3
VOP (V)
IOP (uA)
85 °C
-40 °C
25 °C
0
20
40
60
80
100
120
140
160
0 1 2 3 4 5 6
VOP (V)
IOP (uA)
85 °C
-40 °C
25 °C195
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-24. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 1.8V
Figure 21-25. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 2.7V
0
5
10
15
20
25
30
35
40
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VRESET (V)
IRESET (uA)
85 °C
-40 °C
25 °C
0
10
20
30
40
50
60
0 0,5 1 1,5 2 2,5 3
VRESET (V)
IRESET (uA)
85 °C
-40 °C
25 °C196
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-26. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 5V
21.2.7 Output Driver Strength
Figure 21-27. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 3V
0
20
40
60
80
100
120
0 1 2 3 4 5 6
VRESET (V)
IRESET (uA)
85 °C
-40 °C
25 °C
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
0 5 10 15 20
IOL (mA)
VOL (V)197
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-28. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 5V
Figure 21-29. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 3V
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0 5 10 15 20
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C
1,8
2
2,2
2,4
2,6
2,8
3
3,2
0 5 10 15 20
IOH (mA)
VOH (V)198
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-30. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 5V
Figure 21-31. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
4,2
4,4
4,6
4,8
5
5,2
0 5 10 15 20
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
0 0,5 1 1,5 2 2,5 3
IOL (mA)
VOL (V)199
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-32. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 5V
Figure 21-33. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
IOH (mA)
VOH (V)200
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-34. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 5V
21.2.8 Input Threshold and Hysteresis (for I/O Ports)
Figure 21-35. VIH: Input Threshold Voltage vs. VCC
I/O Pin, Read as ‘1’
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
3,5
4
4,5
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
3,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)201
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-36. VIL: Input Threshold Voltage vs. VCC
I/O Pin, Read as ‘0’
Figure 21-37. VIH-VIL: Input Hysteresis vs. VCC
I/O Pin
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)202
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-38. VIH: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘1’
Figure 21-39. VIL: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘0’
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)203
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-40. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin as I/O
21.2.9 BOD, Bandgap and Reset
Figure 21-41. BOD Threshold vs. Temperature
BODLEVEL is 4.3V
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (V)
RISING VCC
FALLING VCC
4,26
4,28
4,3
4,32
4,34
4,36
4,38
4,4
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (C)
Threshold (V)204
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-42. BOD Threshold vs. Temperature
BODLEVEL is 2.7V
Figure 21-43. BOD Threshold vs. Temperature
BODLEVEL is 1.8V
2,68
2,7
2,72
2,74
2,76
2,78
2,8
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (C)
Threshold (V)
RISING VCC
FALLING VCC
RISING VCC
FALLING VCC
1,77
1,78
1,79
1,8
1,81
1,82
1,83
1,84
1,85
1,86
1,87
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (C)
Threshold (V)205
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-44. Bandgap Voltage vs. Supply Voltage
Figure 21-45. Bandgap Voltage vs. Temperature
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
1,16
1,18
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
Vcc (V)
Bandgap Voltage (V)
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
1,16
1,18
1,2
-40 -20 0 20 40 60 80 100
Temperature (C)
Bandgap Voltage (V)206
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-46. VIH: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘1’
Figure 21-47. VIL: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘0’
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)207
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-48. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin
Figure 21-49. Minimum Reset Pulse Width vs. VCC
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
85 °C
25 °C
-40 °C
0
200
400
600
800
1000
1200
1400
1600
1800
2000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Pulsewidth (ns)208
8183F–AVR–06/12
ATtiny24A/44A/84A
21.2.10 Analog Comparator Offset
Figure 21-50. Analog Comparator Offset
VCC = 5V
21.2.11 Internal Oscillator Speed
Figure 21-51. Watchdog Oscillator Frequency vs. VCC
85
25
-40
-0.008
-0.006
-0.004
-0.002
0
0.002
0.004
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VIN (V)
Offset (V)
85 °C
25 °C
-40 °C
112
114
116
118
120
122
124
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (kHz)209
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-52. Watchdog Oscillator Frequency vs. Temperature
Figure 21-53. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
5.5 V
3.0 V
1.8 V
112
114
116
118
120
122
124
-40 -20 0 20 40 60 80 100
Temperature (C)
FRC (kHz)
85 °C
25 °C
-40 °C
7,4
7,6
7,8
8
8,2
8,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (MHz)210
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-54. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature
Figure 21-55. Calibrated 8 MHz RC Oscillator Frequency vs. OSCCAL Value
VCC = 3V
5.5 V
3.0 V
1.8 V
7,5
7,6
7,7
7,8
7,9
8
8,1
8,2
8,3
8,4
-40 -20 0 20 40 60 80 100
Temperature (C)
FRC (MHz)
85 °C
25 °C
-40 °C
0
4
8
12
16
20
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL (X1)
FRC (MHz)211
8183F–AVR–06/12
ATtiny24A/44A/84A
21.3 ATtiny44A
21.3.1 Current Consumption in Active Mode
Figure 21-56. Active Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
Figure 21-57. Active Supply Current vs. frequency
1 - 20 MHz, PRR = 0xFF
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.2
0.4
0.6
0.8
1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
2
4
6
8
10
12
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)212
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-58. Active Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
Figure 21-59. Active Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)213
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-60. Active Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
21.3.2 Current Consumption in Idle Mode
Figure 21-61. Idle Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
85 °C
25 °C
-40 °C
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0.2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)214
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-62. Idle Supply Current vs. Frequency
1 - 20 MHz, PRR = 0xFF
Figure 21-63. Idle Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V 0
0.5
1
1.5
2
2.5
3
3.5
4
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)215
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-64. Idle Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
Figure 21-65. Idle Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
85 °C
25 °C
-40 °C
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0.005
0.01
0.015
0.02
0.025
0.03
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)216
8183F–AVR–06/12
ATtiny24A/44A/84A
21.3.3 Standby Supply Current
Figure 21-66. Standby Supply Current vs. VCC
4 MHz External Crystal, 22 pF External Capacitors, Watchdog Timer Disabled
21.3.4 Current Consumption in Power-down Mode
Figure 21-67. Power-down Supply Current vs. VCC
Watchdog Timer Disabled
85 °C
25 °C
-40 °C
0
0.02
0.04
0.06
0.08
0.1
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)217
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-68. Power-down Supply Current vs. VCC
Watchdog Timer Enabled
21.3.5 Current Consumption in Reset
Figure 21-69. Reset Supply Current vs. VCC
0.1 - 1.0 MHz, Excluding Current through Reset Pull-up
85 °C
25 °C
-40 °C
0
2
4
6
8
10
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)218
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-70. Reset Supply Current vs. VCC
1 - 20 MHz, Excluding Current Through Reset Pull-up
21.3.6 Current Consumption of Peripheral Units
Figure 21-71. ADC Current vs. VCC
4 MHz Frequency
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0.5
1
1.5
2
2.5
3
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
0
100
200
300
400
500
600
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)219
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-72. AREF Pin Current vs. Pin Voltage
Figure 21-73. Analog Comparator Current vs. VCC
4 MHz Frequency
0
20
40
60
80
100
120
140
160
180
1.5 2 2.5 3 3.5 4 4.5 5 5.5
AREF (V)
AREF pin current (uA)
0
20
40
60
80
100
120
140
160
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)220
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-74. Programming Current vs. VCC
Figure 21-75. Brownout Detector Current vs. VCC
BOD Level = 1.8V
85 °C
25 °C
-40 °C
0
2000
4000
6000
8000
10000
12000
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (uA)221
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-76. Watchdog Timer Current vs. VCC
21.3.7 Pull-up Resistors
Figure 21-77. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 1.8V
85 °C
25 °C
-40 °C
0
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
ICC (mA)
85 °C
25 °C
-40 °C 0
10
20
30
40
50
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOP (V)
IOP (uA)222
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-78. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 2.7V
Figure 21-79. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 5V
85 °C
25 °C
-40 °C 0
10
20
30
40
50
60
70
80
0 0.5 1 1.5 2 2.5 3
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C 0
20
40
60
80
100
120
140
160
012345
VOP (V)
IOP (uA)223
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-80. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 1.8V
Figure 21-81. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 2.7V
0
5
10
15
20
25
30
35
40
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
85 °C
25 °C
0 -40 °C
10
20
30
40
50
60
0 0.5 1 1.5 2 2.5 3
VRESET (V)
IRESET (uA)224
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-82. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 5V
21.3.8 Output Driver Strength
Figure 21-83. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 3V
85 °C
25 °C
-40 °C 0
20
40
60
80
100
120
012345
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
0 5 10 15 20
IOL (mA)
VOL (V)225
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-84. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 5V
Figure 21-85. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 3V
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 5 10 15 20
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C
1.8
2
2.2
2.4
2.6
2.8
3
3.2
0 5 10 15 20
IOH (mA)
VOH (V)226
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-86. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 5V
Figure 21-87. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
4.2
4.4
4.6
4.8
5
5.2
0 5 10 15 20
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
0 0.5 1 1.5 2 2.5 3
IOL (mA)
VOL (V)227
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-88. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 5V
Figure 21-89. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
012345678
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
IOH (mA)
VOH (V)228
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-90. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 5V
21.3.9 Input Threshold and Hysteresis (for I/O Ports)
Figure 21-91. VIH: Input Threshold Voltage vs. VCC
IO Pin, Read as ‘1’
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
5
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
3.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Threshold (V)229
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-92. VIL: Input Threshold Voltage vs. VCC
I/O Pin, Read as ‘0’
Figure 21-93. VIH-VIL: Input Hysteresis vs. VCC
I/O Pin
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Input Hysteresis (V)230
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-94. VIH: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘1’
Figure 21-95. VIL: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘0’
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Threshold (V)231
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-96. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin as I/O
21.3.10 BOD, Bandgap and Reset
Figure 21-97. BOD Threshold vs. Temperature
BODLEVEL is 4.3V
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Input Hysteresis (V)
4.2
4.22
4.24
4.26
4.28
4.3
4.32
4.34
4.36
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
RISING VCC
FALLING VCC232
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-98. BOD Threshold vs. Temperature
BODLEVEL is 2.7V
Figure 21-99. BOD Threshold vs. Temperature
BODLEVEL is 1.8V
2.64
2.66
2.68
2.7
2.72
2.74
2.76
2.78
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
RISING VCC
FALLING VCC
RISING VCC
FALLING VCC
1.77
1.78
1.79
1.8
1.81
1.82
1.83
1.84
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)233
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-100. Bandgap Voltage vs. Supply Voltage
Figure 21-101. Bandgap Voltage vs. Temperature
1
1.02
1.04
1.06
1.08
1.1
1.12
1.14
1.16
1.18
1.2
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Bandgap Voltage (V)
1
1.02
1.04
1.06
1.08
1.1
1.12
1.14
1.16
1.18
1.2
-40 -20 0 20 40 60 80 100
Temperature (C)
Bandgap Voltage (V)234
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-102. VIH: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘1’
Figure 21-103. VIL: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘0’
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)235
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-104. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin
Figure 21-105. Minimum Reset Pulse Width vs. VCC
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Input Hysteresis (V)
85 °C
25 °C
-40 °C
0
200
400
600
800
1000
1200
1400
1600
1800
2000
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Pulsewidth (ns)236
8183F–AVR–06/12
ATtiny24A/44A/84A
21.3.11 Analog Comparator Offset
Figure 21-106. Analog Comparator Offset
VCC = 5V
21.3.12 Internal Oscillator Speed
Figure 21-107. Watchdog Oscillator Frequency vs. VCC
85
25
-40
-0.007
-0.006
-0.005
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0.004
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VIN (V)
Offset (V)
85 °C
25 °C
-40 °C
0.108
0.11
0.112
0.114
0.116
0.118
0.12
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Frequency (MHz)237
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-108. Watchdog Oscillator Frequency vs. Temperature
Figure 21-109. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
5.5 V
3.0 V
1.8 V
0.106
0.108
0.11
0.112
0.114
0.116
0.118
0.12
-40 -20 0 20 40 60 80 100
Temperature (C)
Frequency (MHz)
7.4
7.6
7.8
8
8.2
8.4
1.5 2 2.5 3 3.5 4 4.5 5 5.5
V CC (V)
Frequency (MHz)
85 °C
25 °C
-40 °C238
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-110. Calibrated 8 MHz RC oscillator Frequency vs. Temperature
Figure 21-111. Calibrated 8 MHz RC Oscillator Frequency vs. OSCCAL Value
VCC = 3V
5.0 V
3.0 V
1.8 V
7.5
7.6
7.7
7.8
7.9
8
8.1
8.2
-40 -20 0 20 40 60 80 100
Temperature (C)
Frequency (MHz)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
16
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL (X1)
Frequency (MHz)239
8183F–AVR–06/12
ATtiny24A/44A/84A
21.4 ATtiny84A
21.4.1 Current Consumption in Active Mode
Figure 21-112. Active Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
Figure 21-113. Active Supply Current vs. Frequency
1 - 20 MHz, PRR = 0xFF
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,2
0,4
0,6
0,8
1
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
2
4
6
8
10
12
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)240
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-114. Active Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
Figure 21-115. Active Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
3,5
4
4,5
5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)241
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-116. Active Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
21.4.2 Current Consumption in Idle Mode
Figure 21-117. Idle Supply Current vs. Low Frequency
0.1 - 1.0 MHz, PRR = 0xFF
85 °C
25 °C
-40 °C
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)242
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-118. Idle Supply Current vs. Frequency
1 - 20 MHz, PRR = 0xFF
Figure 21-119. Idle Supply Current vs. VCC
Internal RC Oscillator, 8 MHz
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V 0
0,5
1
1,5
2
2,5
3
3,5
4
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,8
2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C243
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-120. Idle Supply Current vs. VCC
Internal RC Oscillator, 1 MHz
Figure 21-121. Idle Supply Current vs. VCC
Internal RC Oscillator, 128 kHz
85 °C
25 °C
-40 °C
0
0,05
0,1
0,15
0,2
0,25
0,3
0,35
0,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
0
0,005
0,01
0,015
0,02
0,025
0,03
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C244
8183F–AVR–06/12
ATtiny24A/44A/84A
21.4.3 Current Consumption in Power-down Mode
Figure 21-122. Power-down Supply Current vs. VCC
Watchdog Timer Disabled
Figure 21-123. Power-down Supply Current vs. VCC
Watchdog Timer Enabled
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C245
8183F–AVR–06/12
ATtiny24A/44A/84A
21.4.4 Current Consumption in Reset
Figure 21-124. Reset Supply Current vs. VCC
0.1 - 1.0 MHz, Excluding Current through Reset Pull-up
Figure 21-125. Reset Supply Current vs. VCC
1 - 20 MHz, Excluding Current through Reset Pull-up
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V
0
0,02
0,04
0,06
0,08
0,1
0,12
0,14
0,16
0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.3 V
2.7 V
1.8 V 0
0,5
1
1,5
2
2,5
3
0 2 4 6 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)246
8183F–AVR–06/12
ATtiny24A/44A/84A
21.4.5 Current Consumption of Peripheral Units
Figure 21-126. ADC Current vs. VCC
4 MHz Frequency
Figure 21-127. AREF Pin Current vs. Pin Voltage
0
100
200
300
400
500
600
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
0
20
40
60
80
100
120
140
160
1,5 2 2,5 3 3,5 4 4,5 5 5,5
AREF (V)
AREF pin current (uA)247
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-128. Analog Comparator Current vs. VCC
4 MHz Frequency
Figure 21-129. Programming Current vs. VCC
0
20
40
60
80
100
120
140
160
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
1000
2000
3000
4000
5000
6000
7000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)248
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-130. Brownout Detector Current vs. VCC
BOD Level = 1.8V
21.4.6 Pull-up Resistors
Figure 21-131. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 1.8V
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
40
45
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VOP (V)
IOP (uA)249
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-132. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 2.7V
Figure 21-133. Pull-up Resistor Current vs. Input Voltage
I/O Pin, VCC = 5V
85 °C
25 °C
-40 °C 0
10
20
30
40
50
60
70
80
0 0,5 1 1,5 2 2,5 3
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C 0
20
40
60
80
100
120
140
160
0 1 2 3 4 5 6
VOP (V)
IOP (uA)250
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-134. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 1.8V
Figure 21-135. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 2.7V
85 °C
25 °C
-40 °C
0
5
10
15
20
25
30
35
40
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
0 0,5 1 1,5 2 2,5 3
VRESET (V)
IRESET (uA)251
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-136. Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 5V
21.4.7 Output Driver Strength
Figure 21-137. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 3V
85 °C
25 °C
-40 °C
0
20
40
60
80
100
120
0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
VOL (V)252
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-138. VOL: Output Voltage vs. Sink Current
I/O Pin, VCC = 5V
Figure 21-139. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 3V
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0 2 4 6 8 10 12 14 16 18 20
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C
1,8
2
2,2
2,4
2,6
2,8
3
3,2
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
VOH (V)253
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-140. VOH: Output Voltage vs. Source Current
I/O Pin, VCC = 5V
Figure 21-141. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
4,2
4,4
4,6
4,8
5
5,2
0 2 4 6 8 10 12 14 16 18 20
IOH (mA)
VOH (V)
0
0,2
0,4
0,6
0,8
1
1,2
1,4
0 0,5 1 1,5 2 2,5 3
IOL (mA)
VOL (V)
85 °C
25 °C
-40 °C254
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-142. VOL: Output Voltage vs. Sink Current
Reset Pin as I/O, VCC = 5V
Figure 21-143. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 3V
85 °C
25 °C
-40 °C
0
0,2
0,4
0,6
0,8
1
1,2
1,4
1,6
1,8
2
012345678
IOL (mA)
VOL (V)
0
0,5
1
1,5
2
2,5
3
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C255
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-144. VOH: Output Voltage vs. Source Current
Reset Pin as I/O, VCC = 5V
21.4.8 Input Threshold and Hysteresis (for I/O Ports)
Figure 21-145. VIH: Input Threshold Voltage vs. VCC
I/O Pin, Read as ‘1’
0
0,5
1
1,5
2
2,5
3
3,5
4
4,5
5
0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
IOH (mA)
VOH (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
3
3,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C256
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-146. VIL: Input Threshold Voltage vs. VCC
I/O Pin, Read as ‘0’
Figure 21-147. VIH-VIL: Input Hysteresis vs. VCC
I/O Pin
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
0
0,1
0,2
0,3
0,4
0,5
0,6
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
85 °C
25 °C
-40 °C257
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-148. VIH: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘1’
Figure 21-149. VIL: Input Threshold Voltage vs. VCC
Reset Pin as I/O, Read as ‘0’
0
0,5
1
1,5
2
2,5
3
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C258
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-150. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin as I/O
21.4.9 BOD, Bandgap and Reset
Figure 21-151. BOD Threshold vs. Temperature
BODLEVEL is 4.3V
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V) 4,24
4,26
4,28
4,3
4,32
4,34
4,36
4,38
4,4
4,42
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
RISING VCC
FALLING VCC259
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-152. BOD Threshold vs. Temperature
BODLEVEL is 2.7V
Figure 21-153. Bandgap Voltage vs. Supply Voltage
2,66
2,68
2,7
2,72
2,74
2,76
2,78
2,8
2,82
-40 -20 0 20 40 60 80 100
Temperature (C)
Threshold (V)
RISING VCC
FALLING VCC
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
1,16
1,18
1,2
1,5 2 2,5 3 3,5 4 4,5 5 5,5
Vcc (V)
Bandgap Voltage (V)260
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-154. Bandgap Voltage vs. Temperature
Figure 21-155. VIH: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘1’
1
1,02
1,04
1,06
1,08
1,1
1,12
1,14
1,16
1,18
1,2
-40 -20 0 20 40 60 80 100
Temperature (C)
Bandgap Voltage (V)
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C261
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-156. VIL: Input Threshold Voltage vs. VCC
Reset Pin, Read as ‘0’
Figure 21-157. VIH-VIL: Input Hysteresis vs. VCC
Reset Pin
0
0,5
1
1,5
2
2,5
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Threshold (V)
85 °C
25 °C
-40 °C
0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
0,9
1
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Input Hysteresis (V)
85 °C
25 °C
-40 °C262
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-158. Minimum Reset Pulse Width vs. VCC
21.4.10 Analog Comparator Offset
Figure 21-159. Analog Comparator Offset
VCC = 5V
0
200
400
600
800
1000
1200
1400
1600
1800
2000
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
Pulsewidth (ns)
85 °C
25 °C
-40 °C
85
25
-40
-0.012
-0.01
-0.008
-0.006
-0.004
-0.002
0
0.002
0.004
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Vin (V)
Offset (V)263
8183F–AVR–06/12
ATtiny24A/44A/84A
21.4.11 Internal Oscillator Speed
Figure 21-160. Watchdog Oscillator Frequency vs. VCC
Figure 21-161. Watchdog Oscillator Frequency vs. Temperature
108
110
112
114
116
118
120
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (kHz)
85 °C
25 °C
-40 °C
5.5 V
3.0 V
1.8 V
106
108
110
112
114
116
118
120
-40 -20 0 20 40 60 80 100
Temperature (C)
FRC (kHz)264
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-162. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
Figure 21-163. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature
7,4
7,5
7,6
7,7
7,8
7,9
8
8,1
8,2
8,3
8,4
1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC (V)
FRC (MHz)
85 °C
25 °C
-40 °C
5.0 V
3.0 V
1.8 V
7,5
7,6
7,7
7,8
7,9
8
8,1
8,2
8,3
8,4
-40 -20 0 20 40 60 80 100
Temperature (C)
FRC (MHz)265
8183F–AVR–06/12
ATtiny24A/44A/84A
Figure 21-164. Calibrated 8 MHz RC Oscillator Frequency vs. OSCCAL Value
VCC = 3V
0
2
4
6
8
10
12
14
16
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL (X1)
FRC (MHz)
85 °C
25 °C
-40 °C266
8183F–AVR–06/12
ATtiny24A/44A/84A
22. Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x3F (0x5F) SREG I T H S V N Z C Page 14
0x3E (0x5E) SPH – – – – – – SP9 SP8 Page 13
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 Page 13
0x3C (0x5C) OCR0B Timer/Counter0 – Output Compare Register B Page 83
0x3B (0x5B) GIMSK – INT0 PCIE1 PCIE0 – – – – Page 50
0x3A (0x5A) GIFR – INTF0 PCIF1 PCIF0 – – – – Page 51
0x39 (0x59) TIMSK0 – – – – – OCIE0B OCIE0A TOIE0 Page 83
0x38 (0x58) TIFR0 – – – – – OCF0B OCF0A TOV0 Page 84
0x37 (0x57) SPMCSR – – RSIG CTPB RFLB PGWRT PGERS SPMEN Page 156
0x36 (0x56) OCR0A Timer/Counter0 – Output Compare Register A Page 83
0x35 (0x55) MCUCR BODS PUD SE SM1 SM0 BODSE ISC01 ISC00 Pages 36, 50, 66
0x34 (0x54) MCUSR – – – – WDRF BORF EXTRF PORF Page 44
0x33 (0x53) TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00 Page 82
0x32 (0x52) TCNT0 Timer/Counter0 Page 83
0x31 (0x51) OSCCAL CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 Page 31
0x30 (0x50) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 Page 79
0x2F (0x4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 Page 106
0x2E (0x4E) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 Page 108
0x2D (0x4D) TCNT1H Timer/Counter1 – Counter Register High Byte Page 110
0x2C (0x4C) TCNT1L Timer/Counter1 – Counter Register Low Byte Page 110
0x2B (0x4B) OCR1AH Timer/Counter1 – Compare Register A High Byte Page 110
0x2A (0x4A) OCR1AL Timer/Counter1 – Compare Register A Low Byte Page 110
0x29 (0x49) OCR1BH Timer/Counter1 – Compare Register B High Byte Page 110
0x28 (0x48) OCR1BL Timer/Counter1 – Compare Register B Low Byte Page 110
0x27 (0x47) DWDR DWDR[7:0] Page 151
0x26 (0x46) CLKPR CLKPCE – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 Page 31
0x25 (0x45) ICR1H Timer/Counter1 - Input Capture Register High Byte Page 111
0x24 (0x44) ICR1L Timer/Counter1 - Input Capture Register Low Byte Page 111
0x23 (0x43) GTCCR TSM – – – – – – PSR10 Page 114
0x22 (0x42) TCCR1C FOC1A FOC1B – – – – – – Page 109
0x21 (0x41) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 Page 44
0x20 (0x40) PCMSK1 – – – – PCINT11 PCINT10 PCINT9 PCINT8 Page 51
0x1F (0x3F) EEARH – – – – – – – EEAR8 Page 20
0x1E (0x3E) EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 Page 21
0x1D (0x3D) EEDR EEPROM Data Register Page 21
0x1C (0x3C) EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE Page 23
0x1B (0x3B) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0 Page 66
0x1A (0x3A) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0 Page 66
0x19 (0x39) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0 Page 67
0x18 (0x38) PORTB – – – – PORTB3 PORTB2 PORTB1 PORTB0 Page 67
0x17 (0x37) DDRB – – – – DDB3 DDB2 DDB1 DDB0 Page 67
0x16 (0x36) PINB – – – – PINB3 PINB2 PINB1 PINB0 Page 67
0x15 (0x35) GPIOR2 General Purpose I/O Register 2 Page 22
0x14 (0x34) GPIOR1 General Purpose I/O Register 1 Page 23
0x13 (0x33) GPIOR0 General Purpose I/O Register 0 Page 23
0x12 (0x32) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 Page 52
0x11 (0x31)) Reserved –
0x10 (0x30) USIBR USI Buffer Register Page 127
0x0F (0x2F) USIDR USI Data Register Page 126
0x0E (0x2E) USISR USISIF USIOIF USIPF USIDC USICNT3 USICNT2 USICNT1 USICNT0 Page 125
0x0D (0x2D) USICR USISIE USIOIE USIWM1 USIWM0 USICS1 USICS0 USICLK USITC Page 123
0x0C (0x2C) TIMSK1 – – ICIE1 – – OCIE1B OCIE1A TOIE1 Page 111
0x0B (0x2B) TIFR1 – – ICF1 – – OCF1B OCF1A TOV1 Page 112
0x0A (0x2A) Reserved –
0x09 (0x29) Reserved –
0x08 (0x28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 Page 129
0x07 (0x27) ADMUX REFS1 REFS0 MUX5 MUX4 MUX3 MUX2 MUX1 MUX0 Page 144
0x06 (0x26) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 Page 146
0x05 (0x25) ADCH ADC Data Register High Byte Page 148
0x04 (0x24) ADCL ADC Data Register Low Byte Page 148
0x03 (0x23) ADCSRB BIN ACME – ADLAR – ADTS2 ADTS1 ADTS0 Pages 130, 148
0x02 (0x22) Reserved –
0x01 (0x21) DIDR0 ADC7D ADC6D ADC5D ADC4D ADC3D ADC2D ADC1D ADC0D Pages 131, 149
0x00 (0x20) PRR – – – – PRTIM1 PRTIM0 PRUSI PRADC Page 37267
8183F–AVR–06/12
ATtiny24A/44A/84A
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operation the specified bit, and can therefore be used on registers containing such Status Flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.268
8183F–AVR–06/12
ATtiny24A/44A/84A
23. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd ← Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd ← Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd ← Rd • Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd ← Rd • K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd ← Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd ← Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd ← Rd ⊕ Rr Z,N,V 1
COM Rd One’s Complement Rd ← 0xFF − Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd ← 0x00 − Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd ← Rd • (0xFF - K) Z,N,V 1
INC Rd Increment Rd ← Rd + 1 Z,N,V 1
DEC Rd Decrement Rd ← Rd − 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V 1
SER Rd Set Register Rd ← 0xFF None 1
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC ← PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC ← Z None 2
RCALL k Relative Subroutine Call PC ← PC + k + 1 None 3
ICALL Indirect Call to (Z) PC ← Z None 3
RET Subroutine Return PC ← STACK None 4
RETI Interrupt Return PC ← STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd − Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd − Rr − C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd − K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1/2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2
LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z,C,N,V 1269
8183F–AVR–06/12
ATtiny24A/44A/84A
ROR Rd Rotate Right Through Carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1
BSET s Flag Set SREG(s) ← 1 SREG(s) 1
BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) ← T None 1
SEC Set Carry C ← 1 C1
CLC Clear Carry C ← 0 C 1
SEN Set Negative Flag N ← 1 N1
CLN Clear Negative Flag N ← 0 N 1
SEZ Set Zero Flag Z ← 1 Z1
CLZ Clear Zero Flag Z ← 0 Z 1
SEI Global Interrupt Enable I ← 1 I1
CLI Global Interrupt Disable I ← 0 I 1
SES Set Signed Test Flag S ← 1 S1
CLS Clear Signed Test Flag S ← 0 S 1
SEV Set Twos Complement Overflow. V ← 1 V1
CLV Clear Twos Complement Overflow V ← 0 V 1
SET Set T in SREG T ← 1 T1
CLT Clear T in SREG T ← 0 T 1
SEH Set Half Carry Flag in SREG H ← 1 H1
CLH Clear Half Carry Flag in SREG H ← 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd ← Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd ← Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd ← K None 1
LD Rd, X Load Indirect Rd ← (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd ← (X), X ← X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X ← X - 1, Rd ← (X) None 2
LD Rd, Y Load Indirect Rd ← (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd ← (Y), Y ← Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y ← Y - 1, Rd ← (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd ← (Y + q) None 2
LD Rd, Z Load Indirect Rd ← (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd ← (Z), Z ← Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z ← Z - 1, Rd ← (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd ← (k) None 2
ST X, Rr Store Indirect (X) ← Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) ← Rr, X ← X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X ← X - 1, (X) ← Rr None 2
ST Y, Rr Store Indirect (Y) ← Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) ← Rr, Y ← Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y ← Y - 1, (Y) ← Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) ← Rr None 2
ST Z, Rr Store Indirect (Z) ← Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) ← Rr, Z ← Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z ← Z - 1, (Z) ← Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2
STS k, Rr Store Direct to SRAM (k) ← Rr None 2
LPM Load Program Memory R0 ← (Z) None 3
LPM Rd, Z Load Program Memory Rd ← (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd ← (Z), Z ← Z+1 None 3
SPM Store Program Memory (z) ← R1:R0 None
IN Rd, P In Port Rd ← P None 1
OUT P, Rr Out Port P ← Rr None 1
PUSH Rr Push Register on Stack STACK ← Rr None 2
POP Rd Pop Register from Stack Rd ← STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/Timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #Clocks270
8183F–AVR–06/12
ATtiny24A/44A/84A
24. Ordering Information
Notes: 1. For speed vs. supply voltage, see section 20.3 “Speed” on page 174.
2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous
Substances (RoHS)
3. Code indicators:
– H: NiPdAu lead finish
– F, N, U: matte tin
– R: tape & reel
4. Topside marking for ATtiny24A: T24 / Axx / manufacturing data
5. Also supplied in wafer form. Contact your local Atmel sales office for ordering information and minimum quantities.
6. For typical and electrical characteristics, see “Appendix A – ATtiny24A/44A Specification at 105°C”.
7. For typical and electrical characteristics, see “Appendix B – ATtiny24A/44A/84A Specification at 125°C”.
24.1 ATtiny24A
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
20 1.8 – 5.5V
Industrial
(-40°C to +85°C) (5)
14S1
ATtiny24A-SSU
ATtiny24A-SSUR
14P3 ATtiny24A-PU
15CC1
ATtiny24A-CCU
ATtiny24A-CCUR
20M1
ATtiny24A-MU
ATtiny24A-MUR
20M2
ATtiny24A-MMH (4)
ATtiny24A-MMHR (4)
Industrial
(-40°C to +105°C) (6) 14S1
ATtiny24A-SSN
ATtiny24A-SSNR
Industrial
(-40°C to +125°C) (7)
14S1
ATtiny24A-SSF
ATtiny24A-SSFR
20M1
ATtiny24A-MF
ATtiny24A-MFR
20M2
ATtiny24A-MM8
ATtiny24A-MM8R
Package Type
14S1 14-lead, 0.150" Wide Body, Plastic Gull Wing Small Outline Package (SOIC)
14P3 14-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
15CC1 15-ball (4 x 4 Array), 0.65 mm Pitch, 3.0 x 3.0 x 0.6 mm, Ultra Thin, Fine-Pitch Ball Grid Array Package (UFBGA)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No Lead / Micro Lead Frame Package (QFN/MLF)
20M2 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)271
8183F–AVR–06/12
ATtiny24A/44A/84A
Notes: 1. For speed vs. supply voltage, see section 20.3 “Speed” on page 174.
2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– F, N, U: matte tin
– R: tape & reel
4. Topside marking for ATtiny44A:
– 1st Line: T44
– 2nd Line: Axx
– 3rd Line: manufacturing data
5. These devices can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
6. For typical and electrical characteristics, see “Appendix A – ATtiny24A/44A Specification at 105°C”.
7. For typical and electrical characteristics, see “Appendix B – ATtiny24A/44A/84A Specification at 125°C”.
24.2 ATtiny44A
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
20 1.8 – 5.5V
Industrial
(-40°C to +85°C) (5)
14S1
ATtiny44A-SSU
ATtiny44A-SSUR
14P3 ATtiny44A-PU
15CC1
ATtiny44A-CCU
ATtiny44A-CCUR
20M1
ATtiny44A-MU
ATtiny44A-MUR
20M2
ATtiny44A-MMH (4)
ATtiny44A-MMHR (4)
Industrial
(-40°C to +105°C) (6) 14S1
ATtiny44A-SSN
ATtiny44A-SSNR
Industrial
(-40°C to +125°C) (7)
14S1
ATtiny44A-SSF
ATtiny44A-SSFR
20M1
ATtiny44A-MF
ATtiny44A-MFR
Package Type
14S1 14-lead, 0.150" Wide Body, Plastic Gull Wing Small Outline Package (SOIC)
14P3 14-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
15CC1 15-ball (4 x 4 Array), 0.65 mm Pitch, 3.0 x 3.0 x 0.6 mm, Ultra Thin, Fine-Pitch Ball Grid Array Package (UFBGA)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No Lead / Micro Lead Frame Package (QFN/MLF)
20M2 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)272
8183F–AVR–06/12
ATtiny24A/44A/84A
Notes: 1. For speed vs. supply voltage, see section 20.3 “Speed” on page 174.
2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous
Substances (RoHS).
3. Code indicators:
– H: NiPdAu lead finish
– F, N, U: matte tin
– R: tape & reel
4. Topside marking for ATtiny84A:
– 1st Line: T84
– 2nd Line: Axx
– 3rd Line: manufacturing data
5. These devices can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
6. For typical and electrical characteristics, see “Appendix A – ATtiny24A/44A Specification at 105°C”.
7. For typical and electrical characteristics, see “Appendix B – ATtiny24A/44A/84A Specification at 125°C”.
24.3 ATtiny84A
Speed (MHz) (1) Supply Voltage (V) Temperature Range Package (2) Ordering Code (3)
20 1.8 – 5.5V
Industrial
(-40°C to +85°C) (5)
14S1
ATtiny84A-SSU
ATtiny84A-SSUR
14P3 ATtiny84A-PU
15CC1
ATtiny84A-CCU
ATtiny84A-CCUR
20M1
ATtiny84A-MU
ATtiny84A-MUR
20M2
ATtiny84A-MMH (4)
ATtiny84A-MMHR (4)
Industrial
(-40°C to +125°C) (7) 14S1
ATtiny84A-SSF
ATtiny84A-SSFR
Package Type
14S1 14-lead, 0.150" Wide Body, Plastic Gull Wing Small Outline Package (SOIC)
14P3 14-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP)
15CC1 15-ball (4 x 4 Array), 0.65 mm Pitch, 3.0 x 3.0 x 0.6 mm, Ultra Thin, Fine-Pitch Ball Grid Array Package (UFBGA)
20M1 20-pad, 4 x 4 x 0.8 mm Body, Quad Flat No Lead / Micro Lead Frame Package (QFN/MLF)
20M2 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)273
8183F–AVR–06/12
ATtiny24A/44A/84A
25. Packaging Information
25.1 14S1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
14S1, 14-lead, 0.150" Wide Body, Plastic Gull
Wing Small Outline Package (SOIC)
2/5/02
14S1 A
A1
E
L
Side View
Top View End View
E H
b
N
1
e
A
D
COMMON DIMENSIONS
(Unit of Measure = mm/inches)
SYMBOL MIN NOM MAX NOTE
Notes: 1. This drawing is for general information only; refer to JEDEC Drawing MS-012, Variation AB for additional information.
2. Dimension D does not include mold Flash, protrusions or gate burrs. Mold Flash, protrusion and gate burrs shall not
exceed 0.15 mm (0.006") per side.
3. Dimension E does not include inter-lead Flash or protrusion. Inter-lead flash and protrusions shall not exceed 0.25 mm
(0.010") per side.
4. L is the length of the terminal for soldering to a substrate.
5. The lead width B, as measured 0.36 mm (0.014") or greater above the seating plane, shall not exceed a maximum value
of 0.61 mm (0.024") per side.
A 1.35/0.0532 – 1.75/0.0688
A1 0.1/.0040 – 0.25/0.0098
b 0.33/0.0130 – 0.5/0.02005
D 8.55/0.3367 – 8.74/0.3444 2
E 3.8/0.1497 – 3.99/0.1574 3
H 5.8/0.2284 – 6.19/0.2440
L 0.41/0.0160 – 1.27/0.0500 4
e 1.27/0.050 BSC274
8183F–AVR–06/12
ATtiny24A/44A/84A
25.2 14P3
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
14P3, 14-lead (0.300"/7.62 mm Wide) Plastic Dual
Inline Package (PDIP) 14P3 B
2010-10-20
PIN
1
E1
A1
B
E
B1
C
L
SEATING PLANE
A
D
e
eB
eC
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A – – 5.334
A1 0.381 – –
D 18.669 – 19.685 Note 2
E 7.620 – 8.255
E1 6.096 – 7.112 Note 2
B 0.356 – 0.559
B1 1.143 – 1.778
L 2.921 – 3.810
C 0.203 – 0.356
eB – – 10.922
eC 0.000 – 1.524
e 2.540 TYP
Notes: 1. This package conforms to JEDEC reference MS-001, Variation AA.
2. Dimensions D and E1 do not include mold Flash or Protrusion.
Mold Flash or Protrusion shall not exceed 0.25 mm (0.010"). 275
8183F–AVR–06/12
ATtiny24A/44A/84A
25.3 15CC1
TITLE GPC DRAWING NO. REV.
Package Drawing Contact:
R packagedrawings@atmel.com CBC C
15CC1, 15-ball (4 x 4 Array), 3.0 x 3.0 x 0.6 mm
package, ball pitch 0.65 mm,
Ultra thin, Fine-Pitch Ball Grid Array Package (UFBGA)
15CC1
07/06/10
A – – 0.60
A1 0.12 – –
A2 0.38 REF
b 0.25 0.30 0.35 1
b1 0.25 – – 2
D 2.90 3.00 3.10
D1 1.95 BSC
E 2.90 3.00 3.10
E1 1.95 BSC
e 0.65 BSC
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
TOP VIEW
123 4
A
B
C
D
E
D
15-Øb
D
C
B
A
Pin#1 ID
0.08
A1
A
D1
E1
A2
A1 BALL CORNER
e
123 4
SIDE VIEW
b1
BOTTOM VIEW
e
Note1: Dimension “b” is measured at the maximum ball dia. in a plane parallel
to the seating plane.
Note2: Dimension “b1” is the solderable surface defined by the opening of the
solder resist layer.276
8183F–AVR–06/12
ATtiny24A/44A/84A
25.4 20M1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
20M1, 20-pad, 4 x 4 x 0.8 mm Body, Lead Pitch 0.50 mm, 20M1 B
10/27/04
2.6 mm Exposed Pad, Micro Lead Frame Package (MLF)
A 0.70 0.75 0.80
A1 – 0.01 0.05
A2 0.20 REF
b 0.18 0.23 0.30
D 4.00 BSC
D2 2.45 2.60 2.75
E 4.00 BSC
E2 2.45 2.60 2.75
e 0.50 BSC
L 0.35 0.40 0.55
SIDE VIEW
Pin 1 ID
Pin #1
Notch
(0.20 R)
BOTTOM VIEW
TOP VIEW
Note: Reference JEDEC Standard MO-220, Fig. 1 (SAW Singulation) WGGD-5.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D
E
e
A2
A1
A
D2
E2
0.08 C
L
1
2
3
b
1
2
3277
8183F–AVR–06/12
ATtiny24A/44A/84A
25.5 20M2
TITLE GPC DRAWING NO. REV.
Package Drawing Contact:
packagedrawings@atmel.com ZFC B 20M2
20M2, 20-pad, 3 x 3 x 0.85 mm Body, Lead Pitch 0.45 mm,
1.55 x 1.55 mm Exposed Pad, Thermally Enhanced
Plastic Very Thin Quad Flat No Lead Package (VQFN)
10/24/08
15
14
13
12
11
1
2
3
4
5
16 17 18 19 20
10 9 8 7 6
D2
E2
e
b
L K
Pin #1 Chamfer
(C 0.3)
D
E SIDE VIEW
A1
y
Pin 1 ID
BOTTOM VIEW
TOP VIEW
A
C
C0.18 (8X)
0.3 Ref (4x)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A 0.75 0.80 0.85
A1 0.00 0.02 0.05
b 0.17 0.22 0.27
C 0.152
D 2.90 3.00 3.10
D2 1.40 1.55 1.70
E 2.90 3.00 3.10
E2 1.40 1.55 1.70
e – 0.45 –
L 0.35 0.40 0.45
K 0.20 – –
y 0.00 – 0.08 278
8183F–AVR–06/12
ATtiny24A/44A/84A
26. Errata
The revision letters in this section refer to the revision of the corresponding ATtiny24A/44A/84A
device.
26.1 ATtiny24A
26.1.1 Rev. H
No known errata.
26.1.2 Rev. G
Not sampled.
26.1.3 Rev. F
Not sampled.
26.2 ATtiny44A
26.2.1 Rev. G
No known errata. Yield improvement.
26.2.2 Rev. F
No known errata.
26.2.3 Rev. E
Not sampled.
26.3 ATtiny84A
26.3.1 Rev. C
No known errata.279
8183F–AVR–06/12
ATtiny24A/44A/84A
27. Datasheet Revision History
27.1 Rev. 8183F – 06/12
1. Updated:
– Table 16-1 on page 138
– Figure 16-7 on page 137
– “Ordering Information” on page 270
27.2 Rev. 8183E – 01/12
1. Updated:
– Production status for ATtiny24A and ATtiny84A
– “Start Condition Detector” on page 122
– “Ordering Information” on page 270, 271, and 272
27.3 Rev. 8183D – 04/11
1. Added errata for ATtiny44A rev. G in Section 26. “Errata” on page 278
27.4 Rev. 8183C – 03/11
1. Added:
– ATtiny84A, including typical characteristics plots
– Section 3.3 “Capacitive Touch Sensing” on page 6
– Table 6-8, “Capacitance of Low-Frequency Crystal Oscillator,” on page 28
– Analog Comparator Offset plots for ATtiny24A (Figure 21.2.10 on page 208) and
ATtiny44A (Figure 21.3.11 on page 236)
– Extended temperature part numbers in Section 24. “Ordering Information” on page
270
2. Updated:
– Bit syntax throughout the datasheet, e.g. from CS02:0 to CS0[2:0]
– Section 6.4 “Clock Output Buffer” on page 30, changed CLKO to CKOUT
– Table 16-4, “Single-Ended Input channel Selections,” on page 145, added note for
Internal 1.1V Reference
– Table 19-16, “High-voltage Serial Programming Instruction Set for
ATtiny24A/44A/84A,” on page 170, adjusted notes
– Table 20-1, “DC Characteristics. TA = -40°C to +85°C,” on page 173, adjusted notes
27.5 Rev. 8183B – 03/10
1. Updated template.
2. Added UFBGA package (15CC1) in: “Features” on page 1, “Pin Configurations” on
page 2, Section 24. “Ordering Information” on page 270, and Section 25.3 “15CC1” on
page 275.
3. Separated typical characteristic plots, added Section 21.2 “ATtiny24A” on page 183.
4. Updated sections:
– Section 14.5.4 “USIBR – USI Buffer Register” on page 127, header updated280
8183F–AVR–06/12
ATtiny24A/44A/84A
– Section 24. “Ordering Information” on page 270, added tape & reel and topside
marking, updated notes
5. Updated Figures:
– Figure 4-1 “Block Diagram of the AVR Architecture” on page 7
– Figure 8-1 “Reset Logic” on page 38
– Figure 14-1 “Universal Serial Interface, Block Diagram” on page 116, USIDB ->
USIBR
– Figure 19-5 “High-voltage Serial Programming Waveforms” on page 169
6. Updated Tables:
– Table 19-11, “Minimum Wait Delay Before Writing the Next Flash or EEPROM
Location,” on page 164, updated value for tWD_ERASE
27.6 Rev. 8183A – 12/08
1. Initial revision. Created from document 8006H.
2. Updated "Ordering Information" on page 278 and page 278. Pb-plated packages are no
longer offered and there are no separate ordering codes for commercial operation
range, the only available option now is industrial. Also, updated some order codes to
reflect changes in leadframe composition and added VQFN package option.
3. Updated data sheet template.
4. Removed all references to 8K device.
5. Updated characteristic plots of section “Typical Characteristics”, starting on page 182.
6. Added characteristic plots:
– “Bandgap Voltage vs. Supply Voltage” on page 233
– “Bandgap Voltage vs. Temperature” on page 233
7. Updated sections:
– “Features” on page 1
– “Power Reduction Register” on page 35
– “Analog Comparator” on page 128
– “Features” on page 132
– “Operation” on page 133
– “Starting a Conversion” on page 134
– “ADC Voltage Reference” on page 139
– “Speed” on page 174
8. Updated Figures:
– “Program Memory Map” on page 15
– “Data Memory Map” on page 16
9. Update Tables:
– “Device Signature Bytes” on page 161
– “DC Characteristics. TA = -40°C to +85°C” on page 173
– “Additional Current Consumption for the different I/O modules (absolute values)” on
page 182
– “Additional Current Consumption (percentage) in Active and Idle mode” on page 183i
8183F–AVR–06/12
ATtiny24A/44A/84A
Table of Contents
Features ..................................................................................................... 1
1 Pin Configurations ................................................................................... 2
1.1 Pin Descriptions .................................................................................................3
2 Overview ................................................................................................... 4
3 General Information ................................................................................. 6
3.1 Resources .........................................................................................................6
3.2 Code Examples .................................................................................................6
3.3 Capacitive Touch Sensing .................................................................................6
3.4 Data Retention ...................................................................................................6
3.5 Disclaimer ..........................................................................................................6
4 CPU Core .................................................................................................. 7
4.1 Architectural Overview .......................................................................................7
4.2 ALU – Arithmetic Logic Unit ...............................................................................8
4.3 Status Register ..................................................................................................8
4.4 General Purpose Register File ..........................................................................9
4.5 Stack Pointer ...................................................................................................10
4.6 Instruction Execution Timing ...........................................................................10
4.7 Reset and Interrupt Handling ...........................................................................11
4.8 Register Description ........................................................................................13
5 Memories ................................................................................................ 15
5.1 In-System Re-programmable Flash Program Memory ....................................15
5.2 SRAM Data Memory ........................................................................................15
5.3 EEPROM Data Memory ..................................................................................16
5.4 I/O Memory ......................................................................................................20
5.5 Register Description ........................................................................................20
6 Clock System ......................................................................................... 24
6.1 Clock Subsystems ...........................................................................................24
6.2 Clock Sources .................................................................................................25
6.3 System Clock Prescaler ..................................................................................30
6.4 Clock Output Buffer .........................................................................................30
6.5 Register Description ........................................................................................31
7 Power Management and Sleep Modes ................................................. 33ii
8183F–AVR–06/12
ATtiny24A/44A/84A
7.1 Sleep Modes ....................................................................................................33
7.2 Software BOD Disable .....................................................................................34
7.3 Power Reduction Register ...............................................................................35
7.4 Minimizing Power Consumption ......................................................................35
7.5 Register Description ........................................................................................36
8 System Control and Reset .................................................................... 38
8.1 Resetting the AVR ...........................................................................................38
8.2 Reset Sources .................................................................................................39
8.3 Internal Voltage Reference ..............................................................................41
8.4 Watchdog Timer ..............................................................................................41
8.5 Register Description ........................................................................................44
9 Interrupts ................................................................................................ 47
9.1 Interrupt Vectors ..............................................................................................47
9.2 External Interrupts ...........................................................................................48
9.3 Register Description ........................................................................................50
10 I/O Ports .................................................................................................. 53
10.1 Ports as General Digital I/O .............................................................................54
10.2 Alternate Port Functions ..................................................................................58
10.3 Register Description ........................................................................................66
11 8-bit Timer/Counter0 with PWM ............................................................ 68
11.1 Features ..........................................................................................................68
11.2 Overview ..........................................................................................................68
11.3 Clock Sources .................................................................................................69
11.4 Counter Unit ....................................................................................................69
11.5 Output Compare Unit .......................................................................................70
11.6 Compare Match Output Unit ............................................................................72
11.7 Modes of Operation .........................................................................................73
11.8 Timer/Counter Timing Diagrams .....................................................................77
11.9 Register Description ........................................................................................79
12 16-bit Timer/Counter1 ............................................................................ 85
12.1 Features ..........................................................................................................85
12.2 Overview ..........................................................................................................85
12.3 Timer/Counter Clock Sources .........................................................................87
12.4 Counter Unit ....................................................................................................87iii
8183F–AVR–06/12
ATtiny24A/44A/84A
12.5 Input Capture Unit ...........................................................................................88
12.6 Output Compare Units .....................................................................................90
12.7 Compare Match Output Unit ............................................................................92
12.8 Modes of Operation .........................................................................................94
12.9 Timer/Counter Timing Diagrams ...................................................................101
12.10 Accessing 16-bit Registers ............................................................................103
12.11 Register Description ......................................................................................106
13 Timer/Counter Prescaler ..................................................................... 113
13.1 Prescaler Reset .............................................................................................113
13.2 External Clock Source ...................................................................................113
13.3 Register Description ......................................................................................114
14 USI – Universal Serial Interface .......................................................... 116
14.1 Features ........................................................................................................116
14.2 Overview ........................................................................................................116
14.3 Functional Descriptions .................................................................................117
14.4 Alternative USI Usage ...................................................................................123
14.5 Register Descriptions ....................................................................................123
15 Analog Comparator ............................................................................. 128
15.1 Analog Comparator Multiplexed Input ...........................................................128
15.2 Register Description ......................................................................................129
16 Analog to Digital Converter ................................................................ 132
16.1 Features ........................................................................................................132
16.2 Overview ........................................................................................................132
16.3 Operation .......................................................................................................133
16.4 Starting a Conversion ....................................................................................134
16.5 Prescaling and Conversion Timing ................................................................135
16.6 Changing Channel or Reference Selection ...................................................138
16.7 ADC Noise Canceler .....................................................................................139
16.8 Analog Input Circuitry ....................................................................................139
16.9 Noise Canceling Techniques .........................................................................140
16.10 ADC Accuracy Definitions .............................................................................140
16.11 ADC Conversion Result .................................................................................142
16.12 Temperature Measurement ...........................................................................143
16.13 Register Description ......................................................................................144iv
8183F–AVR–06/12
ATtiny24A/44A/84A
17 debugWIRE On-chip Debug System .................................................. 150
17.1 Features ........................................................................................................150
17.2 Overview ........................................................................................................150
17.3 Physical Interface ..........................................................................................150
17.4 Software Break Points ...................................................................................151
17.5 Limitations of debugWIRE .............................................................................151
17.6 Register Description ......................................................................................151
18 Self-Programming the Flash ............................................................... 152
18.1 Performing Page Erase by SPM ....................................................................152
18.2 Filling the Temporary Buffer (Page Loading) .................................................152
18.3 Performing a Page Write ...............................................................................153
18.4 Addressing the Flash During Self-Programming ...........................................153
18.5 EEPROM Write Prevents Writing to SPMCSR ..............................................154
18.6 Reading Lock, Fuse and Signature Data from Software ...............................154
18.7 Preventing Flash Corruption ..........................................................................156
18.8 Programming Time for Flash when Using SPM ............................................156
18.9 Register Description ......................................................................................156
19 Memory Programming ......................................................................... 158
19.1 Program And Data Memory Lock Bits ...........................................................158
19.2 Fuse Bytes .....................................................................................................159
19.3 Device Signature Imprint Table .....................................................................160
19.4 Page Size ......................................................................................................161
19.5 Serial Programming .......................................................................................162
19.6 High-voltage Serial Programming ..................................................................166
19.7 High-Voltage Serial Programming Algorithm .................................................166
20 Electrical Characteristics .................................................................... 173
20.1 Absolute Maximum Ratings* .........................................................................173
20.2 DC Characteristics .........................................................................................173
20.3 Speed ............................................................................................................174
20.4 Clock Characteristics .....................................................................................175
20.5 System and Reset Characteristics ................................................................176
20.6 ADC Characteristics ......................................................................................177
20.7 Analog Comparator Characteristics ...............................................................180
20.8 Serial Programming Characteristics ..............................................................180
20.9 High-Voltage Serial Programming Characteristics ........................................181v
8183F–AVR–06/12
ATtiny24A/44A/84A
21 Typical Characteristics ........................................................................ 182
21.1 Supply Current of I/O Modules ......................................................................182
21.2 ATtiny24A ......................................................................................................183
21.3 ATtiny44A ......................................................................................................211
21.4 ATtiny84A ......................................................................................................239
22 Register Summary ............................................................................... 266
23 Instruction Set Summary .................................................................... 268
24 Ordering Information ........................................................................... 270
24.1 ATtiny24A ......................................................................................................270
24.2 ATtiny44A ......................................................................................................271
24.3 ATtiny84A ......................................................................................................272
25 Packaging Information ........................................................................ 273
25.1 14S1 ..............................................................................................................273
25.2 14P3 ..............................................................................................................274
25.3 15CC1 ...........................................................................................................275
25.4 20M1 ..............................................................................................................276
25.5 20M2 ..............................................................................................................277
26 Errata ..................................................................................................... 278
26.1 ATtiny24A ......................................................................................................278
26.2 ATtiny44A ......................................................................................................278
26.3 ATtiny84A ......................................................................................................278
27 Datasheet Revision History ................................................................ 279
27.1 Rev. 8183F – 06/12 .......................................................................................279
27.2 Rev. 8183E – 01/12 .......................................................................................279
27.3 Rev. 8183D – 04/11 .......................................................................................279
27.4 Rev. 8183C – 03/11 .......................................................................................279
27.5 Rev. 8183B – 03/10 .......................................................................................279
27.6 Rev. 8183A – 12/08 .......................................................................................2808183F–AVR–06/12
Headquarters International
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: (+1)(408) 441-0311
Fax: (+1)(408) 487-2600
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan
9F, Tonetsu Shinkawa Bldg.
1-24-8 Shinkawa
Chuo-ku, Tokyo 104-0033
JAPAN
Tel: (+81)(3) 3523-3551
Fax: (+81)(3) 3523-7581
Product Contact
Web Site
www.atmel.com
Technical Support
avr@atmel.com
Sales Contact
www.atmel.com/contacts
Literature Requests
www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any
intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND CONDITIONS
OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY
WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL
DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT
OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications
and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided
otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel’s products are not intended, authorized, or warranted for use
as components in applications intended to support or sustain life.
© 2012 Atmel Corporation. All rights reserved.
Atmel®, logo and combinations thereof, and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms
and product names may be trademarks of others.
Atmel Xplained Pro
Atmel® Xplained Pro kits provide a complete and easy to use low-cost development platform for evaluating and prototyping
your Atmel Flash-based microcontrollers (MCUs) designs.
The Xplained Pro kits offer expansion ports that allow you to connect extension boards to provide more system functionality
including OLED LCD displays, buttons, sensors and more, for fast application prototyping. You can purchase add-on boards
from Atmel, or build your own.
The new kits are part of Atmel’s complete MCU tools ecosystem, working seamlessly with Atmel Studio 6 IDP that includes
over 1600 example projects from Atmel Software Framework. When combined with Atmel Gallery, an online apps store
for development tools and embedded software, and Atmel Spaces, a cloud-based collaborative development work space,
the Xplained Pro kits further simplify your embedded MCU designs reducing your overall development time.
To learn more about Atmel Xplained Pro kits, visit http://www.atmel.com/XplainedPro
Atmel Xplained Pro kits are available from your Atmel distributor or at store.atmel.com.© 2013 Atmel Corporation. All rights reserved. / Rev.: Atmel-45024B-Xplained-Pro-Flyer_E_A5_0213
Atmel®, Atmel logo and combinations thereof, and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T : (+1)(408) 441. 0311 F : (+1)(408) 436. 4200 | www.atmel.com
Evaluation Kit Contents SAP Code Price
SAM4L Xplained Pro Evaluation Kit SAM4L MCU Board ATSAM4L-XPRO $39
SAM4S Xplained Pro Evaluation Kit SAM4S MCU Board ATSAM4S-XPRO $39
ATmega256RFR2 Xplained Pro
Evaluation Kit ATmega256RFR2 MCU Board ATMEGA256RFR2-XPRO $39
SAM4L Xplained Pro Starter Kit SAM4L MCU Board
4 Extension Boards: Segment LCD, OLED Display, I/O, Prototyping ATSAM4L-XSTK $109
SAM4S Xplained Pro Starter Kit SAM4S MCU Board
3 Extension Boards: OLED Display, I/O, Prototyping ATSAM4S-XSTK $99
RFR2 Xplained Pro Starter Kit 3 Extension Boards: OLED Display, I/O, Prototyping ATMEGA256RFR2-XSTK $99
OLED Xplained Pro Extension Extension board with 128x32 OLED Display,
3 Buttons and 3 LEDs ATOLED1-XPRO $22
Segment LCD Xplained Pro Extension Extension Board with LCD Segment Display ATSLCD1-XPRO $22
I/O Xplained Pro Extension Extension Board with Light Sensor, Temperature Sensor,
Micro SD Card, UART Loopback ATIO1-XPRO $27
Prototyping Xplained Pro Extension Prototyping Extension Board with Bread-boarding Area ATPROTO1-XPRO $18
Not recommended for new designs - Use XMEGA A1U series 8067O–AVR–06/2013
Features
High-performance, low-power Atmel® AVR® XMEGA® 8/16-bit Microcontroller
Nonvolatile program and data memories
64K - 128KBytes of in-system self-programmable flash
4K - 8KBytes boot section
2 KBBytes EEPROM
4 KB - 8 KBBytes internal SRAM
External bus interface for up to 16Mbytes SRAM
External bus interface for up to 128Mbit SDRAM
Peripheral features
Four-channel DMA controller
Eight-channel event system
Eight 16-bit timer/counters
Four timer/counters with 4 output compare or input capture channels
Four timer/counters with 2 output compare or input capture channels
High resolution extension on all timer/counters
Advanced waveform extension (AWeX) on two timer/counters
Eight USARTs with IrDA support for one USART
Four two-wire interfaces with dual address match (I2
C and SMBus compatible)
Four serial peripheral interfaces (SPIs)
AES and DES crypto engine
16-bit real time counter (RTC) with separate oscillator
Two sixteen channel, 12-bit, 2msps Analog to Digital Converters
Two two-channel, 12-bit, 1msps Digital to Analog Converters
Four Analog Comparators (ACs) with window compare function, and current sources
External interrupts on all general purpose I/O pins
Programmable watchdog timer with separate on-chip ultra low power oscillator
QTouch® library support
Capacitive touch buttons, sliders and wheels
Special microcontroller features
Power-on reset and programmable brown-out detection
Internal and external clock options with PLL and prescaler
Programmable multilevel interrupt controller
Five sleep modes
Programming and debug interfaces
JTAG (IEEE 1149.1 compliant) interface, including boundary scan
PDI (Program and Debug Interface)
I/O and packages
78 Programmable I/O pins
100 lead TQFP
100 ball BGA
100 ball VFBGA
Operating voltage
1.6 – 3.6V
Operating frequency
0 – 12MHz from 1.6V
0 – 32MHz from 2.7V
8/16-bit XMEGA A1 Microcontroller
ATxmega128A1 / ATxmega64A1
Preliminary
8067O–AVR–06/2013
Not recommended for new designs -
Use XMEGA A1U series[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 2
8067O–AVR–06/2013
‘
1. Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information.
2. Pb-free packaging, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive). Also Halide free and fully Green.
3. For packaging information, see “Packaging information” on page 70.
Typical Applications
Ordering Code Flash (B) E2 SRAM Speed (MHz) Power Supply Package(1)(2)(3) Temp
ATxmega128A1-AU
128K + 8K 2 KB 8 KB
32 1.6 - 3.6V
100A
-40C - 85C
ATxmega128A1-AUR
ATxmega64A1-AU
64K + 4K 2 KB 4 KB
ATxmega64A1-AUR
ATxmega128A1-CU
128K + 8K 2 KB 8 KB
100C1
ATxmega128A1CUR
ATxmega64A1-CU
64K + 4K 2 KB 4 KB
ATxmega64A1-CUR
ATxmega128A1-C7U
128K + 8K 2 KB 8 KB
100C2
ATxmega128A1-C7UR
ATxmega64A1-C7U
64K + 4K 2 KB 4 KB
ATxmega64A1-C7UR
Package Type
100A 100-lead, 14 x 14 x 1.0mm, 0.5mm lead pitch, thin profile plastic quad flat package (TQFP)
100C1 100-ball, 9 x 9 x 1.2mm body, ball pitch 0.88mm, chip ball grid array (CBGA)
100C2 100-ball, 7 x 7 x 1.0mm body, ball pitch 0.65mm, very thin fine-pitch ball grid array (VFBGA)
Industrial control Climate control Low power battery applications
Factory automation RF and ZigBee® Power tools
Building control Sensor control HVAC
Board control Optical Utility metering
White goods Medical applications[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 3
8067O–AVR–06/2013
2. Pinout/Block Diagram
Figure 2-1. Block diagram and pinout
Notes: 1. For full details on pinout and pin functions refer to “Pinout and Pin Functions” on page 55.
2. VCC/GND on pin 83/84 are swapped compared to other VCC/GND to allow easier routing of GND to 32kHz crystal.
INDEX CORNER
PA6
PA7
GND
AVCC
PB0
PB1
PB2
PB3
PB4
PB5
PB6
PB7
GND
VCC
PC0
PC1
PC2
PC3
PC4
PC5
PC6
PC7
GND
VCC
PD0
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
100
99
98
97
96
95
94
93
92
91
90
89
88
87
86
85
84
83
82
81
80
79
78
77
76
75
74
73
72
71
70
69
68
67
66
65
64
63
62
61
60
59
58
57
56
55
54
53
52
51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PD1
PD2
PD3
PD4
PD5
PD6
PD7
GND
VCC
PE0
PE1
PE2
PE3
PE4
PE5
PE6
PE7
GND
VCC
PF0
PF1
PF2
PF3
PF4
PF5
PK0
VCC
GND
PJ7
PJ6
PJ5
PJ4
PJ3
PJ2
PJ1
PJ0
VCC
GND
PH7
PH6
PH5
PH4
PH3
PH2
PH1
PH0
VCC
GND
PF7
PF6
PA5
PA4
PA3
PA2
PA1
PA0
AVCC
GND
PR1
PR0
RESET/PDI
PDI
PQ3
PQ2
PQ1
PQ0
GND
VCC
PK7
PK6
PK5
PK4
PK3
PK2
PK1
FLASH
RAM
E 2PROM DMA
Interrupt Controlle r
OCD
External Bus Interface
ADC A
ADC B
DAC B
DAC A
AC A0
AC A1
AC B0
AC B1
Port
A Port B
Event System ctrl
Port K
Port J
Port H
Port R Port Q
Power
Contro l
Reset
Contro l
Watchdog
OSC/CLK
Contro l BOD POR
RTC
EVENT ROUTING NETWORK
DATA BU S
DATA BU S
VREF
TEMP
Port C
CPU
T/C0:1
USART0:1
TWI
SPI
Port D Port E Port F
T/C0:1
USART0/1
TWI
SPI
T/C0:1
USART0:1
TWI
SPI
T/C0:1
USART0:1
TWI
SPI[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 4
8067O–AVR–06/2013
Figure 2-2. CBGA-pinout
Table 2-1. CBGA-pinout.
1 2 3 4 5 6 7 8 9 10
A PK0 VCC GND PJ3 VCC GND PH1 GND VCC PF7
B PK3 PK2 PK1 PJ4 PH7 PH4 PH2 PH0 PF6 PF5
C VCC PK5 PK4 PJ5 PJ0 PH5 PH3 PF2 PF3 VCC
D GND PK6 PK7 PJ6 PJ1 PH6 PF0 PF1 PF4 GND
E PQ0 PQ1 PQ2 PJ7 PJ2 PE7 PE6 PE5 PE4 PE3
F PR1 PR0 RESET/
PDI PDI PQ3 PC2 PE2 PE1 PE0 VCC
G GND PA1 PA4 PB3 PB4 PC1 PC6 PD7 PD6 GND
H AVCC PA2 PA5 PB2 PB5 PC0 PC5 PD5 PD4 PD3
J PA0 PA3 PB0 PB1 PB6 PC3 PC4 PC7 PD2 PD1
K PA6 PA7 GND AVCC PB7 VCC GND VCC GND PD0
A
B
C
D
E
F
G
H
J
K
1 2 3 4 5 6 7 8 9 10
A
B
C
D
E
F
G
H
J
K
10 9 8 7 6 5 4 3 2 1
Top view Bottom view[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 5
8067O–AVR–06/2013
3. Overview
The Atmel AVR XMEGA is a family of low power, high performance, and peripheral rich 8/16-bit microcontrollers based
on the AVR enhanced RISC architecture. By executing instructions in a single clock cycle, the AVR XMEGA devices
achieve CPU throughput approaching one million instructions per second (MIPS) per megahertz, allowing the system
designer to optimize power consumption versus processing speed.
The Atmel AVR CPU combines a rich instruction set with 32 general purpose working registers. All 32 registers are
directly connected to the arithmetic logic unit (ALU), allowing two independent registers to be accessed in a single
instruction, executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs
many times faster than conventional single-accumulator or CISC based microcontrollers.
The AVR XMEGA A1 devices provide the following features: in-system programmable flash with read-while-write
capabilities; internal EEPROM and SRAM; four-channel DMA controller, eight-channel event system and programmable
multilevel interrupt controller, 78 general purpose I/O lines, 16-bit real-time counter (RTC); eight flexible, 16-bit
timer/counters with compare and PWM channels, eight USARTs; four two-wire serial interfaces (TWIs); four serial
peripheral interfaces (SPIs); AES and DES cryptographic engine; two 16-channel, 12-bit ADCs with programmable gain;
two 2-channel, 12-bit DACs; four Analog Comparators (ACs) with window mode; programmable watchdog timer with
separate internal oscillator; accurate internal oscillators with PLL and prescaler; and programmable brown-out detection.
The program and debug interface (PDI), a fast, two-pin interface for programming and debugging, is available. The
devices also have an IEEE std. 1149.1 compliant JTAG interface, and this can also be used for boundary scan, on-chip
debug and programming.
The XMEGA A1 devices have five software selectable power saving modes. The idle mode stops the CPU while allowing
the SRAM, DMA controller, event system, interrupt controller, and all peripherals to continue functioning. The powerdown
mode saves the SRAM and register contents, but stops the oscillators, disabling all other functions until the next
TWI or pin-change interrupt, or reset. In power-save mode, the asynchronous real-time counter continues to run, allowing
the application to maintain a timer base while the rest of the device is sleeping. In standby mode, the external crystal
oscillator keeps running while the rest of the device is sleeping. This allows very fast startup from the external crystal,
combined with low power consumption. In extended standby mode, both the main oscillator and the asynchronous timer
continue to run. To further reduce power consumption, the peripheral clock to each individual peripheral can optionally be
stopped in active mode and idle sleep mode.
Atmel offers a free QTouch library for embedding capacitive touch buttons, sliders and wheels functionality into AVR
microcontrollers.
The device are manufactured using Atmel high-density, nonvolatile memory technology. The program flash memory can
be reprogrammed in-system through the PDI or JTAG interfaces. A boot loader running in the device can use any
interface to download the application program to the flash memory. The boot loader software in the boot flash section will
continue to run while the application flash section is updated, providing true read-while-write operation. By combining an
8/16-bit RISC CPU with in-system, self-programmable flash, the AVR XMEGA is a powerful microcontroller family that
provides a highly flexible and cost effective solution for many embedded applications.
All Atmel AVR XMEGA devices are supported with a full suite of program and system development tools, including C
compilers, macro assemblers, program debugger/simulators, programmers, and evaluation kits.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 6
8067O–AVR–06/2013
3.1 Block Diagram
Figure 3-1. XMEGA A1 Block Diagram
VBAT
Power
Supervision
Battery Backup
Controller
Real Time
Counter
32.768 kHz
XOSC
Power
Supervision
POR/BOD &
RESET PORT A (8)
PORT B (8)
EVENT ROUTING NETWORK
DMA
Controller
BUS
Matrix
SRAM
EBI
ADCA
DACA
ACA
DACB
ADCB
ACB
OCD
PORT K (8)
PORT J (8)
PORT H (8)
PDI
Watchdog
Timer
Watchdog
Oscillator
Interrupt
Controller
DATA BUS
Prog/Debug
Controller
PORT R (2)
Oscillator
Circuits/
Clock
Generation
Oscillator
Control
Real Time
Counter
Event System
Controller
JTAG
Sleep
Controller
DES
IRCOM
PORT G (8)
PORT L (8)
PORT Q (8)
PORT M (8)
PORT C (8) TCC0:1 USARTC0:1 SPIC
TWIC
PORT D (8) TCD0:1 USARTD0:1 SPID
TWID
TCF0:1
USARTF0:1
SPIF
TWIF
TCE0:1
USARTE0:1
SPIE
TWIE
PORT E (8) PORT F (8)
EVENT ROUTING NETWORK
AES
AREFA
AREFB
PORT N (8)
PORT P (8)
CPU
NVM Controller
Flash EEPROM
DATA BUS
Int. Refs.
Tempref
Digital function
Analog function
Bus masters / Programming / Debug
Oscillator / Crystal / Clock
General Purpose I/O
EBI[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 7
8067O–AVR–06/2013
4. Resources
A comprehensive set of development tools, application notes and datasheets are available for download on
http://www.atmel.com/avr.
4.1 Recommended reading
XMEGA A Manual
XMEGA A Application Notes
This device data sheet only contains part specific information and a short description of each peripheral and module. The
XMEGA A Manual describes the modules and peripherals in depth. The XMEGA A application notes contain example
code and show applied use of the modules and peripherals.
The XMEGA A Manual and Application Notes are available from http://www.atmel.com/avr.
5. Capacitive touch sensing
The Atmel QTouch library provides a simple to use solution to realize touch sensitive interfaces on most Atmel AVR
microcontrollers. The patented charge-transfer signal acquisition offers robust sensing and includes fully debounced
reporting of touch keys and includes Adjacent Key Suppression® (AKS®) technology for unambiguous detection of key
events. The QTouch library includes support for the QTouch and QMatrix acquisition methods.
Touch sensing can be added to any application by linking the appropriate Atmel QTouch library for the AVR
microcontroller. This is done by using a simple set of APIs to define the touch channels and sensors, and then calling the
touch sensing API’s to retrieve the channel information and determine the touch sensor states.
The QTouch library is FREE and downloadable from the Atmel website at the following location:
www.atmel.com/qtouchlibrary. For implementation details and other information, refer to the QTouch library user guide -
also available for download from the Atmel website.
6. Disclaimer
For devices that are not available yet, typical values contained in this datasheet are based on simulations and
characterization of other AVR XMEGA microcontrollers manufactured on the same process technology. Min. and Max
values will be available after the device is characterized.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 8
8067O–AVR–06/2013
7. AVR CPU
7.1 Features
8/16-bit high performance AVR RISC Architecture
138 instructions
Hardware multiplier
32x8-bit registers directly connected to the ALU
Stack in SRAM
Stack Pointer accessible in I/O memory space
Direct addressing of up to 16M Bytes of program and data memory
True 16/24-bit access to 16/24-bit I/O registers
Support for 8-, 16- and 32-bit Arithmetic
Configuration Change Protection of system critical features
7.2 Overview
All Atmel AVR XMEGA devices use the 8/16-bit AVR CPU. The main function of the CPU is to execute the code and
perform all calculations. The CPU is able to access memories, perform calculations, control peripherals, and execute the
program in the flash memory. Interrupt handling is described in a separate section, refer to “Interrupts and Programmable
Multilevel Interrupt Controller” on page 29.
7.3 Architectural Overview
In order to maximize performance and parallelism, the AVR CPU uses a Harvard architecture with separate memories
and buses for program and data. Instructions in the program memory are executed with single-level pipelining. While one
instruction is being executed, the next instruction is pre-fetched from the program memory. This enables instructions to
be executed on every clock cycle. For details of all AVR instructions, refer to http://www.atmel.com/avr.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 9
8067O–AVR–06/2013
Figure 7-1. Block diagram of the AVR CPU architecture.
The arithmetic logic unit (ALU) supports arithmetic and logic operations between registers or between a constant and a
register. Single-register operations can also be executed in the ALU. After an arithmetic operation, the status register is
updated to reflect information about the result of the operation.
The ALU is directly connected to the fast-access register file. The 32 x 8-bit general purpose working registers all have
single clock cycle access time allowing single-cycle arithmetic logic unit (ALU) operation between registers or between a
register and an immediate. Six of the 32 registers can be used as three 16-bit address pointers for program and data
space addressing, enabling efficient address calculations.
The memory spaces are linear. The data memory space and the program memory space are two different memory
spaces.
The data memory space is divided into I/O registers, SRAM, and external RAM. In addition, the EEPROM can be
memory mapped in the data memory.
All I/O status and control registers reside in the lowest 4KB addresses of the data memory. This is referred to as the I/O
memory space. The lowest 64 addresses can be accessed directly, or as the data space locations from 0x00 to 0x3F.
The rest is the extended I/O memory space, ranging from 0x0040 to 0x0FFF. I/O registers here must be accessed as
data space locations using load (LD/LDS/LDD) and store (ST/STS/STD) instructions.
The SRAM holds data. Code execution from SRAM is not supported. It can easily be accessed through the five different
addressing modes supported in the AVR architecture. The first SRAM address is 0x2000.
Data addresses 0x1000 to 0x1FFF are reserved for memory mapping of EEPROM.
The program memory is divided in two sections, the application program section and the boot program section. Both
sections have dedicated lock bits for write and read/write protection. The SPM instruction that is used for selfprogramming
of the application flash memory must reside in the boot program section. The application section contains
an application table section with separate lock bits for write and read/write protection. The application table section can
be used for safe storing of nonvolatile data in the program memory.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 10
8067O–AVR–06/2013
7.4 ALU - Arithmetic Logic Unit
The arithmetic logic unit (ALU) supports arithmetic and logic operations between registers or between a constant and a
register. Single-register operations can also be executed. The ALU operates in direct connection with all 32 general
purpose registers. In a single clock cycle, arithmetic operations between general purpose registers or between a register
and an immediate are executed and the result is stored in the register file. After an arithmetic or logic operation, the
status register is updated to reflect information about the result of the operation.
ALU operations are divided into three main categories – arithmetic, logical, and bit functions. Both 8- and 16-bit
arithmetic is supported, and the instruction set allows for efficient implementation of 32-bit aritmetic. The hardware
multiplier supports signed and unsigned multiplication and fractional format.
7.4.1 Hardware Multiplier
The multiplier is capable of multiplying two 8-bit numbers into a 16-bit result. The hardware multiplier supports different
variations of signed and unsigned integer and fractional numbers:
Multiplication of unsigned integers
Multiplication of signed integers
Multiplication of a signed integer with an unsigned integer
Multiplication of unsigned fractional numbers
Multiplication of signed fractional numbers
Multiplication of a signed fractional number with an unsigned one
A multiplication takes two CPU clock cycles.
7.5 Program Flow
After reset, the CPU starts to execute instructions from the lowest address in the flash program memory ‘0.’ The program
counter (PC) addresses the next instruction to be fetched.
Program flow is provided by conditional and unconditional jump and call instructions capable of addressing the whole
address space directly. Most AVR instructions use a 16-bit word format, while a limited number use a 32-bit format.
During interrupts and subroutine calls, the return address PC is stored on the stack. The stack is allocated in the general
data SRAM, and consequently the stack size is only limited by the total SRAM size and the usage of the SRAM. After
reset, the stack pointer (SP) points to the highest address in the internal SRAM. The SP is read/write accessible in the
I/O memory space, enabling easy implementation of multiple stacks or stack areas. The data SRAM can easily be
accessed through the five different addressing modes supported in the AVR CPU.
7.6 Status Register
The status register (SREG) contains information about the result of the most recently executed arithmetic or logic
instruction. This information can be used for altering program flow in order to perform conditional operations. Note that
the status register is updated after all ALU operations, as specified in the instruction set reference. This will in many
cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code.
The status register is not automatically stored when entering an interrupt routine nor restored when returning from an
interrupt. This must be handled by software.
The status register is accessible in the I/O memory space.
7.6.1 Stack and Stack Pointer
The stack is used for storing return addresses after interrupts and subroutine calls. It can also be used for storing
temporary data. The stack pointer (SP) register always points to the top of the stack. It is implemented as two 8-bit
registers that are accessible in the I/O memory space. Data are pushed and popped from the stack using the PUSH and
POP instructions. The stack grows from a higher memory location to a lower memory location. This implies that pushing
data onto the stack decreases the SP, and popping data off the stack increases the SP. The SP is automatically loaded [Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 11
8067O–AVR–06/2013
after reset, and the initial value is the highest address of the internal SRAM. If the SP is changed, it must be set to point
above address 0x2000, and it must be defined before any subroutine calls are executed or before interrupts are enabled.
During interrupts or subroutine calls, the return address is automatically pushed on the stack. The return address can be
two or three bytes, depending on program memory size of the device. For devices with 128KB or less of program
memory, the return address is two bytes, and hence the stack pointer is decremented/incremented by two. For devices
with more than 128KB of program memory, the return address is three bytes, and hence the SP is
decremented/incremented by three. The return address is popped off the stack when returning from interrupts using the
RETI instruction, and from subroutine calls using the RET instruction.
The SP is decremented by one when data are pushed on the stack with the PUSH instruction, and incremented by one
when data is popped off the stack using the POP instruction.
To prevent corruption when updating the stack pointer from software, a write to SPL will automatically disable interrupts
for up to four instructions or until the next I/O memory write.
After reset the stack pointer is initialized to the highest address of the SRAM. See Table 8-2 on page 15.
7.7 Register File
The register file consists of 32 x 8-bit general purpose working registers with single clock cycle access time. The register
file supports the following input/output schemes:
One 8-bit output operand and one 8-bit result input
Two 8-bit output operands and one 8-bit result input
Two 8-bit output operands and one 16-bit result input
One 16-bit output operand and one 16-bit result input
Six of the 32 registers can be used as three 16-bit address register pointers for data space addressing, enabling efficient
address calculations. One of these address pointers can also be used as an address pointer for lookup tables in flash
program memory.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 12
8067O–AVR–06/2013
8. Memories
8.1 Features
Flash Program Memory
One linear address space
In-System Programmable
Self-Programming and Bootloader support
Application Section for application code
Application Table Section for application code or data storage
Boot Section for application code or bootloader code
Separate lock bits and protection for all sections
Built in fast CRC check of a selectable flash program memory section
Data Memory
One linear address space
Single cycle access from CPU
SRAM
EEPROM
Byte and page accessible
Optional memory mapping for direct load and store
I/O Memory
Configuration and Status registers for all peripherals and modules
16 bit-accessible General Purpose Register for global variables or flags
External Memory support
SRAM
SDRAM
Memory mapped external hardware
Bus arbitration
Safe and deterministic handling of CPU and DMA Controller priority
Separate buses for SRAM, EEPROM, I/O Memory and External Memory access
Simultaneous bus access for CPU and DMA Controller
Production Signature Row Memory for factory programmed data
Device ID for each microcontroller device type
Serial number for each device
Oscillator calibration bytes
ADC, DAC and temperature sensor calibration data
User Signature Row
One flash page in size
Can be read and written from software
Content is kept after chip erase
8.2 Overview
The Atmel AVR architecture has two main memory spaces, the program memory and the data memory. Executable code
can reside only in the program memory, while data can be stored in the program memory and the data memory. The data
memory includes the internal SRAM, and EEPROM for nonvolatile data storage. All memory spaces are linear and
require no memory bank switching. Nonvolatile memory (NVM) spaces can be locked for further write and read/write
operations. This prevents unrestricted access to the application software.
A separate memory section contains the fuse bytes. These are used for configuring important system functions, and can
only be written by an external programmer.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 13
8067O–AVR–06/2013
The available memory size configurations are shown in “Ordering Information” on page 2. In addition each device has a
flash memory signature rows for calibration data, device identification, serial number etc.
8.3 In-System Programmable Flash Program Memory
he Atmel AVR XMEGA devices contain on-chip, in-system reprogrammable flash memory for program storage. The flash
memory can be accessed for read and write from an external programmer through the PDI or from application software
running in the device.
All AVR CPU instructions are 16 or 32 bits wide, and each flash location is 16 bits wide. The flash memory is organized
in two main sections, the application section and the boot loader section. The sizes of the different sections are fixed, but
device-dependent. These two sections have separate lock bits, and can have different levels of protection. The store
program memory (SPM) instruction, which is used to write to the flash from the application software, will only operate
when executed from the boot loader section.
The application section contains an application table section with separate lock settings. This enables safe storage of
nonvolatile data in the program memory.
Figure 8-1. Flash Program Memory (Hexadecimal address)
8.3.1 Application Section
The Application section is the section of the flash that is used for storing the executable application code. The protection
level for the application section can be selected by the boot lock bits for this section. The application section can not store
any boot loader code since the SPM instruction cannot be executed from the application section.
8.3.2 Application Table Section
The application table section is a part of the application section of the flash memory that can be used for storing data.
The size is identical to the boot loader section. The protection level for the application table section can be selected by
the boot lock bits for this section. The possibilities for different protection levels on the application section and the
application table section enable safe parameter storage in the program memory. If this section is not used for data,
application code can reside here.
8.3.3 Boot Loader Section
While the application section is used for storing the application code, the boot loader software must be located in the boot
loader section because the SPM instruction can only initiate programming when executing from this section. The SPM
instruction can access the entire flash, including the boot loader section itself. The protection level for the boot loader
section can be selected by the boot loader lock bits. If this section is not used for boot loader software, application code
can be stored here.
Word Address
ATxega128A1 ATxmega64A1
0 0 Application Section (Bytes)
(128K/64K)
...
EFFF / 77FF
F000 / 7800 Application Table Section (Bytes)
FFFF / 7FFF (8K/4K)
10000 / 8000 Boot Section (Bytes)
10FFF / 87FF (8K/4K)[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 14
8067O–AVR–06/2013
8.3.4 Production Signature Row
The production signature row is a separate memory section for factory programmed data. It contains calibration data for
functions such as oscillators and analog modules. Some of the calibration values will be automatically loaded to the
corresponding module or peripheral unit during reset. Other values must be loaded from the signature row and written to
the corresponding peripheral registers from software. For details on calibration conditions, refer to “Electrical
Characteristics” on page 76.
The production signature row also contains an ID that identifies each microcontroller device type and a serial number for
each manufactured device. The serial number consists of the production lot number, wafer number, and wafer
coordinates for the device. The device ID for the available devices is shown in Table 8-1.
The production signature row cannot be written or erased, but it can be read from application software and external
programmers.
Table 8-1. Device ID bytes.
8.3.5 User Signature Row
The user signature row is a separate memory section that is fully accessible (read and write) from application software
and external programmers. It is one flash page in size, and is meant for static user parameter storage, such as calibration
data, custom serial number, identification numbers, random number seeds, etc. This section is not erased by chip erase
commands that erase the flash, and requires a dedicated erase command. This ensures parameter storage during
multiple program/erase operations and on-chip debug sessions.
8.4 Fuses and Lock bits
The fuses are used to configure important system functions, and can only be written from an external programmer. The
application software can read the fuses. The fuses are used to configure reset sources such as brownout detector and
watchdog, startup configuration, JTAG enable, and JTAG user ID.
The lock bits are used to set protection levels for the different flash sections (that is, if read and/or write access should be
blocked). Lock bits can be written by external programmers and application software, but only to stricter protection levels.
Chip erase is the only way to erase the lock bits. To ensure that flash contents are protected even during chip erase, the
lock bits are erased after the rest of the flash memory has been erased.
An unprogrammed fuse or lock bit will have the value one, while a programmed fuse or lock bit will have the value zero.
Both fuses and lock bits are reprogrammable like the flash program memory.
8.5 Data Memory
The data memory contains the I/O memory, internal SRAM, optionally memory mapped EEPROM, and external memory
if available. The data memory is organized as one continuous memory section, see Figure 8-2 on page 15. To simplify
development, I/O Memory, EEPROM and SRAM will always have the same start addresses for all Atmel AVR XMEGA
devices. The address space for External Memory will always start at the end of Internal SRAM and end at address
0xFFFFFF.
Device Device ID bytes
Byte 2 Byte 1 Byte 0
ATxmega64A1 4E 96 1E
ATxmega128A1 4C 97 1E[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 15
8067O–AVR–06/2013
Figure 8-2. Data Memory Map (Hexadecimal address)
8.6 EEPROM
XMEGA AU devices have EEPROM for nonvolatile data storage. It is either addressable in a separate data space
(default) or memory mapped and accessed in normal data space. The EEPROM supports both byte and page access.
Memory mapped EEPROM allows highly efficient EEPROM reading and EEPROM buffer loading. When doing this,
EEPROM is accessible using load and store instructions. Memory mapped EEPROM will always start at hexadecimal
address 0x1000.
8.7 I/O Memory
The status and configuration registers for peripherals and modules, including the CPU, are addressable through I/O
memory locations. All I/O locations can be accessed by the load (LD/LDS/LDD) and store (ST/STS/STD) instructions,
which is used to transfer data between the 32 registers in the register file and the I/O memory. The IN and OUT
instructions can address I/O memory locations in the range 0x00 - 0x3F directly. In the address range 0x00 - 0x1F,
single- cycle instructions for manipulation and checking of individual bits are available.
The I/O memory address for all peripherals and modules in XMEGA A1U is shown in the “Peripheral Module Address
Map” on page 62.
8.7.1 General Purpose I/O Registers
The lowest 16 I/O memory addresses are reserved as general purpose I/O registers. These registers can be used for
storing global variables and flags, as they are directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
8.8 External Memory
Four ports can be used for external memory, supporting external SRAM, SDRAM, and memory mapped peripherals such
as LCD displays. Refer to “EBI – External Bus Interface” on page 47. The external memory address space will always
start at the end of internal SRAM.
8.9 Data Memory and Bus Arbitration
Since the data memory is organized as four separate sets of memories, the different bus masters (CPU, DMA controller
read and DMA controller write, etc.) can access different memory sections at the same time.
Byte Address ATxmega128A1 Byte Address ATxmega64A1
0 I/O Registers
(4 KB)
0 I/O Registers
FFF FFF (4 KB)
1000 EEPROM
(2 KB)
1000 EEPROM
17FF 17FF (2 KB)
RESERVED RESERVED
2000 Internal SRAM
(8 KB)
2000 Internal SRAM
3FFF 2FFF (4 KB)
4000 External Memory
(0 to 16 MB)
3000 External Memory
FFFFFF FFFFFF (0 to 16 MB)[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 16
8067O–AVR–06/2013
8.10 Memory Timing
Read and write access to the I/O memory takes one CPU clock cycle. A write to SRAM takes one cycle, and a read from
SRAM takes two cycles. For burst read (DMA), new data are available every cycle. EEPROM page load (write) takes one
cycle, and three cycles are required for read. For burst read, new data are available every second cycle. External
memory has multi-cycle read and write. The number of cycles depends on the type of memory and configuration of the
external bus interface. Refer to the instruction summary for more details on instructions and instruction timing.
8.11 Device ID and Revision
Each device has a three-byte device ID. This ID identifies Atmel as the manufacturer of the device and the device type. A
separate register contains the revision number of the device.
8.12 I/O Memory Protection
Some features in the device are regarded as critical for safety in some applications. Due to this, it is possible to lock the
I/O register related to the clock system, the event system, and the advanced waveform extensions. As long as the lock is
enabled, all related I/O registers are locked and they can not be written from the application software. The lock registers
themselves are protected by the configuration change protection mechanism.
8.13 JTAG Disable
It is possible to disable the JTAG interface from the application software. This will prevent all external JTAG access to the
device until the next device reset or until JTAG is enabled again from the application software. As long as JTAG is
disabled, the I/O pins required for JTAG can be used as normal I/O pins.
8.14 Flash and EEPROM Page Size
The flash program memory and EEPROM data memory are organized in pages. The pages are word accessible for the
flash and byte accessible for the EEPROM.
Table 8-2 shows the Flash Program Memory organization. Flash write and erase operations are performed on one page
at a time, while reading the Flash is done one byte at a time. For Flash access the Z-pointer (Z[m:n]) is used for
addressing. The most significant bits in the address (FPAGE) gives the page number and the least significant address
bits (FWORD) gives the word in the page.
Table 8-2. Number of words and Pages in the Flash.
Table 8-3 shows EEPROM memory organization for the Atmel AVR XMEGA A1U devices. EEPROM write and erase
operations can be performed one page or one byte at a time, while reading the EEPROM is done one byte at a time. For
EEPROM access the NVM Address Register (ADDR[m:n]) is used for addressing. The most significant bits in the
address (E2PAGE) give the page number and the least significant address bits (E2BYTE) give the byte in the page.
Device PC size Flash
Page
Size FWORD FPAGE Application Boot
bits bytes words Size No of
pages
Size No of
pages
ATxmega64A1 16 64K + 4K 128 Z[7:1] Z[16:8] 64K 256 4K 16
ATxmega128A1 17 128K+ 8K 256 Z[8:1] Z[17:9] 128K 256 8K 16[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 17
8067O–AVR–06/2013
Table 8-3. Number of Bytes and Pages in the EEPROM.
8.14.1 I/O Memory
All peripherals and modules are addressable through I/O memory locations in the data memory space. All I/O memory
locations can be accessed by the Load (LD/LDS/LDD) and Store (ST/STS/STD) instructions, transferring data between
the 32 general purpose registers in the CPU and the I/O Memory.
The IN and OUT instructions can address I/O memory locations in the range 0x00 - 0x3F directly.
I/O registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. The
value of single bits can be checked by using the SBIS and SBIC instructions on these registers.
The I/O memory address for all peripherals and modules in XMEGA A1 is shown in the “Peripheral Module Address Map”
on page 62.
Device EEPROM Page Size E2BYTE E2PAGE No of pages
Size bytes
ATxmega64A1 2 KB 32 ADDR[4:0] ADDR[10:5] 64
ATxmega128A1 2 KB 32 ADDR[4:0 ADDR[10:5] 64[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 18
8067O–AVR–06/2013
9. DMAC - Direct Memory Access Controller
9.1 Features
Allows High-speed data transfer
From memory to peripheral
From memory to memory
From peripheral to memory
From peripheral to peripheral
4 Channels
From 1 byte and up to 16M bytes transfers in a single transaction
Multiple addressing modes for source and destination address
Increment
Decrement
Static
1, 2, 4, or 8 byte Burst Transfers
Programmable priority between channels
9.2 Overview
The four-channel direct memory access (DMA) controller can transfer data between memories and peripherals, and thus
offload these tasks from the CPU. It enables high data transfer rates with minimum CPU intervention, and frees up CPU
time. The four DMA channels enable up to four independent and parallel transfers.
The DMA controller can move data between SRAM and peripherals, between SRAM locations and directly between
peripheral registers. With access to all peripherals, the DMA controller can handle automatic transfer of data to/from
communication modules. The DMA controller can also read from memory mapped EEPROM.
Data transfers are done in continuous bursts of 1, 2, 4, or 8 bytes. They build block transfers of configurable size from 1
byte to 64KB. A repeat counter can be used to repeat each block transfer for single transactions up to 16MB. Source and
destination addressing can be static, incremental or decremental. Automatic reload of source and/or destination
addresses can be done after each burst or block transfer, or when a transaction is complete. Application software,
peripherals, and events can trigger DMA transfers.
The four DMA channels have individual configuration and control settings. This include source, destination, transfer
triggers, and transaction sizes. They have individual interrupt settings. Interrupt requests can be generated when a
transaction is complete or when the DMA controller detects an error on a DMA channel.
To allow for continuous transfers, two channels can be interlinked so that the second takes over the transfer when the
first is finished, and vice versa.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 19
8067O–AVR–06/2013
10. Event System
10.1 Features
Inter-peripheral communication and signalling with minimum latency
CPU and DMA independent operation
8 Event Channels allows for up to 8 signals to be routed at the same time
Events can be generated by
Timer/Counters (TCxn)
Real Time Counter (RTC)
Analog to Digital Converters (ADCx)
Analog Comparators (ACx)
Ports (PORTx)
System Clock (ClkSYS)
Software (CPU)
Events can be used by
Timer/Counters (TCxn)
Analog to Digital Converters (ADCx)
Digital to Analog Converters (DACx)
Ports (PORTx)
DMA Controller (DMAC)
IR Communication Module (IRCOM)
The same event can be used by multiple peripherals for synchronized timing
Advanced Features
Manual Event Generation from software (CPU)
Quadrature Decoding
Digital Filtering
Functions in Active and Idle mode
10.2 Overview
The Event System is a set of features for inter-peripheral communication. It enables the possibility for a change of state
in one peripheral to automatically trigger actions in one or more peripherals. These changes in a peripheral that will
trigger actions in other peripherals are configurable by software. It is a simple, but powerful system as it allows for
autonomous control of peripherals without any use of interrupts, CPU or DMA resources.
The indication of a change in a peripheral is referred to as an event, and is usually the same as the interrupt conditions
for that peripheral. Events are passed between peripherals using a dedicated routing network called the Event Routing
Network. Figure 10-1 on page 20 shows a basic block diagram of the Event System with the Event Routing Network and
the peripherals to which it is connected. This highly flexible system can be used for simple routing of signals, pin
functions or for sequencing of events.
The maximum latency is two CPU clock cycles from when an event is generated in one peripheral, until the actions are
triggered in one or more other peripherals.
The Event System is functional in both Active and Idle modes.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 20
8067O–AVR–06/2013
Figure 10-1. Event system block diagram.
he event routing network consists of eight software-configurable multiplexers that control how events are routed and
used. These are called event channels, and allow for up to eight parallel event routing configurations. The maximum
routing latency is two peripheral clock cycles. The event system works in both active mode and idle sleep mode.
DAC Timer /
Counters
ADC
Real Time
Counter
Port pins
CPU /
Software
DMA
Controller
IRCOM
Event Routing Network
Event
System
Controller
clkPER
Prescaler
AC[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 21
8067O–AVR–06/2013
11. System Clock and Clock options
11.1 Features
Fast start-up time
Safe run-time clock switching
Internal Oscillators:
32 MHz run-time calibrated RC oscillator
2 MHz run-time calibrated RC oscillator
32.768 kHz calibrated RC oscillator
32 kHz Ultra Low Power (ULP) oscillator with 1 kHz ouput
External clock options
0.4 - 16 MHz Crystal Oscillator
32 kHz Crystal Oscillator
External clock
PLL with internal and external clock options with 1 to 31x multiplication
Clock Prescalers with 1x to 2048x division
Fast peripheral clock running at two and four times the CPU clock speed
Automatic Run-Time Calibration of internal oscillators
Crystal Oscillator failure detection
11.2 Overview
Atmel AVR XMEGA devices have a flexible clock system supporting a large number of clock sources. It incorporates
both accurate internal oscillators and external crystal oscillator and resonator support. A high-frequency phase locked
loop (PLL) and clock prescalers can be used to generate a wide range of clock frequencies. An oscillator failure monitor
can be enabled to issue a non-maskable interrupt and switch to the internal oscillator if the external oscillator or PLL fails.
When a reset occurs, all clock sources except the 32kHz ultra low power oscillator are disabled. After reset, the device
will always start up running from the 2MHz internal oscillator. During normal operation, the system clock source and
prescalers can be changed from software at any time.
Figure 11-1 on page 22 presents the principal clock system in the XMEGA A1U family devices. Not all of the clocks need
to be active at a given time. The clocks for the CPU and peripherals can be stopped using sleep modes and power
reduction registers as described in “Power Management and Sleep Modes” on page 24.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 22
8067O–AVR–06/2013
Figure 11-1. The clock system, clock sources and clock distribution
11.3 Clock Options
The clock sources are divided in two main groups: internal oscillators and external clock sources. Most of the clock
sources can be directly enabled and disabled from software, while others are automatically enabled or disabled,
depending on peripheral settings. After reset, the device starts up running from the 2MHz internal oscillator. The other
clock sources and PLL are turned off by default.
The internal oscillators do not require any external components to run. For details on characteristics and accuracy of the
internal oscillators, refer to the device datasheet.
11.3.1 32 kHz Ultra Low Power Internal Oscillator
This oscillator provides an approximate 32kHz clock. The 32kHz ultra low power (ULP) internal oscillator is a very low
power clock source, and it is not designed for high accuracy. The oscillator employs a built-in prescaler that provides a
1kHz output. The oscillator is automatically enabled/disabled when it is used as clock source for any part of the device.
This oscillator can be selected as the clock source for the RTC.
Real Time
Counter Peripherals RAM AVR CPU Non-Volatile
Memory
Watchdog
Timer
Brown-out
Detector
System Clock Prescalers
System Clock Multiplexer
(SCLKSEL)
PLLSRC
RTCSRC
DIV32
32 kHz
Int. ULP
32.768 kHz
Int. OSC
32.768 kHz
TOSC
2 MHz
Int. Osc
32 MHz
Int. Osc
0.4 – 16 MHz
XTAL
DIV32
DIV32
DIV4
XOSCSEL
PLL
TOSC1
TOSC2
XTAL1
XTAL2
clkSYS clkRTC
clkPER2
clkPER
clkCPU
clkPER4[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 23
8067O–AVR–06/2013
11.3.2 32.768 kHz Calibrated Internal Oscillator
This oscillator provides an approximate 32.768kHz clock. It is calibrated during production to provide a default frequency
close to its nominal frequency. The calibration register can also be written from software for run-time calibration of the
oscillator frequency. The oscillator employs a built-in prescaler, which provides both a 32.768kHz output and a 1.024kHz
output.
11.3.3 32.768 kHz Crystal Oscillator
A 32.768kHz crystal oscillator can be connected between the 1 and 2 pins and enables a dedicated low frequency
oscillator input circuit. A low power mode with reduced voltage swing on 2 is available. This oscillator can be used as a
clock source for the system clock and RTC.
11.3.4 0.4 - 16 MHz Crystal Oscillator
This oscillator can operate in four different modes optimized for different frequency ranges, all within 0.4 - 16MHz.
11.3.5 2 MHz Run-time Calibrated Internal Oscillator
The 2MHz Run-time Calibrated Internal Oscillator is a high frequency oscillator. It is calibrated during production to
provide a default frequency which is close to its nominal frequency. The oscillator can use the 32kHz Calibrated Internal
Oscillator or the 32kHz Crystal Oscillator as a source for calibrating the frequency run-time to compensate for
temperature and voltage drift hereby optimizing the accuracy of the oscillator.
11.3.6 32 MHz Run-time Calibrated Internal Oscillator
The 32MHz Run-time Calibrated Internal Oscillator is a high frequency oscillator. It is calibrated during production to
provide a default frequency which is close to its nominal frequency. The oscillator can use the 32kHz Calibrated Internal
Oscillator or the 32kHz Crystal Oscillator as a source for calibrating the frequency run-time to compensate for
temperature and voltage drift hereby optimizing the accuracy of the oscillator.
11.3.7 External Clock input
The XTAL1 and XTAL2 pins can be used to drive an external oscillator, either a quartz crystal or a ceramic resonator.
XTAL1 can be used as input for an external clock signal. The 1 and 2 pins is dedicated to driving a 32.768kHz crystal
oscillator.
11.3.8 PLL with Multiplication factor 1 - 31x
The built-in phase locked loop (PLL) can be used to generate a high-frequency system clock. The PLL has a userselectable
multiplication factor of from 1 to 31. In combination with the prescalers, this gives a wide range of output
frequencies from all clock sources.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 24
8067O–AVR–06/2013
12. Power Management and Sleep Modes
12.1 Features
Power management for adjusting power consumption and functions
5 sleep modes
Idle
Power-down
Power-save
Standby
Extended standby
Power reduction register to disable clock and turn off unused peripherals in active and idle modes
12.2 Overview
Various sleep modes and clock gating are provided in order to tailor power consumption to application requirements.
This enables the Atmel AVR XMEGA microcontroller to stop unused modules to save power.
All sleep modes are available and can be entered from active mode. In active mode, the CPU is executing application
code. When the device enters sleep mode, program execution is stopped and interrupts or a reset is used to wake the
device again. The application code decides which sleep mode to enter and when. Interrupts from enabled peripherals
and all enabled reset sources can restore the microcontroller from sleep to active mode.
In addition, power reduction registers provide a method to stop the clock to individual peripherals from software. When
this is done, the current state of the peripheral is frozen, and there is no power consumption from that peripheral. This
reduces the power consumption in active mode and idle sleep modes and enables much more fine-tuned power
management than sleep modes alone.
12.3 Sleep Modes
Sleep modes are used to shut down modules and clock domains in the microcontroller in order to save power. XMEGA
microcontrollers have five different sleep modes tuned to match the typical functional stages during application
execution. A dedicated sleep instruction (SLEEP) is available to enter sleep mode. Interrupts are used to wake the
device from sleep, and the available interrupt wake-up sources are dependent on the configured sleep mode. When an
enabled interrupt occurs, the device will wake up and execute the interrupt service routine before continuing normal
program execution from the first instruction after the SLEEP instruction. If other, higher priority interrupts are pending
when the wake-up occurs, their interrupt service routines will be executed according to their priority before the interrupt
service routine for the wake-up interrupt is executed. After wake-up, the CPU is halted for four cycles before execution
starts.
The content of the register file, SRAM and registers are kept during sleep. If a reset occurs during sleep, the device will
reset, start up, and execute from the reset vector.
12.3.1 Idle Mode
In idle mode the CPU and nonvolatile memory are stopped (note that any ongoing programming will be completed), but
all peripherals, including the interrupt controller, event system and DMA controller are kept running. Any enabled
interrupt will wake the device.
12.3.2 Power-down Mode
In power-down mode, all clocks, including the real-time counter clock source, are stopped. This allows operation only of
asynchronous modules that do not require a running clock. The only interrupts that can wake up the MCU are the twowire
interface address match interrupt and asynchronous port interrupts, e.g pin change.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 25
8067O–AVR–06/2013
12.3.3 Power-save Mode
Power-save mode is identical to power down, with one exception. If the real-time counter (RTC) is enabled, it will keep
running during sleep, and the device can also wake up from either an RTC overflow or compare match interrupt.
12.3.4 Standby Mode
Standby mode is identical to power down, with the exception that the enabled system clock sources are kept running
while the CPU, peripheral, and RTC clocks are stopped. This reduces the wake-up time.
12.3.5 Extended Standby Mode
Extended standby mode is identical to power-save mode, with the exception that the enabled system clock sources are
kept running while the CPU and peripheral clocks are stopped. This reduces the wake-up time.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 26
8067O–AVR–06/2013
13. System Control and Reset
13.1 Features
Multiple reset sources for safe operation and device reset
Power-On Reset
External Reset
Watchdog Reset
Brown-Out Reset
PDI reset
Software reset
Asynchronous reset
No running clock in the device is required for reset
Reset status register
13.2 Overview
The reset system issues a microcontroller reset and sets the device to its initial state. This is for situations where
operation should not start or continue, such as when the microcontroller operates below its power supply rating. If a reset
source goes active, the device enters and is kept in reset until all reset sources have released their reset. The I/O pins
are immediately tri-stated. The program counter is set to the reset vector location, and all I/O registers are set to their
initial values. The SRAM content is kept. However, if the device accesses the SRAM when a reset occurs, the content of
the accessed location can not be guaranteed.
After reset is released from all reset sources, the default oscillator is started and calibrated before the device starts
running from the reset vector address. By default, this is the lowest program memory address, 0, but it is possible to
move the reset vector to the lowest address in the boot section.
The reset functionality is asynchronous, and so no running system clock is required to reset the device. The software
reset feature makes it possible to issue a controlled system reset from the user software.
The reset status register has individual status flags for each reset source. It is cleared at power-on reset, and shows
which sources have issued a reset since the last power-on.
13.3 Reset Sequence
A reset request from any reset source will immediately reset the device and keep it in reset as long as the request is
active. When all reset requests are released, the device will go through three stages before the device starts running
again:
Reset counter delay
Oscillator startup
Oscillator calibration
If another reset requests occurs during this process, the reset sequence will start over again.
13.4 Reset Sources
13.4.1 Power-On Reset
TA power-on reset (POR) is generated by an on-chip detection circuit. The POR is activated when the VCC rises and
reaches the POR threshold voltage (VPOT), and this will start the reset sequence.
The POR is also activated to power down the device properly when the VCC falls and drops below the VPOT level.
The VPOT level is higher for falling VCC than for rising VCC. Consult the datasheet for POR characteristics data.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 27
8067O–AVR–06/2013
13.4.2 Brownout Detection
The on-chip brownout detection (BOD) circuit monitors the VCC level during operation by comparing it to a fixed,
programmable level that is selected by the BODLEVEL fuses. If disabled, BOD is forced on at the lowest level during chip
erase and when the PDI is enabled.
13.4.3 External Reset
The external reset circuit is connected to the external RESET pin. The external reset will trigger when the RESET pin is
driven below the RESET pin threshold voltage, VRST, for longer than the minimum pulse period, tEXT. The reset will be
held as long as the pin is kept low. The RESET pin includes an internal pull-up resistor.
13.4.4 Watchdog Reset
The watchdog timer (WDT) is a system function for monitoring correct program operation. If the WDT is not reset from
the software within a programmable timeout period, a watchdog reset will be given. The watchdog reset is active for one
to two clock cycles of the 2MHz internal oscillator. For more details see “WDT - Watchdog Timer” on page 28.
13.4.5 Software reset
The software reset makes it possible to issue a system reset from software by writing to the software reset bit in the reset
control register.The reset will be issued within two CPU clock cycles after writing the bit. It is not possible to execute any
instruction from when a software reset is requested until it is issued.
13.4.6 Program and Debug Interface Reset
The program and debug interface reset contains a separate reset source that is used to reset the device during external
programming and debugging. This reset source is accessible only from external debuggers and programmers.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 28
8067O–AVR–06/2013
13.5 WDT - Watchdog Timer
13.5.1 Features
Issues a device reset if the timer is not reset before its timeout period
Asynchronous operation from dedicated oscillator
1kHz output of the 32kHz ultra low power oscillator
11 selectable timeout periods, from 8ms to 8s
Two operation modes:
Normal mode
Window mode
Configuration lock to prevent unwanted changes
13.6 Overview
The watchdog timer (WDT) is a system function for monitoring correct program operation. It makes it possible to recover
from error situations such as runaway or deadlocked code. The WDT is a timer, configured to a predefined timeout
period, and is constantly running when enabled. If the WDT is not reset within the timeout period, it will issue a
microcontroller reset. The WDT is reset by executing the WDR (watchdog timer reset) instruction from the application
code.
The window mode makes it possible to define a time slot or window inside the total timeout period during which WDT
must be reset. If the WDT is reset outside this window, either too early or too late, a system reset will be issued.
Compared to the normal mode, this can also catch situations where a code error causes constant WDR execution.
The WDT will run in active mode and all sleep modes, if enabled. It is asynchronous, runs from a CPU-independent clock
source, and will continue to operate to issue a system reset even if the main clocks fail.
The configuration change protection mechanism ensures that the WDT settings cannot be changed by accident. For
increased safety, a fuse for locking the WDT settings is also available.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 29
8067O–AVR–06/2013
14. Interrupts and Programmable Multilevel Interrupt Controller
14.1 Features
Short and predictable interrupt response time
Separate interrupt configuration and vector address for each interrupt
Programmable multilevel interrupt controller
Interrupt prioritizing according to level and vector address
Three selectable interrupt levels for all interrupts: low, medium and high
Selectable, round-robin priority scheme within low-level interrupts
Non-maskable interrupts for critical functions
Interrupt vectors optionally placed in the application section or the boot loader section
14.2 Overview
Interrupts signal a change of state in peripherals, and this can be used to alter program execution. Peripherals can have
one or more interrupts, and all are individually enabled and configured. When an interrupt is enabled and configured, it
will generate an interrupt request when the interrupt condition is present. The programmable multilevel interrupt
controller (PMIC) controls the handling and prioritizing of interrupt requests. When an interrupt request is acknowledged
by the PMIC, the program counter is set to point to the interrupt vector, and the interrupt handler can be executed.
All peripherals can select between three different priority levels for their interrupts: low, medium, and high. Interrupts are
prioritized according to their level and their interrupt vector address. Medium-level interrupts will interrupt low-level
interrupt handlers. High-level interrupts will interrupt both medium- and low-level interrupt handlers. Within each level, the
interrupt priority is decided from the interrupt vector address, where the lowest interrupt vector address has the highest
interrupt priority. Low-level interrupts have an optional round-robin scheduling scheme to ensure that all interrupts are
serviced within a certain amount of time.
Non-maskable interrupts (NMI) are also supported, and can be used for system critical functions.
14.3 Interrupt vectors
The interrupt vector is the sum of the peripheral’s base interrupt address and the offset address for specific interrupts in
each peripheral. The base addresses for the Atmel AVR XMEGA A1U devices are shown in Table 14-1. Offset
addresses for each interrupt available in the peripheral are described for each peripheral in the XMEGA AU manual. For
peripherals or modules that have only one interrupt, the interrupt vector is shown in Table 14-1. The program address is
the word address.
Table 14-1. Reset and Interrupt vectors
Program Address
(Base Address) Source Interrupt Description
0x000 RESET
0x002 OSCF_INT_vect Crystal Oscillator Failure Interrupt vector (NMI)
0x004 PORTC_INT_base Port C Interrupt base
0x008 PORTR_INT_base Port R Interrupt base
0x00C DMA_INT_base DMA Controller Interrupt base
0x014 RTC_INT_base Real Time Counter Interrupt base
0x018 TWIC_INT_base Two-Wire Interface on Port C Interrupt base[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 30
8067O–AVR–06/2013
0x01C TCC0_INT_base Timer/Counter 0 on port C Interrupt base
0x028 TCC1_INT_base Timer/Counter 1 on port C Interrupt base
0x030 SPIC_INT_vect SPI on port C Interrupt vector
0x032 USARTC0_INT_base USART 0 on port C Interrupt base
0x038 USARTC1_INT_base USART 1 on port C Interrupt base
0x03E AES_INT_vect AES Interrupt vector
0x040 NVM_INT_base Non-Volatile Memory Interrupt base
0x044 PORTB_INT_base Port B Interrupt base
0x048 ACB_INT_base Analog Comparator on Port B Interrupt base
0x04E ADCB_INT_base Analog to Digital Converter on Port B Interrupt base
0x056 PORTE_INT_base Port E Interrupt base
0x05A TWIE_INT_base Two-Wire Interface on Port E Interrupt base
0x05E TCE0_INT_base Timer/Counter 0 on port E Interrupt base
0x06A TCE1_INT_base Timer/Counter 1 on port E Interrupt base
0x072 SPIE_INT_vect SPI on port E Interrupt vector
0x074 USARTE0_INT_base USART 0 on port E Interrupt base
0x07A USARTE1_INT_base USART 1 on port E Interrupt base
0x080 PORTD_INT_base Port D Interrupt base
0x084 PORTA_INT_base Port A Interrupt base
0x088 ACA_INT_base Analog Comparator on Port A Interrupt base
0x08E ADCA_INT_base Analog to Digital Converter on Port A Interrupt base
0x096 TWID_INT_base Two-Wire Interface on Port D Interrupt base
0x09A TCD0_INT_base Timer/Counter 0 on port D Interrupt base
0x0A6 TCD1_INT_base Timer/Counter 1 on port D Interrupt base
0x0AE SPID_INT_vector SPI on port D Interrupt vector
0x0B0 USARTD0_INT_base USART 0 on port D Interrupt base
0x0B6 USARTD1_INT_base USART 1 on port D Interrupt base
0x0BC PORTQ_INT_base Port Q INT base
0x0C0 PORTH_INT_base Port H INT base
0x0C4 PORTJ_INT_base Port J INT base
0x0C8 PORTK_INT_base Port K INT base
0x0D0 PORTF_INT_base Port F INT base
0x0D4 TWIF_INT_base Two-Wire Interface on Port F INT base
Program Address
(Base Address) Source Interrupt Description[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 31
8067O–AVR–06/2013
0x0D8 TCF0_INT_base Timer/Counter 0 on port F Interrupt base
0x0E4 TCF1_INT_base Timer/Counter 1 on port F Interrupt base
0x0EC SPIF_INT_vector SPI ion port F Interrupt base
0x0EE USARTF0_INT_base USART 0 on port F Interrupt base
0x0F4 USARTF1_INT_base USART 1 on port F Interrupt base
Program Address
(Base Address) Source Interrupt Description[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 32
8067O–AVR–06/2013
15. I/O Ports
15.1 Features
78 General purpose input and output pins with individual configuration
Output driver with configurable driver and pull settings:
Totem-pole
Wired-AND
Wired-OR
Bus-keeper
Inverted I/O
Input with synchronous and/or asynchronous sensing with interrupts and events
Sense both edges
Sense rising edges
Sense falling edges
Sense low level
Optional pull-up and pull-down resistor on input and Wired-OR/AND configurations
Optional slew rate control
Asynchronous pin change sensing that can wake the device from all sleep modes
Two port interrupts with pin masking per I/O port
Efficient and safe access to port pins
Hardware read-modify-write through dedicated toggle/clear/set registers
Configuration of multiple pins in a single operation
Mapping of port registers into bit-accessible I/O memory space
Peripheral clocks output on port pin
Real-time counter clock output to port pin
Event channels can be output on port pin
Remapping of digital peripheral pin functions
Selectable USART, SPI, and timer/counter input/output pin locations
15.2 Overview
One port consists of up to eight port pins: pin 0 to 7. Each port pin can be configured as input or output with configurable
driver and pull settings. They also implement synchronous and asynchronous input sensing with interrupts and events for
selectable pin change conditions. Asynchronous pin-change sensing means that a pin change can wake the device from
all sleep modes, included the modes where no clocks are running.
All functions are individual and configurable per pin, but several pins can be configured in a single operation. The pins
have hardware read-modify-write (RMW) functionality for safe and correct change of drive value and/or pull resistor
configuration. The direction of one port pin can be changed without unintentionally changing the direction of any other
pin.
The port pin configuration also controls input and output selection of other device functions. It is possible to have both the
peripheral clock and the real-time clock output to a port pin, and available for external use. The same applies to events
from the event system that can be used to synchronize and control external functions. Other digital peripherals, such as
USART, SPI, and timer/counters, can be remapped to selectable pin locations in order to optimize pin-out versus
application needs.
The notation of these ports are PORTA, PORTB, PORTC, PORTD, PORTE, PORTF, PORTH, PORTJ, PORTK, PORTQ
and PORTR.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 33
8067O–AVR–06/2013
15.3 Output Driver
All port pins (Pn) have programmable output configuration. The port pins also have configurable slew rate limitation to
reduce electromagnetic emission.
15.3.1 Push-pull
Figure 15-1. I/O configuration - Totem-pole
15.3.2 Pull-down
Figure 15-2. I/O configuration - Totem-pole with pull-down (on input)
15.3.3 Pull-up
Figure 15-3. I/O configuration - Totem-pole with pull-up (on input)
INn
OUTn
DIRn
Pn
INn
OUTn
DIRn
Pn
INn
OUTn
DIRn
Pn[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 34
8067O–AVR–06/2013
15.3.4 Bus-keeper
The bus-keeper’s weak output produces the same logical level as the last output level. It acts as a pull-up if the last level
was ‘1’, and pull-down if the last level was ‘0’.
Figure 15-4. I/O configuration - Totem-pole with bus-keeper
15.3.5 Others
Figure 15-5. Output configuration - Wired-OR with optional pull-down
Figure 15-6. I/O configuration - Wired-AND with optional pull-up
INn
OUTn
DIRn
Pn
INn
OUTn
Pn
INn
OUTn
Pn[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 35
8067O–AVR–06/2013
15.4 Input sensing
Input sensing is synchronous or asynchronous depending on the enabled clock for the ports, and the configuration is
shown in Figure 15-7 on page 35.
Figure 15-7. Input sensing system overview
When a pin is configured with inverted I/O the pin value is inverted before the input sensing.
15.5 Port Interrupt
Each ports have two interrupts with seperate priority and interrupt vector. All pins on the port can be individually selected
as source for each of the interrupts. The interrupts are then triggered according to the input sense configuration for each
pin configured as source for the interrupt.
15.6 Alternate Port Functions
In addition to the input/output functions on all port pins, most pins have alternate functions. This means that other
modules or peripherals connected to the port can use the port pins for their functions, such as communication or pulsewidth
modulation. “Pinout and Pin Functions” on page 55 shows which modules on peripherals that enables alternate
functions on a pin, and what alternate functions that is available on a pin.
INVERTED I/O
Interrupt
Control IREQ
Event
Pn
D Q
R
D Q
R
Synchronizer
INn
EDGE
DETECT
Asynchronous sensing
Synchronous sensing
EDGE
DETECT[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 36
8067O–AVR–06/2013
16. T/C - 16-bit Timer/Counter
16.1 Features
Eight 16-bit Timer/Counters
Four Timer/Counters of type 0
Four Timer/Counters of type 1
Four Compare or Capture (CC) Channels in Timer/Counter 0
Two Compare or Capture (CC) Channels in Timer/Counter 1
Double Buffered Timer Period Setting
Double Buffered Compare or Capture Channels
Waveform Generation:
Single Slope Pulse Width Modulation
Dual Slope Pulse Width Modulation
Frequency Generation
Input Capture:
Input Capture with Noise Cancelling
Frequency capture
Pulse width capture
32-bit input capture
Event Counter with Direction Control
Timer Overflow and Timer Error Interrupts and Events
One Compare Match or Capture Interrupt and Event per CC Channel
Supports DMA Operation
Hi-Resolution Extension (Hi-Res)
Advanced Waveform Extension (AWEX)
16.2 Overview
Atmel AVR XMEGA devices have a set of eight flexible 16-bit timer/counters (TC). Their capabilities include accurate
program execution timing, frequency and waveform generation, and input capture with time and frequency measurement
of digital signals. Two timer/counters can be cascaded to create a 32-bit timer/counter with optional 32-bit capture.
A timer/counter consists of a base counter and a set of compare or capture (CC) channels. The base counter can be
used to count clock cycles or events. It has direction control and period setting that can be used for timing. The CC
channels can be used together with the base counter to do compare match control, frequency generation, and pulse
width waveform modulation, as well as various input capture operations. A timer/counter can be configured for either
capture or compare functions, but cannot perform both at the same time.
A timer/counter can be clocked and timed from the peripheral clock with optional prescaling or from the event system.
The event system can also be used for direction control and capture trigger or to synchronize operations.
There are two differences between timer/counter type 0 and type 1. Timer/counter 0 has four CC channels, and
timer/counter 1 has two CC channels. All information related to CC channels 3 and 4 is valid only for timer/counter 0.
Only Timer/Counter 0 has the split mode feature that split it into 2 8-bit Timer/Counters with four compare channels each.
Some timer/counters have extensions to enable more specialized waveform and frequency generation. The advanced
waveform extension (AWeX) is intended for motor control and other power control applications. It enables low- and highside
output with dead-time insertion, as well as fault protection for disabling and shutting down external drivers. It can
also generate a synchronized bit pattern across the port pins.
The advanced waveform extension can be enabled to provide extra and more advanced features for the Timer/Counter.
This is only available for Timer/Counter 0. See “AWeX - Advanced Waveform Extension” on page 38 for more details.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 37
8067O–AVR–06/2013
The high-resolution (hi-res) extension can be used to increase the waveform output resolution by four or eight times by
using an internal clock source running up to four times faster than the peripheral clock. See “Hi-Res - High Resolution
Extension” on page 39 for more details.
Figure 16-1. Overview of a Timer/Counter and closely related peripherals
PORTC, PORTD, PORTE and PORTF each has one Timer/Counter 0 and one Timer/Counter1. Notation of these
Timer/Counters are TCC0 (Time/Counter C0), TCC1, TCD0, TCD1, TCE0, TCE1, TCF0, and TCF1, respectively.
AWeX
Compare/Capture Channel D
Compare/Capture Channel C
Compare/Capture Channel B
Compare/Capture Channel A
Waveform
Generation Buffer
Comparator
Hi-Res
Fault
Protection
Capture
Control
Base Counter
Counter
Control Logic
Timer Period
Prescaler
DTI
Dead-Time
Insertion
Pattern
Generation
clkPER4
PORT
Event
System
clkPER
Timer/Counter[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 38
8067O–AVR–06/2013
17. AWeX - Advanced Waveform Extension
17.1 Features
Output with complementary output from each Capture channel
Four Dead Time Insertion (DTI) Units, one for each Capture channel
8-bit DTI Resolution
Separate High and Low Side Dead-Time Setting
Double Buffered Dead-Time
Event Controlled Fault Protection
Single Channel Multiple Output Operation (for BLDC motor control)
Double Buffered Pattern Generation
17.2 Overview
The advanced waveform extension (AWeX) provides extra functions to the timer/counter in waveform generation (WG)
modes. It is primarily intended for use with different types of motor control and other power control applications. It
enables low- and high side output with dead-time insertion and fault protection for disabling and shutting down external
drivers. It can also generate a synchronized bit pattern across the port pins.
Each of the waveform generator outputs from the Timer/Counter 0 are split into a complimentary pair of outputs when
any AWeX features are enabled. These output pairs go through a dead-time insertion (DTI) unit that generates the noninverted
low side (LS) and inverted high side (HS) of the WG output with dead-time insertion between LS and HS
switching. The DTI output will override the normal port value according to the port override setting.
The pattern generation unit can be used to generate a synchronized bit pattern on the port it is connected to. In addition,
the WG output from compare channel A can be distributed to and override all the port pins. When the pattern generator
unit is enabled, the DTI unit is bypassed.
The fault protection unit is connected to the event system, enabling any event to trigger a fault condition that will disable
the AWeX output. The event system ensures predictable and instant fault reaction, and gives great flexibility in the
selection of fault triggers.
The AWeX is available for TCC0 and TCE0. The notation of these are AWEXC and AWEXE.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 39
8067O–AVR–06/2013
18. Hi-Res - High Resolution Extension
18.1 Features
Increases Waveform Generator resolution by 2-bits (4x)
Supports Frequency, single- and dual-slope PWM operation
Supports the AWeX when this is enabled and used for the same Timer/Counter
18.2 Overview
TThe high-resolution (hi-res) extension can be used to increase the resolution of the waveform generation output from a
timer/counter by four or eight. It can be used for a timer/counter doing frequency, single-slope PWM, or dual-slope PWM
generation. It can also be used with the AWeX if this is used for the same timer/counter.
The hi-res extension uses the peripheral 4x clock (ClkPER4). The system clock prescalers must be configured so the
peripheral 4x clock frequency is four times higher than the peripheral and CPU clock frequency when the hi-res extension
is enabled.
There are four hi-res extensions that each can be enabled for each timer/counters pair on PORTC, PORTD, PORTE and
PORTF. The notation of these peripherals are HIRESC, HIRESD, HIRESE and HIRESF, respectively.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 40
8067O–AVR–06/2013
19. RTC - 16-bit Real-Time Counter
19.1 Features
16-bit resolution
Selectable clock source
32.768kHz external crystal
External clock
32.768kHz internal oscillator
32kHz internal ULP oscillator
Programmable 10-bit clock prescaling
One compare register
One period register
Clear counter on period overflow
Optional interrupt/event on overflow and compare match
19.2 Overview
The 16-bit real-time counter (RTC) is a counter that typically runs continuously, including in low-power sleep modes, to
keep track of time. It can wake up the device from sleep modes and/or interrupt the device at regular intervals.
The reference clock is typically the 1.024kHz output from a high-accuracy crystal of 32.768kHz, and this is the
configuration most optimized for low power consumption. The faster 32.768kHz output can be selected if the RTC needs
a resolution higher than 1ms. The RTC can also be clocked from an external clock signal, the 32.768kHz internal
oscillator or the 32kHz internal ULP oscillator.
The RTC includes a 10-bit programmable prescaler that can scale down the reference clock before it reaches the
counter. A wide range of resolutions and time-out periods can be configured. With a 32.768kHz clock source, the
maximum resolution is 30.5µs, and time-out periods can range up to 2000 seconds. With a resolution of 1s, the
maximum timeout period is more than18 hours (65536 seconds). The RTC can give a compare interrupt and/or event
when the counter equals the compare register value, and an overflow interrupt and/or event when it equals the period
register value.
Figure 19-1. Real Time Counter overview
32.768kHz Crystal Osc
32.768kHz Int. Osc
TOSC1
TOSC2
External Clock
DIV32
DIV32
32kHz int ULP (DIV32)
RTCSRC
10-bit
prescaler
clkRTC
CNT
PER
COMP
=
=
”match”/
Compare
TOP/
Overflow[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 41
8067O–AVR–06/2013
20. TWI - Two-Wire Interface
20.1 Features
Four identical two-wire interface peripherals
Bidirectional two-wire communication interface
Phillips I2C compatible
System Management Bus (SMBus) compatible
Bus master and slave operation supported
Slave operation
Single bus master operation
Bus master in multi-master bus environment
Multi-master arbitration
Flexible slave address match functions
7-bit and general call address recognition in hardware
10-bit addressing supported
Address mask register for dual address match or address range masking
Optional software address recognition for unlimited number of addresses
Slave can operate in all sleep modes, including power-down
Slave address match can wake device from all sleep modes, including power-down
100kHz and 400kHz bus frequency support
Slew-rate limited output drivers
Input filter for bus noise and spike suppression
Support arbitration between start repeated start and data bit (SMBus)
Slave arbitration allows support for address resolve protocol (ARP) (SMBus)
20.2 Overview
The two-wire interface (TWI) is a bidirectional, two-wire communication interface. It is I2C and System Management Bus
(SMBus) compatible. The only external hardware needed to implement the bus is one pull-up resistor on each bus line.
A device connected to the bus must act as a master or a slave. The master initiates a data transaction by addressing a
slave on the bus and telling whether it wants to transmit or receive data. One bus can have many slaves and one or
several masters that can take control of the bus. An arbitration process handles priority if more than one master tries to
transmit data at the same time. Mechanisms for resolving bus contention are inherent in the protocol.
The TWI module supports master and slave functionality. The master and slave functionality are separated from each
other, and can be enabled and configured separately. The master module supports multi-master bus operation and
arbitration. It contains the baud rate generator. Both 100kHz and 400kHz bus frequency is supported. Quick command
and smart mode can be enabled to auto-trigger operations and reduce software complexity.
The slave module implements 7-bit address match and general address call recognition in hardware. 10-bit addressing is
also supported. A dedicated address mask register can act as a second address match register or as a register for
address range masking. The slave continues to operate in all sleep modes, including power-down mode. This enables
the slave to wake up the device from all sleep modes on TWI address match. It is possible to disable the address
matching to let this be handled in software instead.
The TWI module will detect START and STOP conditions, bus collisions, and bus errors. Arbitration lost, errors, collision,
and clock hold on the bus are also detected and indicated in separate status flags available in both master and slave
modes. [Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 42
8067O–AVR–06/2013
It is possible to disable the TWI drivers in the device, and enable a four-wire digital interface for connecting to an external
TWI bus driver. This can be used for applications where the device operates from a different VCC voltage than used by
the TWI bus.
PORTC, PORTD, PORTE, and PORTF each has one TWI. Notation of these peripherals are TWIC, TWID, TWIE, and
TWIF.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 43
8067O–AVR–06/2013
21. SPI - Serial Peripheral Interface
21.1 Features
Four identical SPI peripherals
Full-duplex, three-wire synchronous data transfer
Master or slave operation
Lsb first or msb first data transfer
Eight programmable bit rates
Interrupt flag at the end of transmission
Write collision flag to indicate data collision
Wake up from idle sleep mode
Double speed master mode
21.2 Overview
The Serial Peripheral Interface (SPI) is a high-speed synchronous data transfer interface using three or four pins. It
allows fast communication between an Atmel AVR XMEGA device and peripheral devices or between several
microcontrollers. The SPI supports full-duplex communication.
A device connected to the bus must act as a master or slave. The master initiates and controls all data transactions.
PORTC, PORTD, PORTE, and PORTF each has one SPI. Notation of these peripherals are SPIC, SPID, SPIE, and
SPIF.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 44
8067O–AVR–06/2013
22. USART
22.1 Features
Eight identical USART peripherals
Full-duplex operation
Asynchronous or synchronous operation
Synchronous clock rates up to 1/2 of the device clock frequency
Asynchronous clock rates up to 1/8 of the device clock frequency
Supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits
Fractional baud rate generator
Can generate desired baud rate from any system clock frequency
No need for external oscillator with certain frequencies
Built-in error detection and correction schemes
Odd or even parity generation and parity check
Data overrun and framing error detection
Noise filtering includes false start bit detection and digital low-pass filter
Separate interrupts for
Transmit complete
Transmit data register empty
Receive complete
Multiprocessor communication mode
Addressing scheme to address a specific devices on a multidevice bus
Enable unaddressed devices to automatically ignore all frames
Master SPI mode
Double buffered operation
Operation up to 1/2 of the peripheral clock frequency
IRCOM module for IrDA compliant pulse modulation/demodulation
22.2 Overview
The universal synchronous and asynchronous serial receiver and transmitter (USART) is a fast and flexible serial
communication module. The USART supports full-duplex communication and asynchronous and synchronous operation.
The USART can be configured to operate in SPI master mode and used for SPI communication.
Communication is frame based, and the frame format can be customized to support a wide range of standards. The
USART is buffered in both directions, enabling continued data transmission without any delay between frames. Separate
interrupts for receive and transmit complete enable fully interrupt driven communication. Frame error and buffer overflow
are detected in hardware and indicated with separate status flags. Even or odd parity generation and parity check can
also be enabled.
The clock generator includes a fractional baud rate generator that is able to generate a wide range of USART baud rates
from any system clock frequencies. This removes the need to use an external crystal oscillator with a specific frequency
to achieve a required baud rate. It also supports external clock input in synchronous slave operation.
When the USART is set in master SPI mode, all USART-specific logic is disabled, leaving the transmit and receive
buffers, shift registers, and baud rate generator enabled. Pin control and interrupt generation are identical in both modes.
The registers are used in both modes, but their functionality differs for some control settings.
An IRCOM module can be enabled for one USART to support IrDA 1.4 physical compliant pulse modulation and
demodulation for baud rates up to 115.2Kbps.
PORTC, PORTD, PORTE, and PORTF each has two USARTs. Notation of these peripherals are USARTC0, USARTC1,
USARTD0, USARTD1, USARTE0, USARTE1, USARTF0 and USARTF1.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 45
8067O–AVR–06/2013
23. IRCOM - IR Communication Module
23.1 Features
Pulse modulation/demodulation for infrared communication
IrDA compatible for baud rates up to 115.2Kbps
Selectable pulse modulation scheme
3/16 of the baud rate period
Fixed pulse period, 8-bit programmable
Pulse modulation disabled
Built-in filtering
Can be connected to and used by any USART
23.2 Overview
Atmel AVR XMEGA devices contain an infrared communication module (IRCOM) that is IrDA compatible for baud rates
up to 115.2Kbps. It can be connected to any USART to enable infrared pulse encoding/decoding for that USART.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 46
8067O–AVR–06/2013
24. AES and DES Crypto Engine
24.1 Features
Data Encryption Standard (DES) CPU instruction
Advanced Encryption Standard (AES) crypto module
DES Instruction
Encryption and decryption
DES supported
Encryption/decryption in 16 CPU clock cycles per 8-byte block
AES crypto module
Encryption and decryption
Supports 128-bit keys
Supports XOR data load mode to the state memory
Encryption/decryption in 375 clock cycles per 16-byte block
24.2 Overview
The Advanced Encryption Standard (AES) and Data Encryption Standard (DES) are two commonly used standards for
cryptography. These are supported through an AES peripheral module and a DES CPU instruction, and the
communication interfaces and the CPU can use these for fast, encrypted communication and secure data storage.
DES is supported by an instruction in the AVR CPU. The 8-byte key and 8-byte data blocks must be loaded into the
register file, and then the DES instruction must be executed 16 times to encrypt/decrypt the data block.
The AES crypto module encrypts and decrypts 128-bit data blocks with the use of a 128-bit key. The key and data must
be loaded into the key and state memory in the module before encryption/decryption is started. It takes 375 peripheral
clock cycles before the encryption/decryption is done. The encrypted/encrypted data can then be read out, and an
optional interrupt can be generated. The AES crypto module also has DMA support with transfer triggers when
encryption/decryption is done and optional auto-start of encryption/decryption when the state memory is fully loaded.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 47
8067O–AVR–06/2013
25. EBI – External Bus Interface
25.1 Features
Supports SRAM up to:
512KB using 3-port EBI configuration
16MB using 3-port EBI configuration
Supports SDRAM up to:
128Mb using 3-port EBI configuration
Four software configurable chip selects
Software configurable wait state insertion
Can run from the 2x peripheral clock frequency for fast access
25.2 Overview
The External Bus Interface (EBI) is used to connect external peripherals and memory for access through the data
memory space. When the EBI is enabled, data address space outside the internal SRAM becomes available using
dedicated EBI pins.
The EBI can interface external SRAM, SDRAM, and peripherals, such as LCD displays and other memory mapped
devices.
The address space for the external memory is selectable from 256 bytes (8-bit) up to 16MB (24-bit). Various multiplexing
modes for address and data lines can be selected for optimal use of pins when more or fewer pins are available for the
EBI. The complete memory will be mapped into one linear data address space continuing from the end of the internal
SRAM.
The EBI has four chip selects, each with separate configuration. Each can be configured for SRAM, SRAM low pin count
(LPC), or SDRAM.
The EBI is clocked from the fast, 2x peripheral clock, running up to two times faster than the CPU.
Four-bit and eight-bit SDRAM are supported, and SDRAM configurations, such as CAS latency and refresh rate, are
configurable in software.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 48
8067O–AVR–06/2013
26. ADC - 12-bit Analog to Digital Converter
26.1 Features
Two ADCs with 12-bit resolution
2Msps sample rate for each ADC
Signed and unsigned conversions
4 result registers with individual input channel control for each ADC
8 single ended inputs for each ADC
8x4 differential inputs for each ADC
4 internal inputs:
Integrated Temperature Sensor
DAC Output
VCC voltage divided by 10
Bandgap voltage
Software selectable gain of 2, 4, 8, 16, 32 or 64
Software selectable resolution of 8- or 12-bit.
Internal or External Reference selection
Event triggered conversion for accurate timing
DMA transfer of conversion results
Interrupt/Event on compare result
26.2 Overview
XMEGA A1 devices have two Analog to Digital Converters (ADC), see Figure 26-1 on page 49. The two ADC modules
can be operated simultaneously, individually or synchronized.
The ADC converts analog voltages to digital values. The ADC has 12-bit resolution and is capable of converting up to 2
million samples per second. The input selection is flexible, and both single-ended and differential measurements can be
done. For differential measurements an optional gain stage is available to increase the dynamic range. In addition
several internal signal inputs are available. The ADC can provide both signed and unsigned results.
This is a pipeline ADC. A pipeline ADC consists of several consecutive stages, where each stage convert one part of the
result. The pipeline design enables high sample rate at low clock speeds, and remove limitations on samples speed
versus propagation delay. This also means that a new analog voltage can be sampled and a new ADC measurement
started while other ADC measurements are ongoing.
ADC measurements can either be started by application software or an incoming event from another peripheral in the
device. Four different result registers with individual input selection (MUX selection) are provided to make it easier for the
application to keep track of the data. Each result register and MUX selection pair is referred to as an ADC Channel. It is
possible to use DMA to move ADC results directly to memory or peripherals when conversions are done.
Both internal and external analog reference voltages can be used. An accurate internal 1.0V reference is available.
An integrated temperature sensor is available and the output from this can be measured with the ADC. The output from
the DAC, VCC/10 and the Bandgap voltage can also be measured by the ADC.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 49
8067O–AVR–06/2013
Figure 26-1. ADC overview
Each ADC has four MUX selection registers with a corresponding result register. This means that four channels can be
sampled within 1.5 µs without any intervention by the application other than starting the conversion. The results will be
available in the result registers.
The ADC may be configured for 8- or 12-bit result, reducing the minimum conversion time (propagation delay) from 3.5
µs for 12-bit to 2.5 µs for 8-bit result.
ADC conversion results are provided left- or right adjusted with optional ‘1’ or ‘0’ padding. This eases calculation when
the result is represented as a signed integer (signed 16-bit number).
PORTA and PORTB each has one ADC. Notation of these peripherals are ADCA and ADCB, respectively.
CH1 Result
CH0 Result
CH2 Result
Compare
<
>
Threshold
(Int Req)
Internal 1.00V
Internal VCC/1.6V
AREFA
AREFB
VINP
VINN
Internal
signals
Internal
signals
CH3 Result
ADC0
ADC7
ADC4
ADC7
ADC0
ADC3
•
•
•
Int. signals
Int. signals
Reference
Voltage
1x - 64x •
•
•
•
•
•
ADC0
ADC7
•
•
•[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 50
8067O–AVR–06/2013
27. DAC - 12-bit Digital to Analog Converter
27.1 Features
12-bit resolution
Two independent, continuous-drive output channels
Up to one million samples per second conversion rate
Built-in calibration that removes:
Offset error
Gain error
Multiple conversion trigger sources
On new available data
Events from the event system
High drive capabilities and support for
Resistive loads
Capacitive loads
Combined resistive and capacitive loads
Internal and external reference options
DAC output available as input to analog comparator and ADC
Low-power mode, with reduced drive strength
Optional DMA transfer of data
27.2 Overview
The XMEGA A1 devices features two 12-bit, 1 Msps DACs with built-in offset and gain calibration, see Figure 27-1 on
page 50.
A DAC converts a digital value into an analog signal. The DAC may use an internal 1.0 voltage as the upper limit for
conversion, but it is also possible to use the supply voltage or any applied voltage in-between. The external reference
input is shared with the ADC reference input.
Figure 27-1. DAC overview
CH1DATA
CH0DATA
Trigger
Internal 1.00V
AREFA
AREFB
AVCC
D
A
T
A
DAC CTRL
DAC CH0
REFSEL
Enable
12
12
ADC
DAC
DAC CH1
Output
Control and Driver[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 51
8067O–AVR–06/2013
Each DAC has one continuous output with high drive capabilities for both resistive and capacitive loads. It is also
possible to split the continuous time channel into two Sample and Hold (S/H) channels, each with separate data
conversion registers.
A DAC conversion may be started from the application software by writing the data conversion registers. The DAC can
also be configured to do conversions triggered by the Event System to have regular timing, independent of the
application software. DMA may be used for transferring data from memory locations to DAC data registers.
The DAC has a built-in calibration system to reduce offset and gain error when loading with a calibration value from
software.
PORTA and PORTB each has one DAC. Notation of these peripherals are DACA and DACB. respectively.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 52
8067O–AVR–06/2013
28. AC - Analog Comparator
28.1 Features
Four Analog Comparators
Selectable propagation delay versus current consumption
Selectable hysteresis
No
Small
Large
Analog comparator output available on pin
Flexible input selection
All pins on the port
Output from the DAC
Bandgap reference voltage
A 64-level programmable voltage scaler of the internal VCC voltage
Interrupt and event generation on:
Rising edge
Falling edge
Toggle
Window function interrupt and event generation on:
Signal above window
Signal inside window
Signal below window
Constant current source with configurable output pin selection
28.2 Overview
The analog comparator (AC) compares the voltage levels on two inputs and gives a digital output based on this
comparison. The analog comparator may be configured to generate interrupt requests and/or events upon several
different combinations of input change.
Two important properties of the analog comparator’s dynamic behavior are: hysteresis and propagation delay. Both of
these parameters may be adjusted in order to achieve the optimal operation for each application.
The input selection includes analog port pins, several internal signals, and a 64-level programmable voltage scaler. The
analog comparator output state can also be output on a pin for use by external devices.
A constant current source can be enabled and output on a selectable pin. This can be used to replace, for example,
external resistors used to charge capacitors in capacitive touch sensing applications.
The analog comparators are always grouped in pairs on each port. These are called analog comparator 0 (AC0) and
analog comparator 1 (AC1). They have identical behavior, but separate control registers. Used as pair, they can be set in
window mode to compare a signal to a voltage range instead of a voltage level.
PORTA and PORTB each has one AC pair. Notations are ACA and ACB, respectively.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 53
8067O–AVR–06/2013
Figure 28-1. Analog comparator overview
The window function is realized by connecting the external inputs of the two analog comparators in a pair as shown in
Figure 28-2.
Figure 28-2. Analog comparator window function
ACnMUXCTRL ACnCTRL
Interrupt
Mode
Enable
Enable
Hysteresis
Hysteresis
AC1OUT
WINCTRL
Interrupt
Sensititivity
Control
&
Window
Function
Events
Interrupts
AC0OUT
Pin Input
Pin Input
Pin Input
Pin Input
Voltage
Scaler
DAC
Bandgap
+
-
+
-
AC0
+
-
AC1
+
-
Input signal
Upper limit of window
Lower limit of window
Interrupt
sensitivity
control
Interrupts
Events[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 54
8067O–AVR–06/2013
29. Programming and Debugging
29.1 Features
Programming
External programming through PDI or JTAG interfaces
Minimal protocol overhead for fast operation
Built-in error detection and handling for reliable operation
Boot loader support for programming through any communication interface
Debugging
Nonintrusive, real-time, on-chip debug system
No software or hardware resources required from device except pin connection
Program flow control
Go, Stop, Reset, Step Into, Step Over, Step Out, Run-to-Cursor
Unlimited number of user program breakpoints
Unlimited number of user data breakpoints, break on:
Data location read, write, or both read and write
Data location content equal or not equal to a value
Data location content is greater or smaller than a value
Data location content is within or outside a range
No limitation on device clock frequency
Program and Debug Interface (PDI)
Two-pin interface for external programming and debugging
Uses the Reset pin and a dedicated pin
No I/O pins required during programming or debugging
JTAG interface
Four-pin, IEEE Std. 1149.1 compliant interface for programming and debugging
Boundary scan capabilities according to IEEE Std. 1149.1 (JTAG)
29.2 Overview
The Program and Debug Interface (PDI) is an Atmel proprietary interface for external programming and on-chip
debugging of a device.
The PDI supports fast programming of nonvolatile memory (NVM) spaces; flash, EEPOM, fuses, lock bits, and the user
signature row.
Debug is supported through an on-chip debug system that offers nonintrusive, real-time debug. It does not require any
software or hardware resources except for the device pin connection. Using the Atmel tool chain, it offers complete
program flow control and support for an unlimited number of program and complex data breakpoints. Application debug
can be done from a C or other high-level language source code level, as well as from an assembler and disassembler
level.
Programming and debugging can be done through two physical interfaces. The primary one is the PDI physical layer,
which is available on all devices. This is a two-pin interface that uses the Reset pin for the clock input (PDI_CLK) and one
other dedicated pin for data input and output (PDI_DATA). A JTAG interface is also available on most devices, and this
can be used for programming and debugging through the four-pin JTAG interface. The JTAG interface is IEEE Std.
1149.1 compliant, and supports boundary scan. Any external programmer or on-chip debugger/emulator can be directly
connected to either of these interfaces. Unless otherwise stated, all references to the PDI assume access through the
PDI physical layer.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 55
8067O–AVR–06/2013
30. Pinout and Pin Functions
The pinout of XMEGA A1 is shown in “Pinout/Block Diagram” on page 3. In addition to general I/O functionality, each pin
may have several functions. This will depend on which peripheral is enabled and connected to the actual pin. Only one of
the alternate pin functions can be used at time.
30.1 Alternate Pin Function Description
The tables below shows the notation for all pin functions available and describes its function.
30.1.1 Operation/Power Supply
30.1.2 Port Interrupt functions
30.1.3 Analog functions
30.1.4 EBI functions
VCC Digital supply voltage
AVCC Analog supply voltage
GND Ground
SYNC Port pin with full synchronous and limited asynchronous interrupt function
ASYNC Port pin with full synchronous and full asynchronous interrupt function
ACn Analog Comparator input pin n
AC0OUT Analog Comparator 0 Output
ADCn Analog to Digital Converter input pin n
DACn Digital to Analog Converter output pin n
AREF Analog Reference input pin
An Address line n
Dn Data line n
CSn Chip Select n
ALEn Address Latch Enable pin n (SRAM)
RE Read Enable (SRAM)
WE External Data Memory Write (SRAM /SDRAM)
BAn Bank Address (SDRAM)
CAS Column Access Strobe (SDRAM)
CKE SDRAM Clock Enable (SDRAM)[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 56
8067O–AVR–06/2013
30.1.5 Timer/Counter and AWEX functions
30.1.6 Communication functions
30.1.7 Oscillators, Clock and Event
CLK SDRAM Clock (SDRAM)
DQM Data Mask Signal/Output Enable (SDRAM)
RAS Row Access Strobe (SDRAM)
2P 2 Port Interface
3P 3 Port Interface
OCnx Output Compare Channel x for Timer/Counter n
OCnx Inverted Output Compare Channel x for Timer/Counter n
OCnxLS Output Compare Channel x Low Side for Timer/Counter n
OCnxHS Output Compare Channel x High Side for Timer/Counter n
SCL Serial Clock for TWI
SDA Serial Data for TWI
SCLIN Serial Clock In for TWI when external driver interface is enabled
SCLOUT Serial Clock Out for TWI when external driver interface is enabled
SDAIN Serial Data In for TWI when external driver interface is enabled
SDAOUT Serial Data Out for TWI when external driver interface is enabled
XCKn Transfer Clock for USART n
RXDn Receiver Data for USART n
TXDn Transmitter Data for USART n
SS Slave Select for SPI
MOSI Master Out Slave In for SPI
MISO Master In Slave Out for SPI
SCK Serial Clock for SPI
n Timer Oscillator pin n
XTALn Input/Output for inverting Oscillator pin n
CLKOUT Peripheral Clock Output
EVOUT Event Channel 0 Output[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 57
8067O–AVR–06/2013
30.1.8 Debug/System functions
RESET Reset pin
PDI_CLK Program and Debug Interface Clock pin
PDI_DATA Program and Debug Interface Data pin
TCK JTAG Test Clock
TDI JTAG Test Data In
TDO JTAG Test Data Out
TMS JTAG Test Mode Select[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 58
8067O–AVR–06/2013
30.2 Alternate Pin Functions
The tables below show the primary/default function for each pin on a port in the first column, the pin number in the
second column, and then all alternate pin functions in the remaining columns. The head row shows what peripheral that
enable and use the alternate pin functions.
Table 30-1. Port A - Alternate functions.
Table 30-2. Port B - Alternate functions.
Table 30-3. Port C - Alternate functions.
PORT A PIN # INTERRUPT ADCA
POS
ADCA
NEG
ADCA
GAINPOS
ADCA
GAINNEG
ACA
POS
ACA
NEG
ACA
OUT
DACA REFA
GND 93
AVCC 94
PA0 95 SYNC ADC0 ADC0 ADC0 AC0 AC0 AREF
PA1 96 SYNC ADC1 ADC1 ADC1 AC1 AC1
PA2 97 SYNC/ASYNC ADC2 ADC2 ADC2 AC2 DAC0
PA3 98 SYNC ADC3 ADC3 ADC3 AC3 AC3 DAC1
PA4 99 SYNC ADC4 ADC4 ADC4 AC4
PA5 100 SYNC ADC5 ADC5 ADC5 AC5 AC5
PA6 1 SYNC ADC6 ADC6 ADC6 AC6
PA7 2 SYNC ADC7 ADC7 ADC7 AC7 AC0OUT
PORT B PIN # INTERRUPT ADCB
POS
ADCB
NEG
ADCB
GAINPOS
ADCB
GAINNEG
ACB
POS
ACB
NEG
ACB
OUT
DACB REFB JTAG
GND 3
AVCC 4
PB0 5 SYNC ADC0 ADC0 ADC0 AC0 AC0 AREF
PB1 6 SYNC ADC1 ADC1 ADC1 AC1 AC1
PB2 7 SYNC/ASYNC ADC2 ADC2 ADC2 AC2 DAC0
PB3 8 SYNC ADC3 ADC3 ADC3 AC3 AC3 DAC1
PB4 9 SYNC ADC4 ADC4 ADC4 AC4 TMS
PB5 10 SYNC ADC5 ADC5 ADC5 AC5 AC5 TDI
PB6 11 SYNC ADC6 ADC6 ADC6 AC6 TCK
PB7 12 SYNC ADC7 ADC7 ADC7 AC7 AC0OUT TDO
PORT C PIN # INTERRUPT TCC0 AWEXC TCC1 USARTC0 USARTC1 SPIC TWIC CLOCKOUT EVENTOUT
GND 13
VCC 14
PC0 15 SYNC OC0A OC0ALS SDA
PC1 16 SYNC OC0B OC0AHS XCK0 SCL
PC2 17 SYNC/ASYNC OC0C OC0BLS RXD0[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 59
8067O–AVR–06/2013
Table 30-4. Port D - Alternate functions.
Table 30-5. Port E - Alternate functions.
Table 30-6. Port F - Alternate functions.
PC3 18 SYNC OC0D OC0BHS TXD0
PC4 19 SYNC OC0CLS OC1A SS
PC5 20 SYNC OC0CHS OC1B XCK1 MOSI
PC6 21 SYNC OC0DLS RXD1 MISO
PC7 22 SYNC OC0DHS TXD1 SCK CLKOUT EVOUT
PORT D PIN # INTERRUPT TCD0 TCD1 USARTD0 USARTD1 SPID TWID CLOCKOUT EVENTOUT
GND 23
VCC 24
PD0 25 SYNC OC0A SDA
PD1 26 SYNC OC0B XCK0 SCL
PD2 27 SYNC/ASYNC OC0C RXD0
PD3 28 SYNC OC0D TXD0
PD4 29 SYNC OC1A SS
PD5 30 SYNC OC1B XCK1 MOSI
PD6 31 SYNC RXD1 MISO
PD7 32 SYNC TXD1 SCK CLKOUT EVOUT
PORT E PIN # INTERRUPT TCE0 AWEXE TCE1 USARTE0 USARTE1 SPIE TWIE CLOCKOUT EVENTOUT
GND 33
VCC 34
PE0 35 SYNC OC0A OC0ALS SDA
PE1 36 SYNC OC0B OC0AHS XCK0 SCL
PE2 37 SYNC/ASYNC OC0C OC0BLS RXD0
PE3 38 SYNC OC0D OC0BHS TXD0
PE4 39 SYNC OC0CLS OC1A SS
PE5 40 SYNC OC0CHS OC1B XCK1 MOSI
PE6 41 SYNC OC0DLS RXD1 MISO
PE7 42 SYNC OC0DHS TXD1 SCK CLKOUT EVOUT
PORT F PIN # INTERRUPT TCF0 TCF1 USARTF0 USARTF1 SPIF TWIF
GND 43
VCC 44
PF0 45 SYNC OC0A SDA
PORT C PIN # INTERRUPT TCC0 AWEXC TCC1 USARTC0 USARTC1 SPIC TWIC CLOCKOUT EVENTOUT[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 60
8067O–AVR–06/2013
Table 30-7. Port H - Alternate functions.
Table 30-8. Port J - Alternate functions.
PF1 46 SYNC OC0B XCK0 SCL
PF2 47 SYNC/ASYNC OC0C RXD0
PF3 48 SYNC OC0D TXD0
PF4 49 SYNC OC1A SS
PF5 50 SYNC OC1B XCK1 MOSI
PF6 51 SYNC RXD1 MISO
PF7 52 SYNC TXD1 SCK
PORT H PIN # INTERRUPT SDRAM 3P SRAM ALE1 3P SRAM ALE12 3P LPC ALE1 3P LPC ALE1 2P LPC ALE12 2P
GND 53
VCC 54
PH0 55 SYNC WE WE WE WE WE WE
PH1 56 SYNC CAS RE RE RE RE RE
PH2 57 SYNC/ASYNC RAS ALE1 ALE1 ALE1 ALE1 ALE1
PH3 58 SYNC DQM ALE2 ALE2
PH4 59 SYNC BA0 CS0/A16 CS0 CS0/A16 CS0 CS0/A16
PH5 60 SYNC BA1 CS1/A17 CS1 CS1/A17 CS1 CS1/A17
PH6 61 SYNC CKE CS2/A18 CS2 CS2/A18 CS2 CS2/A18
PH7 62 SYNC CLK CS3/A19 CS3 CS3/A19 CS3 CS3/A19
PORT J PIN # INTERRUPT SDRAM 3P SRAM ALE1 3P SRAM ALE12 3P LPC ALE1 3P LPC ALE1 2P LPC ALE12 2P
GND 63
VCC 64
PJ0 65 SYNC D0 D0 D0 D0/A0 D0/A0 D0/A0/A8
PJ1 66 SYNC D1 D1 D1 D1/A1 D1/A1 D1/A1/A9
PJ2 67 SYNC/ASYNC D2 D2 D2 D2/A2 D2/A2 D2/A2/A10
PJ3 68 SYNC D3 D3 D3 D3/A3 D3/A3 D3/A3/A11
PJ4 69 SYNC A8 D4 D4 D4/A4 D4/A4 D4/A4/A12
PJ5 70 SYNC A9 D5 D5 D5/A5 D5/A5 D5/A5/A13
PJ6 71 SYNC A10 D6 D6 D6/A6 D6/A6 D6/A6/A14
PJ7 72 SYNC A11 D7 D7 D7/A7 D7/A7 D7/A7/A15
PORT F PIN # INTERRUPT TCF0 TCF1 USARTF0 USARTF1 SPIF TWIF[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 61
8067O–AVR–06/2013
Table 30-9. Port K - Alternate functions.
Table 30-10. Port Q - Alternate functions.
Table 30-11. Port R - Alternate functions.
PORT K PIN # INTERRUPT SDRAM 3P SRAM ALE1 3P SRAM ALE12 3P LPC ALE1 3P LPC ALE1 2P LPC ALE12 2P
GND 73
VCC 74
PK0 75 SYNC A0 A0/A8 A0/A8/A16 A8
PK1 76 SYNC A1 A1/A9 A1/A9/A17 A9
PK2 77 SYNC/ASYNC A2 A2/A10 A2/A10/A18 A10
PK3 78 SYNC A3 A3/A11 A3/A11/A19 A11
PK4 79 SYNC A4 A4/A12 A4/A12/A20 A12
PK5 80 SYNC A5 A5/A13 A5/A13/A21 A13
PK6 81 SYNC A6 A6/A14 A6/A14/A22 A14
PK7 82 SYNC A7 A7/A15 A7/A15/A23 A15
PORT Q PIN # INTERRUPT
VCC 83
GND 84
PQ0 85 SYNC TOSC1 (Input)
PQ1 86 SYNC TOSC2 (Output)
PQ2 87 SYNC/ASYNC
PQ3 88 SYNC
PORT R PIN # INTERRUPT PDI XTAL
PDI 89 PDI_DATA
RESET 90 PDI_CLOCK
PRO 91 SYNC XTAL2
PR1 92 SYNC XTAL1[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 62
8067O–AVR–06/2013
31. Peripheral Module Address Map
The address maps show the base address for each peripheral and module in XMEGA A1. For complete register
description and summary for each peripheral module, refer to the XMEGA A Manual.
Table 31-1. Peripheral Module Address Map
Base Address Name Description
0x0000 GPIO General Purpose IO Registers
0x0010 VPORT0 Virtual Port 0
0x0014 VPORT1 Virtual Port 1
0x0018 VPORT2 Virtual Port 2
0x001C VPORT3 Virtual Port 3
0x0030 CPU CPU
0x0040 CLK Clock Control
0x0048 SLEEP Sleep Controller
0x0050 OSC Oscillator Control
0x0060 DFLLRC32M DFLL for the 32 MHz Internal RC Oscillator
0x0068 DFLLRC2M DFLL for the 2 MHz RC Oscillator
0x0070 PR Power Reduction
0x0078 RST Reset Controller
0x0080 WDT Watch-Dog Timer
0x0090 MCU MCU Control
0x00A0 PMIC Programmable Multilevel Interrupt Controller
0x00B0 PORTCFG Port Configuration
0x00C0 AES AES Module
0x0100 DMA DMA Controller
0x0180 EVSYS Event System
0x01C0 NVM Non Volatile Memory (NVM) Controller
0x0200 ADCA Analog to Digital Converter on port A
0x0240 ADCB Analog to Digital Converter on port B
0x0300 DACA Digital to Analog Converter on port A
0x0320 DACB Digital to Analog Converter on port B
0x0380 ACA Analog Comparator pair on port A
0x0390 ACB Analog Comparator pair on port B
0x0400 RTC Real Time Counter
0x0440 EBI External Bus Interface
0x0480 TWIC Two Wire Interface on port C
0x0490 TWID Two Wire Interface on port D[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 63
8067O–AVR–06/2013
0x04A0 TWIE Two Wire Interface on port E
0x04B0 TWIF Two Wire Interface on port F
0x0600 PORTA Port A
0x0620 PORTB Port B
0x0640 PORTC Port C
0x0660 PORTD Port D
0x0680 PORTE Port E
0x06A0 PORTF Port F
0x06E0 PORTH Port H
0x0700 PORTJ Port J
0x0720 PORTK Port K
0x07C0 PORTQ Port Q
0x07E0 PORTR Port R
0x0800 TCC0 Timer/Counter 0 on port C
0x0840 TCC1 Timer/Counter 1 on port C
0x0880 AWEXC Advanced Waveform Extension on port C
0x0890 HIRESC High Resolution Extension on port C
0x08A0 USARTC0 USART 0 on port C
0x08B0 USARTC1 USART 1 on port C
0x08C0 SPIC Serial Peripheral Interface on port C
0x08F8 IRCOM Infrared Communication Module
0x0900 TCD0 Timer/Counter 0 on port D
0x0940 TCD1 Timer/Counter 1 on port D
0x0990 HIRESD High Resolution Extension on port D
0x09A0 USARTD0 USART 0 on port D
0x09B0 USARTD1 USART 1 on port D
0x09C0 SPID Serial Peripheral Interface on port D
0x0A00 TCE0 Timer/Counter 0 on port E
0x0A40 TCE1 Timer/Counter 1 on port E
0x0A80 AWEXE Advanced Waveform Extension on port E
0x0A90 HIRESE High Resolution Extension on port E
0x0AA0 USARTE0 USART 0 on port E
0x0AB0 USARTE1 USART 1 on port E
0x0AC0 SPIE Serial Peripheral Interface on port E
0x0B00 TCF0 Timer/Counter 0 on port F
Base Address Name Description[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 64
8067O–AVR–06/2013
0x0B40 TCF1 Timer/Counter 1 on port F
0x0B90 HIRESF High Resolution Extension on port F
0x0BA0 USARTF0 USART 0 on port F
0x0BB0 USARTF1 USART 1 on port F
0x0BC0 SPIF Serial Peripheral Interface on port F
Base Address Name Description[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 65
8067O–AVR–06/2013
32. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
Arithmetic and Logic Instructions
ADD Rd, Rr Add without Carry Rd Rd + Rr Z,C,N,V,S,H 1
ADC Rd, Rr Add with Carry Rd Rd + Rr + C Z,C,N,V,S,H 1
ADIW Rd, K Add Immediate to Word Rd Rd + 1:Rd + K Z,C,N,V,S 2
SUB Rd, Rr Subtract without Carry Rd Rd - Rr Z,C,N,V,S,H 1
SUBI Rd, K Subtract Immediate Rd Rd - K Z,C,N,V,S,H 1
SBC Rd, Rr Subtract with Carry Rd Rd - Rr - C Z,C,N,V,S,H 1
SBCI Rd, K Subtract Immediate with Carry Rd Rd - K - C Z,C,N,V,S,H 1
SBIW Rd, K Subtract Immediate from Word Rd + 1:Rd Rd + 1:Rd - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Rd Rd Rr Z,N,V,S 1
ANDI Rd, K Logical AND with Immediate Rd Rd K Z,N,V,S 1
OR Rd, Rr Logical OR Rd Rd v Rr Z,N,V,S 1
ORI Rd, K Logical OR with Immediate Rd Rd v K Z,N,V,S 1
EOR Rd, Rr Exclusive OR Rd Rd Rr Z,N,V,S 1
COM Rd One’s Complement Rd $FF - Rd Z,C,N,V,S 1
NEG Rd Two’s Complement Rd $00 - Rd Z,C,N,V,S,H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V,S 1
CBR Rd,K Clear Bit(s) in Register Rd Rd ($FFh - K) Z,N,V,S 1
INC Rd Increment Rd Rd + 1 Z,N,V,S 1
DEC Rd Decrement Rd Rd - 1 Z,N,V,S 1
TST Rd Test for Zero or Minus Rd Rd Rd Z,N,V,S 1
CLR Rd Clear Register Rd Rd Rd Z,N,V,S 1
SER Rd Set Register Rd $FF None 1
MUL Rd,Rr Multiply Unsigned R1:R0 Rd x Rr (UU) Z,C 2
MULS Rd,Rr Multiply Signed R1:R0 Rd x Rr (SS) Z,C 2
MULSU Rd,Rr Multiply Signed with Unsigned R1:R0 Rd x Rr (SU) Z,C 2
FMUL Rd,Rr Fractional Multiply Unsigned R1:R0 Rd x Rr<<1 (UU) Z,C 2
FMULS Rd,Rr Fractional Multiply Signed R1:R0 Rd x Rr<<1 (SS) Z,C 2
FMULSU Rd,Rr Fractional Multiply Signed with Unsigned R1:R0 Rd x Rr<<1 (SU) Z,C 2
DES K Data Encryption if (H = 0) then R15:R0
else if (H = 1) then R15:R0
Encrypt(R15:R0, K)
Decrypt(R15:R0, K)
1/2
Branch Instructions
RJMP k Relative Jump PC PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC(15:0)
PC(21:16)
Z,
0
None 2
EIJMP Extended Indirect Jump to (Z) PC(15:0)
PC(21:16)
Z,
EIND
None 2
JMP k Jump PC k None 3[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 66
8067O–AVR–06/2013
RCALL k Relative Call Subroutine PC PC + k + 1 None 2 / 3(1)
ICALL Indirect Call to (Z) PC(15:0)
PC(21:16)
Z,
0
None 2 / 3(1)
EICALL Extended Indirect Call to (Z) PC(15:0)
PC(21:16)
Z,
EIND
None 3(1)
CALL k call Subroutine PC k None 3 / 4(1)
RET Subroutine Return PC STACK None 4 / 5(1)
RETI Interrupt Return PC STACK I 4 / 5(1)
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1 / 2 / 3
CP Rd,Rr Compare Rd - Rr Z,C,N,V,S,H 1
CPC Rd,Rr Compare with Carry Rd - Rr - C Z,C,N,V,S,H 1
CPI Rd,K Compare with Immediate Rd - K Z,C,N,V,S,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b) = 0) PC PC + 2 or 3 None 1 / 2 / 3
SBRS Rr, b Skip if Bit in Register Set if (Rr(b) = 1) PC PC + 2 or 3 None 1 / 2 / 3
SBIC A, b Skip if Bit in I/O Register Cleared if (I/O(A,b) = 0) PC PC + 2 or 3 None 2 / 3 / 4
SBIS A, b Skip if Bit in I/O Register Set If (I/O(A,b) =1) PC PC + 2 or 3 None 2 / 3 / 4
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC PC + k + 1 None 1 / 2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC PC + k + 1 None 1 / 2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1 / 2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1 / 2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1 / 2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1 / 2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1 / 2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1 / 2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1 / 2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1 / 2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1 / 2
BRLT k Branch if Less Than, Signed if (N V= 1) then PC PC + k + 1 None 1 / 2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1 / 2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1 / 2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1 / 2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1 / 2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1 / 2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1 / 2
BRIE k Branch if Interrupt Enabled if (I = 1) then PC PC + k + 1 None 1 / 2
BRID k Branch if Interrupt Disabled if (I = 0) then PC PC + k + 1 None 1 / 2
Data Transfer Instructions
MOV Rd, Rr Copy Register Rd Rr None 1
MOVW Rd, Rr Copy Register Pair Rd+1:Rd Rr+1:Rr None 1
Mnemonics Operands Description Operation Flags #Clocks[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 67
8067O–AVR–06/2013
LDI Rd, K Load Immediate Rd K None 1
LDS Rd, k Load Direct from data space Rd (k) None 2(1)(2)
LD Rd, X Load Indirect Rd (X) None 1(1)(2)
LD Rd, X+ Load Indirect and Post-Increment Rd
X
(X)
X + 1
None 1(1)(2)
LD Rd, -X Load Indirect and Pre-Decrement X X - 1,
Rd (X)
X - 1
(X)
None 2(1)(2)
LD Rd, Y Load Indirect Rd (Y) (Y) None 1(1)(2)
LD Rd, Y+ Load Indirect and Post-Increment Rd
Y
(Y)
Y + 1
None 1(1)(2)
LD Rd, -Y Load Indirect and Pre-Decrement Y
Rd
Y - 1
(Y)
None 2(1)(2)
LDD Rd, Y+q Load Indirect with Displacement Rd (Y + q) None 2(1)(2)
LD Rd, Z Load Indirect Rd (Z) None 1(1)(2)
LD Rd, Z+ Load Indirect and Post-Increment Rd
Z
(Z),
Z+1
None 1(1)(2)
LD Rd, -Z Load Indirect and Pre-Decrement Z
Rd
Z - 1,
(Z)
None 2(1)(2)
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2(1)(2)
STS k, Rr Store Direct to Data Space (k) Rd None 2(1)
ST X, Rr Store Indirect (X) Rr None 1(1)
ST X+, Rr Store Indirect and Post-Increment (X)
X
Rr,
X + 1
None 1(1)
ST -X, Rr Store Indirect and Pre-Decrement X
(X)
X - 1,
Rr
None 2(1)
ST Y, Rr Store Indirect (Y) Rr None 1(1)
ST Y+, Rr Store Indirect and Post-Increment (Y)
Y
Rr,
Y + 1
None 1(1)
ST -Y, Rr Store Indirect and Pre-Decrement Y
(Y)
Y - 1,
Rr
None 2(1)
STD Y+q, Rr Store Indirect with Displacement (Y + q) Rr None 2(1)
ST Z, Rr Store Indirect (Z) Rr None 1(1)
ST Z+, Rr Store Indirect and Post-Increment (Z)
Z
Rr
Z + 1
None 1(1)
ST -Z, Rr Store Indirect and Pre-Decrement Z Z - 1 None 2(1)
STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2(1)
LPM Load Program Memory R0 (Z) None 3
LPM Rd, Z Load Program Memory Rd (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Increment Rd
Z
(Z),
Z + 1
None 3
ELPM Extended Load Program Memory R0 (RAMPZ:Z) None 3
ELPM Rd, Z Extended Load Program Memory Rd (RAMPZ:Z) None 3
ELPM Rd, Z+ Extended Load Program Memory and PostIncrement
Rd
Z
(RAMPZ:Z),
Z + 1
None 3
SPM Store Program Memory (RAMPZ:Z) R1:R0 None -
Mnemonics Operands Description Operation Flags #Clocks[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 68
8067O–AVR–06/2013
SPM Z+ Store Program Memory and Post-Increment
by 2
(RAMPZ:Z)
Z
R1:R0,
Z + 2
None -
IN Rd, A In From I/O Location Rd I/O(A) None 1
OUT A, Rr Out To I/O Location I/O(A) Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 1(1)
POP Rd Pop Register from Stack Rd STACK None 2(1)
Bit and Bit-test Instructions
LSL Rd Logical Shift Left Rd(n+1)
Rd(0)
C
Rd(n),
0,
Rd(7)
Z,C,N,V,H 1
LSR Rd Logical Shift Right Rd(n)
Rd(7)
C
Rd(n+1),
0,
Rd(0)
Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)
Rd(n+1)
C
C,
Rd(n),
Rd(7)
Z,C,N,V,H 1
ROR Rd Rotate Right Through Carry Rd(7)
Rd(n)
C
C,
Rd(n+1),
Rd(0)
Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0) Rd(7..4) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
SBI A, b Set Bit in I/O Register I/O(A, b) 1 None 1
CBI A, b Clear Bit in I/O Register I/O(A, b) 0 None 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) T None 1
SEC Set Carry C 1 C 1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1 N 1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1 Z 1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1 I 1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1 S 1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Two’s Complement Overflow V 1 V 1
CLV Clear Two’s Complement Overflow V 0 V 1
SET Set T in SREG T 1 T 1
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1 H 1
CLH Clear Half Carry Flag in SREG H 0 H 1
Mnemonics Operands Description Operation Flags #Clocks[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 69
8067O–AVR–06/2013
Notes: 1. Cycle times for Data memory accesses assume internal memory accesses, and are not valid for accesses via the external RAM interface.
2. One extra cycle must be added when accessing Internal SRAM.
MCU Control Instructions
BREAK Break (See specific descr. for BREAK) None 1
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep) None 1
WDR Watchdog Reset (see specific descr. for WDR) None 1
Mnemonics Operands Description Operation Flags #Clocks[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 70
8067O–AVR–06/2013
33. Packaging information
33.1 100A
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
100A, 100-lead, 14 x 14 mm Body Size, 1.0 mm Body Thickness,
0.5 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP) 100A D
2010-10-20
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
e E1 E
B
A – – 1.20
A1 0.05 – 0.15
A2 0.95 1.00 1.05
D 15.75 16.00 16.25
D1 13.90 14.00 14.10 Note 2
E 15.75 16.00 16.25
E1 13.90 14.00 14.10 Note 2
B 0.17 – 0.27
C 0.09 – 0.20
L 0.45 – 0.75
e 0.50 TYP
Notes:
1. This package conforms to JEDEC reference MS-026, Variation AED.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.08 mm maximum.
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 71
8067O–AVR–06/2013
33.2 100C1
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
100C1, 100-ball, 9 x 9 x 1.2 mm Body, Ball Pitch 0.80 mm
Chip Array BGA Package (CBGA) 100C1 A
5/25/06
TOP VIEW
SIDE VIEW
BOTTOM VIEW
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A 1.10 – 1.20
A1 0.30 0.35 0.40
D 8.90 9.00 9.10
E 8.90 9.00 9.10
D1 7.10 7.20 7.30
E1 7.10 7.20 7.30
Øb 0.35 0.40 0.45
e 0.80 TYP
Marked A1 Identifier
8 7 6 5 4 3 2 1
A
B
C
D
E
9
F
G
H
I
J
10
0.90 TYP
0.90 TYP
A1 Corner
0.12 Z
E
D
e
e
Øb
A
A1
E1
D1[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 72
8067O–AVR–06/2013
33.3 100C2
TITLE GPC DRAWING NO. REV.
Package Drawing Contact:
packagedrawings@atmel.com CIF A 100C2
100C2, 100-ball (10 x 10 Array), 0.65 mm Pitch,
7.0 x 7.0 x 1.0 mm, Very Thin, Fine-Pitch
Ball Grid Array Package (VFBGA)
12/23/08
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A – – 1.00
A1 0.20 – –
A2 0.65 – –
D 6.90 7.00 7.10
D1 5.85 BSC
E 6.90 7.00 7.10
E1 5.85 BSC
b 0.30 0.35 0.40
e 0.65 BSC
TOP VIEW
SIDE VIEW
A1 BALL ID
J
I
H
G
F
E
D
C
B
A
12 3 4 5 6 7 8 9 10
A
A1
A2
D
E
0.10
E1
D1
100 - Ø0.35 ± 0.05
e
A1 BALL CORNER
BOTTOM VIEW
b e[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 73
8067O–AVR–06/2013
34. Electrical Characteristics
34.1 Absolute Maximum Ratings*
34.2 DC Characteristics
Table 34-1. Current consumption.
Operating Temperature . . . . . . . . . . . -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only
and functional operation of the device at these
or other conditions beyond those indicated in
the operational sections of this specification is
not implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature . . . . . . . . . . . . . -65C to +150°C
Voltage on any Pin with respect to Ground-0.5V to VCC+0.5V
Maximum Operating Voltage . . . . . . . . . . . . . . . . 3.6V
DC Current per I/O Pin. . . . . . . . . . . . . . . . . . 20.0 mA
DC Current VCC and GND Pins . . . . . . . . . . 200.0 mA
Symbol Parameter Condition Min Typ Max Units
ICC
Active mode(1)
1 MHz, Ext. Clk
VCC = 1.8V 365
µA
VCC = 3.0V 790
2 MHz, Ext. Clk
VCC = 1.8V 690 800
VCC = 3.0V 1400 1600
32 MHz, Ext. Clk VCC = 3.0V 18.35 20 mA
Idle mode(1)
1 MHz, Ext. Clk
VCC = 1.8V 135
µA
VCC = 3.0V 255
2 MHz, Ext. Clk
VCC = 1.8V 270 380
VCC = 3.0V 510 650
32 MHz, Ext. Clk VCC = 3.0V 8.15 9.2 mA
Power-down mode
All Functions Disabled VCC = 3.0V 0.1
µA
All Functions Disabled, T = 85°C VCC = 3.0V 2 5
ULP, WDT, Sampled BOD
VCC = 1.8V 0.5
VCC = 3.0V 0.6
ULP, WDT, Sampled BOD, T=85°C VCC = 3.0V 3 10
Power-save mode
RTC 1 kHz from Low Power 32 kHz
VCC = 1.8V 0.52
VCC = 3.0V 0.55 µA
RTC from Low Power 32 kHz VCC = 3.0V 1.16[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 74
8067O–AVR–06/2013
Note: 1. All Power Reduction Registers set. Typical numbers measured at T = 25°C if nothing else is specified.
2. with no prescaling
Module current consumption(2)
ICC
RC32M 395
µA
RC32M w/DFLL Internal 32.768 kHz oscillator as DFLL source TBD
RC2M 120
RC2M w/DFLL Internal 32.768 kHz oscillator as DFLL source 155
RC32K 30
PLL Multiplication factor = 10x 195
Watchdog normal mode TBD
BOD Continuous mode 120
BOD Sampled mode 1
Internal 1.00 V ref 85
Temperature reference 80
RTC with int. 32 kHz RC as
source No prescaling 30
RTC with ULP as source No prescaling 1
ADC 250 kS/s - Int. 1V Ref 3.6
DAC Normal Mode 1000 kS/s, Single channel, Int. 1V Ref 1.8 mA
DAC Low-Power Mode 1000 KS/s, Single channel, Int. 1V Ref 1
AC High-speed 220
µA
AC Low-power 110
USART Rx and Tx enabled, 9600 BAUD 7.5
DMA 180
Timer/Counter Prescaler DIV1 18
AES 195
Flash/EEPROM
Programming
Vcc = 2V 20
mA
Vcc = 3V 30
Symbol Parameter Condition Min Typ Max Units[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 75
8067O–AVR–06/2013
34.3 Speed
Table 34-2. Operating voltage and frequency.
The maximum CPU clock frequency of the XMEGA A1 devices is depending on VCC. As shown in Figure 34-1 on page
75 the Frequency vs. VCC curve is linear between 1.8V < VCC < 2.7V.
Figure 34-1. Maximum Frequency vs. Vcc
Symbol Parameter Condition Min Typ Max Units
ClkCPU CPU clock frequency
VCC = 1.6V 0 12
MHz
VCC = 1.8V 0 12
VCC = 2.7V 0 32
VCC = 3.6V 0 32
1.8
12
32
MHz
1.6 2.7 3.6 V
Safe Operating Area[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 76
8067O–AVR–06/2013
34.4 Flash and EEPROM Memory Characteristics
Table 34-3. Endurance and data retention.
Table 34-4. Programming time.
Notes: 1. Programming is timed from the internal 2 MHz oscillator.
2. EEPROM is not erased if the EESAVE fuse is programmed.
34.5 ADC Characteristics
Table 34-5. ADC characteristics
Symbol Parameter Condition Min Typ Max Units
Flash
Write/Erase cycles
25°C 10K
Cycle
85°C 10K
Data retention
25°C 100
Year
55°C 25
EEPROM
Write/Erase cycles
25°C 80K
Cycle
85°C 30K
Data retention
25°C 100
Year
55°C 25
Symbol Parameter Condition Min Typ(1) Max Units
Chip Erase Flash, EEPROM(2) and SRAM Erase 40
ms
Flash
Page Erase 4
Page Write 6
Page WriteAutomatic Page Erase and Write 12
EEPROM
Page Erase 4
Page Write 6
Page Write Automatic Page Erase and Write 12
Symbol Parameter Condition Min Typ Max Units
RES Resolution Programmable: 8/12 8 12 12 Bits
INL Integral Non-Linearity 500 kS/s -5 <±1 5 LSB
DNL Differential Non-Linearity 500 kS/s < ±0.75 LSB
Gain Error ±10 mV
Offset Error ±2 mV
ADCclk ADC Clock frequency Max is 1/4 of
Peripheral Clock
VCC2.0V 2000
kHz
VCC<2.0V 500[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 77
8067O–AVR–06/2013
Table 34-6. ADC gain stage characteristics.
Conversion rate
VCC2.0V 2000
ksps
VCC<2.0V 500
Conversion time
(propagation delay)
(RES+2)/2+GAIN
RES = 8 or 12, GAIN = 0 or 1
5 7 8
ADCclk
cycles
Sampling Time 1/2 ADCclk cycle 0.25 µS
Conversion range 0 VREF V
AVCC Analog Supply Voltage Vcc-0.3 Vcc+0.3 V
VREF Reference voltage 1.0 Vcc-0.6 V
Input bandwidth
VCC2.0V 2000
kHz
VCC<2.0V 500
INT1V Internal 1.00V reference 1.00 V
INTVCC Internal VCC/1.6 VCC/1.6 V
SCALEDVCC Scaled internal VCC/10 input VCC/10 V
RAREF Reference input resistance >10 M
Start-up time 12 24
ADCclk
cycles
Internal input sampling speed Temp. sensor, VCC/10, Bandgap 100 ksps
Symbol Parameter Condition Min Typ Max Units
Gain error 1 to 64 gain < ±1 %
Offset error < ±1 mV
Vrms Noise level at input 64x gain
VREF = Int. 1V 0.12
mV
VREF = Ext. 2V 0.06
Clock rate Same as ADC 1000 kHz
Symbol Parameter Condition Min Typ Max Units[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 78
8067O–AVR–06/2013
34.6 DAC Characteristics
Table 34-7. DAC characteristics.
34.7 Analog Comparator Characteristics
Table 34-8. Analog Comparator characteristics.
34.8 Bandgap Characteristics
Table 34-9. Bandgap voltage characteristics.
Symbol Parameter Condition Min Typ Max Units
INL Integral Non-Linearity VCC = 1.6-3.6V VREF = Ext. ref 5 LSB
DNL Differential Non-Linearity VCC = 1.6-3.6V
VREF = Ext. ref 0.6 <±1
LSB
VREF= AVCC 0.6
Fclk Conversion rate 1000 ksps
AREF External reference voltage 1.1 AVCC-0.6 V
Reference input impedance >10 M
Max output voltage Rload=100k AVCC*0.98 V
Min output voltage Rload=100k 0.01 V
Symbol Parameter Condition Min Typ Max Units
Voff Input Offset Voltage VCC = 1.6 - 3.6V <±5 mV
Ilk Input Leakage Current VCC = 1.6 - 3.6V < 1000 pA
Vhys1 Hysteresis, No VCC = 1.6 - 3.6V 0 mV
Vhys2 Hysteresis, Small VCC = 1.6 - 3.6V mode = HS 25 mV
Vhys3 Hysteresis, Large VCC = 1.6 - 3.6V mode = HS 50 mV
tdelay Propagation delay
VCC = 3.0V, T= 85°C mode = HS 100
V ns CC = 1.6 - 3.6V mode = HS 70
VCC = 1.6 - 3.6V mode = LP 140
Symbol Parameter Condition Min Typ Max Units
Bandgap startup time As reference for ADC or DAC 1 Clk_PER + 2.5µs µs
Bandgap voltage 1.1 V[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 79
8067O–AVR–06/2013
34.9 Brownout Detection Characteristics
Table 34-10. Brownout Detection characteristics.
Note: 1. BOD is calibrated to BOD level 0 at 85°C, and BOD level 0 is the default level.
34.10 PAD Characteristics
Table 34-11. PAD characteristics.
ADC/DAC ref
T= 85°C, After calibration 0.99 1.01
V
1
Variation over voltage and temperature VCC = 1.6 - 3.6V, T = -40C to 85C ±5 %
Symbol Parameter Condition Min Typ Max Units
Symbol Parameter Condition Min Typ Max Units
BOD level 0 falling Vcc 1.6
V
BOD level 1 falling Vcc 1.9
BOD level 2 falling Vcc 2.1
BOD level 3 falling Vcc 2.4
BOD level 4 falling Vcc 2.6
BOD level 5 falling Vcc 2.9
BOD level 6 falling Vcc 3.2
BOD level 7 falling Vcc 3.4
Hysteresis BOD level 0-5 2 %
Symbol Parameter Condition Min Typ Max Units
VIH Input High Voltage
VCC = 2.4 - 3.6V 0.7*VCC VCC+0.5
V
VCC = 1.6 - 2.4V 0.8*VCC VCC+0.5
VIL Input Low Voltage
VCC = 2.4 - 3.6V -0.5 0.3*VCC
V
VCC = 1.6 - 2.4V -0.5 0.2*VCC
VOL Output Low Voltage GPIO
IOL = 15 mA, VCC = 3.3V 0.45 0.76
IOL = 10 mA, VCC = 3.0V 0.3 0.64 V
IOL= 5 mA, VCC = 1.8V 0.2 0.46[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 80
8067O–AVR–06/2013
34.11 POR Characteristics
Table 34-12. Power-on Reset characteristics.
34.12 Reset Characteristics
Table 34-13. Reset characteristics.
34.13 Oscillator Characteristics
Table 34-14. Internal 32.768kHz oscillator characteristics.
VOH Output High Voltage GPIO
IOH = -8 mA, VCC = 3.3V 2.6 3
IOH = -6 mA, VCC = 3.0V 2.1 2.2 V
IOH = -2 mA, VCC = 1.8V 1.4 1.6
IIL Input Leakage Current I/O pin <0.001 1 µA
IIH Input Leakage Current I/O pin <0.001 1 µA
RP I/O pin Pull/Buss keeper Resistor 20 k
RRST Reset pin Pull-up Resistor 20 k
Input hysteresis 0.5 V
Symbol Parameter Condition Min Typ Max Units
Symbol Parameter Condition Min Typ Max Units
VPOT- POR threshold voltage falling Vcc 1 V
VPOT+ POR threshold voltage rising Vcc 1.4 V
Symbol Parameter Condition Min Typ Max Units
Minimum reset pulse width 90 ns
Reset threshold voltage
VCC = 2.7 - 3.6V 0.45*VCC
V
VCC = 1.6 - 2.7V 0.42*VCC
Symbol Parameter Condition Min Typ Max Units
Accuracy T = 85C, VCC = 3V,
After production calibration -0.5 0.5 %[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 81
8067O–AVR–06/2013
Table 34-15. Internal 2MHz oscillator characteristics.
Table 34-16. Internal 32MHz oscillator characteristics.
Table 34-17. Internal 32kHz, ULP oscillator characteristics.
Table 34-18. Maximum load capacitance (CL) and ESR recommendation for 32.768kHz crystal.
Table 34-19. Device wake-up time from sleep.
Notes: 1. Non-prescaled System Clock source.
2. Time from pin change on external interrupt pin to first available clock cycle. Additional interrupt response time is minimum 5 system clock source cycles.
Symbol Parameter Condition Min Typ Max Units
Accuracy T = 85C, VCC = 3V,
After production calibration -1.5 1.5 %
DFLL Calibration step size T = 25C, VCC = 3V 0.175 %
Symbol Parameter Condition Min Typ Max Units
Accuracy T = 85C, VCC = 3V,
After production calibration -1.5 1.5 %
DFLL Calibration stepsize T = 25C, VCC = 3V 0.2 %
Symbol Parameter Condition Min Typ Max Units
Output frequency 32 kHz ULP OSC T = 85C, VCC = 3.0V 26 kHz
Crystal CL [pF] Max ESR [k]
6.5 60
9 35
Symbol Parameter Condition(1) Min Typ(2) Max Units
Idle Sleep, Standby and Extended
Standby sleep mode
Int. 32.768 kHz RC 130
µS
Int. 2 MHz RC 2
Ext. 2 MHz Clock 2
Int. 32 MHz RC 0.17
Power-save and Power-down
Sleep mode
Int. 32.768 kHz RC 320
Int. 2 MHz RC 10.3
Ext. 2 MHz Clock 4.5
Int. 32 MHz RC 5.8[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 82
8067O–AVR–06/2013
35. Typical Characteristics
35.1 Active Supply Current
Figure 35-1. Active Supply Current vs. Frequency
fSYS = 1 - 32 MHz, T = 25°C
Figure 35-2. Active Supply Current vs. VCC
fSYS = 1.0 MHz
3.3V
3.0V
2.7V
0
5
10
15
20
25
0 4 8 12 16 20 24 28 32
Frequency [MHz]
Icc [mA]
1.8V
2.2V
85°C
25°C
-40°C
0
200
400
600
800
1000
1200
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Icc [uA][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 83
8067O–AVR–06/2013
35.2 Idle Supply Current
Figure 35-3. Idle Supply Current vs. Frequency
fSYS = 1 - 32 MHz, T = 25°C
Figure 35-4. Active Supply Current vs. VCC
fSYS = 1.0 MHz
,
3.3V
3.0V
2.7V
0
1
2
3
4
5
6
7
8
9
10
0 4 8 12 16 20 24 28 32
Frequency [MHz]
Icc [mA]
1.8V
2.2V
85°C
25°C
-40°C
0
50
100
150
200
250
300
350
400
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Icc [uA][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 84
8067O–AVR–06/2013
35.3 Power-down Supply Current
Figure 35-5. Power-down Supply Current vs. Temperature
35.4 Power-save Supply Current
Figure 35-6. Power-save Supply Current vs. Temperature
Sampled BOD, WDT, RTC from ULP enabled
3.3V
3.0V
2.7V
2.2V
1.8V
0
0.5
1
1.5
2
2.5
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature [°C]
Icc [uA]
3.3V
2.7V
2.2V
1.8V
0
0.5
1
1.5
2
2.5
3
3.5
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature [°C]
Icc [uA][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 85
8067O–AVR–06/2013
35.5 Pin Pull-up
Figure 35-7. I/O Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 1.8V
Figure 35-8. I/O Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 3.0V
85 °C 25 °C
-40 °C
0
20
40
60
80
100
0 0.2 0.4 0.6 0.8 1 1.2 1.4
vreset [V]
Ireset [uA]
85 °C
25 °C
-40 °C
0
20
40
60
80
100
120
140
160
180
0 0.5 1 1.5 2 2.5
vreset [V]
Ireset [uA][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 86
8067O–AVR–06/2013
Figure 35-9. I/O Reset Pull-up Resistor Current vs. Reset Pin Voltage
VCC = 3.3V
35.6 Pin Thresholds and Hysteresis
Figure 35-10.I/O Pin Input Threshold Voltage vs. VCC
VIH - I/O Pin Read as “1”
85 °C
25 °C
-40 °C
0
20
40
60
80
100
120
140
160
180
0 0.5 1 1.5 2 2.5 3
vreset [V]
Ireset [uA]
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Vthreshold [V][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 87
8067O–AVR–06/2013
Figure 35-11.I/O Pin Input Threshold Voltage vs. VCC
VIL - I/O Pin Read as “0”
Figure 35-12.I/O Pin Input Hysteresis vs. VCC.
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Vthreshold [V]
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Vthreshold [V][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 88
8067O–AVR–06/2013
Figure 35-13.Reset Input Threshold Voltage vs. VCC
VIH - I/O Pin Read as “1”
Figure 35-14.Reset Input Threshold Voltage vs. VCC
VIL - I/O Pin Read as “0”
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Vthreshold [V]
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Vthreshold [V][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 89
8067O–AVR–06/2013
35.7 Bod Thresholds
Figure 35-15.BOD Thresholds vs. Temperature
BOD Level = 1.6V
Figure 35-16.BOD Thresholds vs. Temperature
BOD Level = 2.9V
Rising Vcc
Falling Vcc
1.602
1.608
1.614
1.62
1.626
1.632
1.638
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature [°C]
VBOT [V]
Rising Vcc
Falling Vcc
2.905
2.92
2.935
2.95
2.965
2.98
2.995
3.01
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature [°C]
VBOT [V][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 90
8067O–AVR–06/2013
35.8 Bandgap
Figure 35-17.Internal 1.00V Reference vs. Temperature.
35.9 Analog Comparator
Figure 35-18.Analog Comparator Hysteresis vs. VCC
High-speed, Small hysteresis
3.0V
1.8V
0.999
0.9995
1
1.0005
1.001
1.0015
1.002
1.0025
1.003
1.0035
1.004
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature [°C]
VREF [V]
25°C
0
5
10
15
20
25
30
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Hysteresis [mV][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 91
8067O–AVR–06/2013
Figure 35-19.Analog Comparator Hysteresis vs. VCC, High-speed
Large hysteresis
Figure 35-20.Analog Comparator Propagation Delay vs. VCC
High-speed
25°C
0
10
20
30
40
50
60
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Hysteresis [mV]
25°C
0
20
40
60
80
100
120
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
Vcc [V]
Propagation Delay [ns][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 92
8067O–AVR–06/2013
35.10 Oscillators and Wake-up Time
Figure 35-21.Internal 32.768 kHz Oscillator Frequency vs. Temperature
1.024 kHz output
Figure 35-22.Ultra Low-Power (ULP) Oscillator Frequency vs. Temperature
1 kHz output
p
3.0 V
1.8 V
0.99
0.995
1
1.005
1.01
1.015
1.02
1.025
1.03
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
T [°C]
f [kHz]
p
3.0 V
1.8 V
0.87
0.88
0.89
0.9
0.91
0.92
0.93
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
T [°C]
f1kHz output [kHz][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 93
8067O–AVR–06/2013
Figure 35-23.Internal 2 MHz Oscillator CalA Calibration Step Size
T = -40 to 85C, VCC = 3V
Figure 35-24.Internal 2 MHz Oscillator CalB Calibration Step Size
T = -40 to 85C, VCC = 3V
0
0.001
0.002
0.003
0.004
0.005
0.006
0 20 40 60 80 100 120 140
CALA [LSB]
Step size: f [MHz]
0
0.005
0.01
0.015
0.02
0.025
0.03
0.035
0.04
0 10 20 30 40 50 60 70
CALB [LSB]
Step size: f [MHz][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 94
8067O–AVR–06/2013
Figure 35-25.Internal 32 MHz Oscillator CalA Calibration Step Size
T = -40 to 85C, VCC = 3V
Figure 35-26.Internal 32 MHz Oscillator CalB Calibration Step Size
T = -40 to 85C, VCC = 3V
0
0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0 20 40 60 80 100 120 140
CALA
Step size: f [MHz]
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 10 20 30 40 50 60 70
CALB
Step size: f [MHz][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 95
8067O–AVR–06/2013
35.11 PDI Speed
Figure 35-27.PDI Speed vs. VCC
25 °C
0
5
10
15
20
25
30
35
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2 3.4 3.6
VCC [V]
fMAX [MHz][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 96
8067O–AVR–06/2013
36. Errata
36.1 ATxmega64A1and ATxmega128A1 rev. H
Bandgap voltage input for the ACs can not be changed when used for both ACs simultaneously
VCC voltage scaler for AC is non-linear
The ADC has up to ±2 LSB inaccuracy
ADC gain stage output range is limited to 2.4 V
Sampling speed limited to 500 ksps for supply voltage below 2.0V
ADC Event on compare match non-functional
Bandgap measurement with the ADC is non-functional when VCC is below 2.7V
Accuracy lost on first three samples after switching input to ADC gain stage
The input difference between two succeeding ADC samples is limited by VREF
Increased noise when using internal 1.0V reference at low temperature
Configuration of PGM and CWCM not as described in XMEGA A Manual
PWM is not restarted properly after a fault in cycle-by-cycle mode
BOD will be enabled at any reset
BODACT fuse location is not correct
Sampled BOD in Active mode will cause noise when bandgap is used as reference
DAC has up to ±10 LSB noise in Sampled Mode
DAC is nonlinear and inaccurate when reference is above 2.4V or VCC - 0.6V
DAC refresh may be blocked in S/H mode
Conversion lost on DAC channel B in event triggered mode
Both DFLLs and both oscillators have to be enabled for one to work
Access error when multiple bus masters are accessing SDRAM
EEPROM page buffer always written when NVM DATA0 is written
Pending full asynchronous pin change interrupts will not wake the device
Pin configuration does not affect Analog Comparator Output
Low level interrupt triggered when pin input is disabled
JTAG enable does not override Analog Comparator B output
NMI Flag for Crystal Oscillator Failure automatically cleared
Flash Power Reduction Mode can not be enabled when entering sleep
Some NVM Commands are non-functional
Crystal start-up time required after power-save even if crystal is source for RTC
Setting PRHIRES bit makes PWM output unavailable
Accessing EBI address space with PREBI set will lock Bus Master
RTC Counter value not correctly read after sleep
Pending asynchronous RTC-interrupts will not wake up device
TWI, the minimum I2C SCL low time could be violated in Master Read mode
TWI address-mask feature is non-functional
TWI, a general address call will match independent of the R/W-bit value
TWI Transmit collision flag not cleared on repeated start
Clearing TWI Stop Interrupt Flag may lock the bus[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 97
8067O–AVR–06/2013
TWI START condition at bus timeout will cause transaction to be dropped
TWI Data Interrupt Flag erroneously read as set
WDR instruction inside closed window will not issue reset
1. Bandgap voltage input for the ACs cannot be changed when used for both ACs simultaneously
If the Bandgap voltage is selected as input for one Analog Comparator (AC) and then selected/deselected as input
for another AC, the first comparator will be affected for up to 1 µs and could potentially give a wrong comparison
result.
Problem fix/Workaround
If the Bandgap is required for both ACs simultaneously, configure the input selection for both ACs before enabling
any of them.
2. VCC voltage scaler for AC is non-linear
The 6-bit VCC voltage scaler in the Analog Comparators is non-linear.
Figure 36-1. Analog Comparator Voltage Scaler vs. Scalefac
T = 25°C
Problem fix/Workaround
Use external voltage input for the analog comparator if accurate voltage levels are needed
3. The ADC has up to ±2 LSB inaccuracy
The ADC will have up to ±2 LSB inaccuracy, visible as a saw-tooth pattern on the input voltage/ output value transfer
function of the ADC. The inaccuracy increases with increasing voltage reference reaching ±2 LSB with 3V
reference.
3.3 V
2.7 V
1.8 V
0
0.5
1
1.5
2
2.5
3
3.5
0 5 10 15 20 25 30 35 40 45 50 55 60 65
SCALEFAC
VSCALE [V][Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 98
8067O–AVR–06/2013
Problem fix/Workaround
None, the actual ADC resolution will be reduced with up to ±2 LSB.
4. ADC gain stage output range is limited to 2.4 V
The amplified output of the ADC gain stage will never go above 2.4 V, hence the differential input will only give correct
output when below 2.4 V/gain. For the available gain settings, this gives a differential input range of:
Problem fix/Workaround
Keep the amplified voltage output from the ADC gain stage below 2.4 V in order to get a correct result, or keep
ADC voltage reference below 2.4 V.
5. Sampling speed limited to 500 ksps for supply voltage below 2.0V
The sampling frequency is limited to 500 ksps for supply voltage below 2.0V. At higher sampling rate the INL error
will be several hundred LSB.
Problem fix/Workaround
None.
6. ADC Event on compare match non-functional
ADC signalling event will be given at every conversion complete even if Interrupt mode (INTMODE) is set to
BELOW or ABOVE.
Problem fix/Workaround
Enable and use interrupt on compare match when using the compare function.
7. Bandgap measurement with the ADC is non-functional when VCC is below 2.7V
The ADC can not be used to do bandgap measurements when VCC is below 2.7V.
Problem fix/Workaround
– 1x gain: 2.4 V
– 2x gain: 1.2 V
– 4x gain: 0.6 V
– 8x gain: 300 mV
– 16x gain: 150 mV
– 32x gain: 75 mV
– 64x gain: 38 mV[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 99
8067O–AVR–06/2013
None.
8. Accuracy lost on first three samples after switching input to ADC gain stage
Due to memory effect in the ADC gain stage, the first three samples after changing input channel must be disregarded
to achieve 12-bit accuracy.
Problem fix/Workaround
Run three ADC conversions and discard these results after changing input channels to ADC gain stage.
9. The input difference between two succeeding ADC samples is limited by VREF
If the difference in input between two samples changes more than the size of the reference, the ADC will not be
able to convert the data correctly. Two conversions will be required before the conversion is correct.
Problem fix/Workaround
Discard the first conversion if input is changed more than VREF, or ensure that the input never changes more then
VREF.
10. Increased noise when using internal 1.0V reference at low temperature
When operating at below 0C and using internal 1.0V reference the RMS noise will be up 4 LSB, Peak-to-peak
noise up to 25 LSB.
Problem fix/Workaround
Use averaging to remove noise.
11. Configuration of PGM and CWCM not as described in XMEGA A Manual
Enabling Common Waveform Channel Mode will enable Pattern generation mode (PGM), but not Common Waveform
Channel Mode.
Enabling Pattern Generation Mode (PGM) and not Common Waveform Channel Mode (CWCM) will enable both
Pattern Generation Mode and Common Waveform Channel Mode.
Problem fix/Workaround
12 PWM is not restarted properly after a fault in cycle-by-cycle mode
When the AWeX fault restore mode is set to cycle-by-cycle, the waveform output will not return to normal operation
at first update after fault condition is no longer present.
PGM CWCM Description
0 0 PGM and CWCM disabled
0 1 PGM enabled
1 0 PGM and CWCM enabled
1 1 PGM enabled[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 100
8067O–AVR–06/2013
Problem fix/Workaround
Do a write to any AWeX I/O register to re-enable the output.
13. BOD will be enabled after any reset
If any reset source goes active, the BOD will be enabled and keep the device in reset if the VCC voltage is below
the programmed BOD level. During Power-On Reset, reset will not be released until VCC is above the programmed
BOD level even if the BOD is disabled.
Problem fix/Workaround
Do not set the BOD level higher than VCC even if the BOD is not used.
14. BODACT fuse location is not correct
The fuses for enabling BOD in active mode (BODACT) are located at FUSEBYTE2, bit 2 and 3 and not in FUSEBYTE
5 as described in the XMEGA A Manual.
Problem fix/Workaround
Access the fuses in FUSEBYTE2.
15. Sampled BOD in Active mode will cause noise when bandgap is used as reference
Using the BOD in sampled mode when the device is running in Active or Idle mode will add noise on the bandgap
reference for ADC, DAC and Analog Comparator.
Problem fix/Workaround
If the bandgap is used as reference for either the ADC, DAC or Analog Comparator, the BOD must not be set in
sampled mode.
16. DAC has up to ±10 LSB noise in Sampled Mode
The DAC has noise of up to ±10 LSB in Sampled Mode for entire operation range.
Problem fix/Workaround
Use the DAC in continuous mode.
17. DAC is nonlinear and inaccurate when reference is above 2.4V or VCC - 0.6V
Using the DAC with a reference voltage above 2.4V or VCC - 0.6V will give inaccurate output when converting
codes that give below 0.75V output:
±10 LSB for continuous mode
±200 LSB for Sample and Hold mode
Problem fix/Workaround
None.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 101
8067O–AVR–06/2013
18. DAC has up to ±10 LSB noise in Sampled Mode
If the DAC is running in Sample and Hold (S/H) mode and conversion for one channel is done at maximum rate
(i.e. the DAC is always busy doing conversion for this channel), this will block refresh signals to the second channel.
Problem fix/Workaround
When using the DAC in S/H mode, ensure that none of the channels is running at maximum conversion rate, or
ensure that the conversion rate of both channels is high enough to not require refresh.
19. Conversion lost on DAC channel B in event triggered mode
If during dual channel operation channel 1 is set in auto trigged conversion mode, channel 1 conversions are occasionally
lost. This means that not all data-values written to the Channel 1 data register are converted.
Problem fix/Workaround
Keep the DAC conversion interval in the range 000-001 (1 and 3 CLK), and limit the Peripheral clock frequency so
the conversion internal never is shorter than 1.5 µs.
20. Both DFLLs and both oscillators have to be enabled for one to work
In order to use the automatic runtime calibration for the 2 MHz or the 32 MHz internal oscillators, the DFLL for both
oscillators and both oscillators have to be enabled for one to work.
Problem fix/Workaround
Enable both DFLLs and both oscillators when using automatic runtime calibration for either of the internal
oscillators.
21. Access error when multiple bus masters are accessing SDRAM
If one bus master (CPU and DMA channels) is using the EBI to access an SDRAM in burst mode and another bus
master is accessing the same row number in a different BANK of the SDRAM in the cycle directly after the burst
access is complete, the access for the second bus master will fail.
Problem fix/Workaround
Do not put stack pointer in SDRAM and use DMA Controller in 1 byte burst mode if CPU and DMA Controller are
required to access SDRAM at the same time.
22. EEPROM page buffer always written when NVM DATA0 is written
If the EEPROM is memory mapped, writing to NVM DATA0 will corrupt data in the EEPROM page buffer.
Problem fix/Workaround
Before writing to NVM DATA0, for example when doing software CRC or flash page buffer write, check if EEPROM
page buffer active loading flag (EELOAD) is set. Do not write NVM DATA0 when EELOAD is set.
23. Pending full asynchronous pin change interrupts will not wake the device[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 102
8067O–AVR–06/2013
Any full asynchronous pin-change Interrupt from pin 2, on any port, that is pending when the sleep instruction is
executed, will be ignored until the device is woken from another source or the source triggers again. This applies
when entering all sleep modes where the System Clock is stopped.
Problem fix/Workaround
None.
24. Pin configuration does not affect Analog Comparator Output
The Output/Pull and inverted pin configuration does not affect the Analog Comparator output function.
Problem fix/Workaround
None for Output/Pull configuration.
For inverted I/O, configure the Analog Comparator to give an inverted result (i.e. connect positive input to the negative
AC input and vice versa), or use and external inverter to change polarity of Analog Comparator output.
25. Low level interrupt triggered when pin input is disabled
If a pin input is disabled, but pin is configured to trigger on low level, interrupt request will be sent.
Problem fix/Workaround
Ensure that Interrupt mask for the disabled pin is cleared.
26. JTAG enable does not override Analog Comparator B output
When JTAG is enabled this will not override the Analog Comparator B (ACB) output, AC0OUT on pin 7 if this is
enabled.
Problem fix/Workaround
Use Analog Comparator output for ACA when JTAG is used, or use the PDI as debug interface.
27. NMI Flag for Crystal Oscillator Failure automatically cleared
NMI flag for Crystal Oscillator Failure (XOSCFDIF) will be automatically cleared when executing the NMI interrupt
handler.
Problem fix/Workaround
This device revision has only one NMI interrupt source, so checking the interrupt source in software is not
required.
28. Flash Power Reduction Mode can not be enabled when entering sleep
If Flash Power Reduction Mode is enabled when entering Power-save or Extended Standby sleep mode, the
device will only wake up on every fourth wake-up request. If Flash Power Reduction Mode is enabled when entering
Idle sleep mode, the wake-up time will vary with up to 16 CPU clock cycles.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 103
8067O–AVR–06/2013
Problem fix/Workaround
Disable Flash Power Reduction mode before entering sleep mode.
29. Some NVM Commands are non-functional
The following NVM commands are non-functional:
Problem fix/Workaround
None for Flash Range CRC
Use separate programming commands for accessing application and boot section.
30. Crystal start-up time required after power-save even if crystal is source for RTC
Even if 32.768 kHz crystal is used for RTC during sleep, the clock from the crystal will not be ready for the system
before the specified start-up time. See "XOSCSEL[3:0]: Crystal Oscillator Selection" in XMEGA A Manual. If BOD
is used in active mode, the BOD will be on during this period (0.5s).
Problem fix/Workaround
If faster start-up is required, go to sleep with internal oscillator as system clock.
31. Setting PRHIRES bit makes PWM output unavailable
Setting the HIRES Power Reduction (PR) bit for PORTx will make any Frequency or PWM output for the corresponding
Timer/Counters (TCx0 and TCx1) unavailable on the pin even if the Hi-Res is not used.
Problem fix/Workaround
Do not write the HIRES PR bit on PORTx when frequency or PWM output from TCx0/1 is used.
– 0x2B Erase Flash Page
– 0x2E Write Flash Page
– 0x2F Erase & Write Flash Page
– 0x3A Flash Range CRC
– 0x22 Erase Application Section Page
– 0x24 Write Application Section Page
– 0x25 Erase & Write Application Section Page
– 0x2A Erase Boot Loader Section Page
– 0x2C Write Boot Loader Section Page
– 0x2D Erase & Write Boot Loader Section Page[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 104
8067O–AVR–06/2013
32. Accessing EBI address space with PREBI set will lock Bus Master
If EBI Power Reduction Bit is set while EBI is enabled, accessing external memory could result in bus hang-up,
blocking all further access to all data memory.
Problem fix/Workaround
Ensure that EBI is disabled before setting EBI Power Reduction bit.
33. RTC Counter value not correctly read after sleep
If the RTC is set to wake up the device on RTC Overflow and bit 0 of RTC CNT is identical to bit 0 of RTC PER as
the device is entering sleep, the value in the RTC count register can not be read correctly within the first prescaled
RTC clock cycle after wakeup. The value read will be the same as the value in the register when entering sleep.
The same applies if RTC Compare Match is used as wake-up source.
Problem fix/Workaround
Wait at least one prescaled RTC clock cycle before reading the RTC CNT value.
34. Pending asynchronous RTC-interrupts will not wake up device
Asynchronous Interrupts from the Real-Time-Counter that is pending when the sleep instruction is executed, will
be ignored until the device is woken from another source or the source triggers again.
Problem fix/Workaround
None.
35. TWI, the minimum I2
C SCL low time could be violated in Master Read mode
If the TWI is in Master Read mode and issues a Repeated Start on the bus, this will immediately release the SCL
line even if one complete SCL low period has not passed. This means that the minimum SCL low time in the I2C
specification could be violated.
Problem fix/Workaround
If this is a problem in the application, ensure in software that the Repeated Start is never issued before one SCL
low time has passed.
36. TWI address-mask feature is non-functional
The address-mask feature is non-functional, so the TWI can not perform hardware address match on more than
one address.
Problem fix/Workaround
If the TWI must respond to multiple addresses, enable Promiscuous Mode for the TWI to respond to all address
and implement the address-mask function in software.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 105
8067O–AVR–06/2013
37. TWI, a general address call will match independent of the R/W-bit value
When the TWI is in Slave mode and a general address call is issued on the bus, the TWI Slave will get an address
match regardless of the received R/W bit.
Problem fix/Workaround
Use software to check the R/W-bit on general call address match.
38. TWI Transmit collision flag not cleared on repeated start
The TWI transmit collision flag should be automatically cleared on start and repeated start, but is only cleared on
start.
Problem fix/Workaround
Clear the flag in software after address interrupt.
39. Clearing TWI Stop Interrupt Flag may lock the bus
If software clears the STOP Interrupt Flag (APIF) on the same Peripheral Clock cycle as the hardware sets this
flag due to a new address received, CLKHOLD is not cleared and the SCL line is not released. This will lock the
bus.
Problem fix/Workaround
Check if the bus state is IDLE. If this is the case, it is safe to clear APIF. If the bus state is not IDLE, wait for the
SCL pin to be low before clearing APIF.
Code:
/* Only clear the interrupt flag if within a "safe zone". */
while ( /* Bus not IDLE: */
((COMMS_TWI.MASTER.STATUS & TWI_MASTER_BUSSTATE_gm) !=
TWI_MASTER_BUSSTATE_IDLE_gc)) &&
/* SCL not held by slave: */
!(COMMS_TWI.SLAVE.STATUS & TWI_SLAVE_CLKHOLD_bm)
)
{
/* Ensure that the SCL line is low */
if ( !(COMMS_PORT.IN & PIN1_bm) )
if ( !(COMMS_PORT.IN & PIN1_bm) )
break;
}
/* Check for an pending address match interrupt */
if ( !(COMMS_TWI.SLAVE.STATUS & TWI_SLAVE_CLKHOLD_bm) )
{
/* Safely clear interrupt flag */
COMMS_TWI.SLAVE.STATUS |= (uint8_t)TWI_SLAVE_APIF_bm;
}[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 106
8067O–AVR–06/2013
40. TWI START condition at bus timeout will cause transaction to be dropped
If Bus Timeout is enabled and a timeout occurs on the same Peripheral Clock cycle as a START is detected, the
transaction will be dropped.
Problem fix/Workaround
None.
41. TWI Data Interrupt Flag erroneously read as set
When issuing the TWI slave response command CMD=0b11, it takes 1 Peripheral Clock cycle to clear the data
interrupt flag (DIF). A read of DIF directly after issuing the command will show the DIF still set.
Problem fix/Workaround
Add one NOP instruction before checking DIF.
42. WDR instruction inside closed window will not issue reset
When a WDR instruction is execute within one ULP clock cycle after updating the window control register, the
counter can be cleared without giving a system reset.
Problem fix/Workaround
Wait at least one ULP clock cycle before executing a WDR instruction.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 107
8067O–AVR–06/2013
36.2 ATxmega64A1 and ATxmega128A1 rev. G
Bootloader Section in Flash is non-functional
Bandgap voltage input for the ACs cannot be changed when used for both ACs simultaneously
DAC is nonlinear and inaccurate when reference is above 2.4V
ADC gain stage output range is limited to 2.4 V
The ADC has up to ±2 LSB inaccuracy
TWI, a general address call will match independent of the R/W-bit value
TWI, the minimum I2
C SCL low time could be violated in Master Read mode
Setting HIRES PR bit makes PWM output unavailable
EEPROM erase and write does not work with all System Clock sources
BOD will be enabled after any reset
Propagation delay analog Comparator increasing to 2 ms at -40C
Sampled BOD in Active mode will cause noise when bandgap is used as reference
Default setting for SDRAM refresh period too low
Flash Power Reduction Mode can not be enabled when entering sleep mode
Enabling Analog Comparator B output will cause JTAG failure
JTAG enable does not override Analog Comparator B output
Bandgap measurement with the ADC is non-functional when VCC is below 2.7V
DAC refresh may be blocked in S/H mode
Inverted I/O enable does not affect Analog Comparator Output
Both DFLLs and both oscillators has to be enabled for one to work
1. Bootloader Section in Flash is non-functional
The Bootloader Section is non-functional, and bootloader or application code cannot reside in this part of the
Flash.
Problem fix/Workaround
None, do not use the Bootloader Section.
2. Bandgap voltage input for the ACs cannot be changed when used for both ACs simultaneously
If the Bandgap voltage is selected as input for one Analog Comparator (AC) and then selected/deselected as input
for the another AC, the first comparator will be affected for up to 1 us and could potentially give a wrong comparison
result.
Problem fix/Workaround
If the Bandgap is required for both ACs simultaneously, configure the input selection for both ACs before enabling
any of them.
3. DAC is nonlinear and inaccurate when reference is above 2.4V
Using the DAC with a reference voltage above 2.4V give inaccurate output when converting codes that give below
0.75V output:
±20 LSB for continuous mode[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 108
8067O–AVR–06/2013
±200 LSB for Sample and Hold mode
Problem fix/Workaround
None, avoid using a voltage reference above 2.4V.
4. ADC gain stage output range is limited to 2.4 V
The amplified output of the ADC gain stage will never go above 2.4 V, hence the differential input will only give correct
output when below 2.4 V/gain. For the available gain settings, this gives a differential input range of:
Problem fix/Workaround
Keep the amplified voltage output from the ADC gain stage below 2.4 V in order to get a correct result, or keep
ADC voltage reference below 2.4 V.
5. The ADC has up to ±2 LSB inaccuracy
The ADC will have up to ±2 LSB inaccuracy, visible as a saw-tooth pattern on the input voltage/ output value transfer
function of the ADC. The inaccuracy increases with increasing voltage reference reaching ±2 LSB with 3V
reference.
Problem fix/Workaround
None, the actual ADC resolution will be reduced with up to ±2 LSB.
6. TWI, a general address call will match independent of the R/W-bit value
When the TWI is in Slave mode and a general address call is issued on the bus, the TWI Slave will get an address
match regardless of the R/W-bit (ADDR[0] bit) value in the Slave Address Register.
Problem fix/Workaround
Use software to check the R/W-bit on general call address match.
– 1x gain: 2.4 V
– 2x gain: 1.2 V
– 4x gain: 0.6 V
– 8x gain: 300 mV
– 16x gain: 150 mV
– 32x gain: 75 mV
– 64x gain: 38 mV[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 109
8067O–AVR–06/2013
7. TWI, the minimum I2
C SCL low time could be violated in Master Read mode
When the TWI is in Master Read mode and issuing a Repeated Start on the bus, this will immediately release the
SCL line even if one complete SCL low period has not passed. This means that the minimum SCL low time in the
I
2
C specification could be violated.
Problem fix/Workaround
If this causes a potential problem in the application, software must ensure that the Repeated Start is never issued
before one SCL low time has passed.
8. Setting HIRES PR bit makes PWM output unavailable
Setting the HIRES Power Reduction (PR) bit for PORTx will make any Frequency or PWM output for the corresponding
Timer/Counters (TCx0 and TCx1) unavailable on the pin.
Problem fix/Workaround
Do not write the HIRES PR bit on PORTx when frequency or PWM output from TCx0/1 is used.
9. EEPROM erase and write does not work with all System Clock sources
When doing EEPROM erase or Write operations with other clock sources than the 2 MHz RCOSC, Flash will be
read wrongly for one or two clock cycles at the end of the EEPROM operation.
Problem fix/Workaround
Alt 1: Use the internal 2 MHz RCOSC when doing erase or write operations on EEPROM.
Alt 2: Ensure to be in sleep mode while completing erase or write on EEPROM. After starting erase or write operations
on EEPROM, other interrupts should be disabled and the device put to sleep.
10. BOD will be enabled after any reset
If any reset source goes active, the BOD will be enabled and keep the device in reset if the VCC voltage is below
the programmed BOD level. During Power-On Reset, reset will not be released until VCC is above the programmed
BOD level even if the BOD is disabled.
Problem fix/Workaround
Do not set the BOD level higher than VCC even if the BOD is not used.
11. Propagation delay analog Comparator increasing to 2 ms at -40 °C
When the analog comparator is used at temperatures reaching down to -40 °C, the propagation delay will increase
to ~2 ms.
Problem fix/Workaround
None[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 110
8067O–AVR–06/2013
12. Sampled BOD in Active mode will cause noise when bandgap is used as reference
Using the BOD in sampled mode when the device is running in Active or Idle mode will add noise on the bandgap
reference for ADC and DAC.
Problem fix/Workaround
If the bandgap is used as reference for either the ADC or the DAC, the BOD must not be set in sampled mode.
13. Default setting for SDRAM refresh period too low
If the SDRAM refresh period is set to a value less then 0x20, the SDRAM content may be corrupted when accessing
through On-Chip Debug sessions.
Problem fix/Workaround
The SDRAM refresh period (REFRESHH/L) should not be set to a value less then 0x20.
14. Flash Power Reduction Mode can not be enabled when entering sleep mode
If Flash Power Reduction Mode is enabled when entering Power-save or Extended Standby sleep mode, the
device will only wake up on every fourth wake-up request.
If Flash Power Reduction Mode is enabled when entering Idle sleep mode, the wake-up time will vary with up to 16
CPU clock cycles.
Problem fix/Workaround
Disable Flash Power Reduction mode before entering sleep mode.
15. JTAG enable does not override Analog Comparator B output
When JTAG is enabled this will not override the Anlog Comparator B (ACB)ouput, AC0OUT on pin 7 if this is
enabled.
Problem fix/Workaround
AC0OUT for ACB should not be enabled when JTAG is used. Use only analog comparator output for ACA when
JTAG is used, or use the PDI as debug interface.
16. Bandgap measurement with the ADC is non-functional when VCC is below 2.7V
The ADC cannot be used to do bandgap measurements when VCC is below 2.7V.
Problem fix/Workaround
If internal voltages must be measured when VCC is below 2.7V, measure the internal 1.00V reference instead of
the bandgap.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 111
8067O–AVR–06/2013
17. DAC refresh may be blocked in S/H mode
If the DAC is running in Sample and Hold (S/H) mode and conversion for one channel is done at maximum rate
(i.e. the DAC is always busy doing conversion for this channel), this will block refresh signals to the second channel.
Problem fix/Workarund
When using the DAC in S/H mode, ensure that none of the channels is running at maximum conversion rate, or
ensure that the conversion rate of both channels is high enough to not require refresh.
18. Inverted I/O enable does not affect Analog Comparator Output
The inverted I/O pin function does not affect the Analog Comparator output function.
Problem fix/Workarund
Configure the analog comparator setup to give a inverted result (i.e. connect positive input to the negative AC input
and vice versa), or use and externel inverter to change polarity of Analog Comparator Output.
19. Both DFLLs and both oscillators has to be enabled for one to work
In order to use the automatic runtime calibration for the 2 MHz or the 32 MHz internal oscilla-tors, the DFLL for
both oscillators and both oscillators has to be enabled for one to work.
Problem fix/Workarund
Enabled both DFLLs and oscillators when using automatic runtime calibration for one of the internal oscillators. [Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 112
8067O–AVR–06/2013
37. Datasheet Revision History
Please note that the referring page numbers in this section are referred to this document. The referring revision in this
section are referring to the document revision.
37.1 8067O – 06/2013
37.2 8067N – 03/2013
37.3 8067M – 09/2010
37.4 8067L – 08/2010
1. Not recommended for new designs - Use XMEGA A1U series.
1. Removed all references to ATxmega192A1, ATxmega256A1 and ATxmega384A1.
2. Updated module description. Based on the XMEGA A1U device datasheet.
3. Updated analog comparator (AC) overview, Figure 28-1 on page 53.
4. Updated “ADC Characteristics” on page 76.
5 Updated page erase time in “Flash and EEPROM Memory Characteristics” on page 76.
6 Updated Output low voltage conditions from IOH to IOL in “PAD Characteristics” on page 79.
7. Removed TBDs from:
“DC Characteristics” on page 73.
“DAC Characteristics” on page 78.
“Bandgap Characteristics” on page 78.
8. Updated “Errata” on page 96 to be valid for both ATxmega64A1 and ATxmega128A1.
9. Removed Boundary Scan Order table.
1. Updated Errata “ATxmega64A1and ATxmega128A1 rev. H” on page 96
1. Removed Footnote 3 of Figure 2-1 on page 3
2. Updated “Features” on page 32. Event Channel 0 output on port pin 7
3. Updated “DC Characteristics” on page 73, by adding ICC for Flash/EEPROM Programming.
4. Added AVCC in “ADC Characteristics” on page 76.
5. Updated Start up time in “ADC Characteristics” on page 76. [Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 113
8067O–AVR–06/2013
37.5 8067K – 02/2010
37.6 8067J – 02/2010
37.7 8067I – 04/2009
37.8 8067H – 04/2009
6. Updated “DAC Characteristics” on page 78. Removed DC output impedance.
7. Fixed typo in “Packaging information” section.
8. Fixed typo in “Errata” section.
1. Added “PDI Speed vs. VCC” on page 95.
1. Removed JTAG Reset from the datasheet.
2. Updated “Timer/Counter and AWEX functions” on page 56.
3. Updated “Alternate Pin Functions” on page 58.
3. Updated all “Electrical Characteristics” on page 73.
4. Updated “PAD Characteristics” on page 79.
5. Changed Internal Oscillator Speed to “Oscillators and Wake-up Time” on page 92.
6. Updated “Errata” on page 96
1. Updated “Ordering Information” on page 2.
2. Updated “PAD Characteristics” on page 79.
1. Editorial updates.
2. Updated “Overview” on page 54.
3. Updated Table 29-9 on page 54.
4. Updated “Peripheral Module Address Map” on page 62. IRCOM has address map: 0x08F8.
5. Updated “Electrical Characteristics” on page 73.
6. Updated “PAD Characteristics” on page 79.
7. Updated “Typical Characteristics” on page 82.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 114
8067O–AVR–06/2013
37.9 8067G – 11/2008
37.10 8067F – 09/2008
37.11 8067E – 08/2008
37.12 8067D – 07/2008
1. Updated “Block Diagram” on page 6.
2. Updated feature list in “Memories” on page 12.
3. Updated “Programming and Debugging” on page 54.
4. Updated “Peripheral Module Address Map” on page 62. IRCOM has address 0x8F0.
5. Added “Electrical Characteristics” on page 73.
6. Added “Typical Characteristics” on page 82.
7. Added “ATxmega64A1and ATxmega128A1 rev. H” on page 96.
8. Updated “ATxmega64A1 and ATxmega128A1 rev. G” on page 107.
1. Updated “Features” on page 1
2. Updated “Ordering Information” on page 2
3. Updated Figure 7-1 on page 11 and Figure 7-2 on page 11.
4. Updated Table 7-2 on page 15.
5. Updated “Features” on page 48 and “Overview” on page 48.
6. Removed “Interrupt Vector Summary” section from datasheet.
1. Changed Figure 2-1’s title to “Block diagram and pinout” on page 3.
2. Updated Figure 2-2 on page 4.
3. Updated Table 29-2 on page 51 and Table 29-3 on page 52.
1. Updated “Ordering Information” on page 2.
2. Updated “Peripheral Module Address Map” on page 62.
3. Inserted “Interrupt Vector Summary” on page 56.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 115
8067O–AVR–06/2013
37.13 8067C – 06/2008
37.14 8067B – 05/2008
37.15 8067A – 02/2008
1. Updated the Front page and “Features” on page 1.
2. Updated the “DC Characteristics” on page 73.
3. Updated Figure 3-1 on page 6.
4. Added “Flash and EEPROM Page Size” on page 15.
5. Updated Table 33-6 on page 72 with new data: Gain Error, Offset Error and Signal -to-Noise
Ratio (SNR).
6. Updated Errata “ATxmega64A1 and ATxmega128A1 rev. G” on page 107.
1. Updated “Pinout/Block Diagram” on page 3 and “Pinout and Pin Functions” on page 55.
2. Added XMEGA A1 Block Diagram, Figure 3-1 on page 6.
3. Updated “Overview” on page 5 included the XMEGA A1 explanation text on page 6.
4. Updated AVR CPU “Features” on page 8.
5. Updated Event System block diagram, Figure 10-1 on page 20.
6. Updated “Interrupts and Programmable Multilevel Interrupt Controller” on page 29.
7. Updated “AC - Analog Comparator” on page 52.
8. Updated “Alternate Pin Function Description” on page 55.
9. Updated “Alternate Pin Functions” on page 58.
10. Updated “Typical Characteristics” on page 82.
11. Updated “Ordering Information” on page 2.
12. Updated “Overview” on page 5.
13. Updated Figure 6-1 on page 8.
14. Inserted a new Figure 16-1 on page 37.
15. Updated Speed grades in “Speed” on page 75.
16. Added a new ATxmega384A1 device in “Features” on page 1, updated “Ordering Information” on
page 2 and “Memories” on page 12.
17. Replaced the Figure 3-1 on page 6 by a new XMEGA A1 detailed block diagram.
18. Inserted Errata “ATxmega64A1 and ATxmega128A1 rev. G” on page 107.
1. Initial revision.[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 116
8067O–AVR–06/2013[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 1
8067O–AVR–06/2013
Table of Contents
Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1. Ordering Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2. Pinout/Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1 Block Diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.1 Recommended reading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5. Capacitive touch sensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6. Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7. AVR CPU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.3 Architectural Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.4 ALU - Arithmetic Logic Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7.5 Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7.6 Status Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7.7 Register File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8. Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.3 In-System Programmable Flash Program Memory. . . . . . . . . . . . . . . . . . . . . 13
8.4 Fuses and Lock bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.5 Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.6 EEPROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.7 I/O Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.8 External Memory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.9 Data Memory and Bus Arbitration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
8.10 Memory Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8.11 Device ID and Revision. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8.12 I/O Memory Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8.13 JTAG Disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8.14 Flash and EEPROM Page Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
9. DMAC - Direct Memory Access Controller . . . . . . . . . . . . . . . . . . . . 18
9.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
9.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
10. Event System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
10.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
10.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
11. System Clock and Clock options . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
11.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
11.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 2
8067O–AVR–06/2013
11.3 Clock Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12. Power Management and Sleep Modes . . . . . . . . . . . . . . . . . . . . . . 24
12.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
12.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
12.3 Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
13. System Control and Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3 Reset Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.4 Reset Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5 WDT - Watchdog Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.6 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
14. Interrupts and Programmable Multilevel Interrupt Controller . . . . . . 29
14.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
14.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
14.3 Interrupt vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
15. I/O Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
15.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
15.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
15.3 Output Driver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
15.4 Input sensing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
15.5 Port Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
15.6 Alternate Port Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
16. T/C - 16-bit Timer/Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
16.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
16.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
17. AWeX - Advanced Waveform Extension . . . . . . . . . . . . . . . . . . . . . 38
17.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
17.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
18. Hi-Res - High Resolution Extension . . . . . . . . . . . . . . . . . . . . . . . . . 39
18.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
18.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
19. RTC - 16-bit Real-Time Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
19.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
19.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
20. TWI - Two-Wire Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
20.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
20.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
21. SPI - Serial Peripheral Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
21.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
21.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
22. USART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 3
8067O–AVR–06/2013
22.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
22.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
23. IRCOM - IR Communication Module . . . . . . . . . . . . . . . . . . . . . . . . 45
23.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
24. AES and DES Crypto Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
24.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
24.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
25. EBI – External Bus Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
25.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
25.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
26. ADC - 12-bit Analog to Digital Converter . . . . . . . . . . . . . . . . . . . . . 48
26.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
26.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
27. DAC - 12-bit Digital to Analog Converter . . . . . . . . . . . . . . . . . . . . . 50
27.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
27.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
28. AC - Analog Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
28.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
28.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
29. Programming and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
29.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
29.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
30. Pinout and Pin Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
30.1 Alternate Pin Function Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
30.2 Alternate Pin Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
31. Peripheral Module Address Map . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
32. Instruction Set Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
33. Packaging information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
33.1 100A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
33.2 100C1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
33.3 100C2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
34. Electrical Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
34.1 Absolute Maximum Ratings*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
34.2 DC Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
34.3 Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
34.4 Flash and EEPROM Memory Characteristics. . . . . . . . . . . . . . . . . . . . . . . . . 76
34.5 ADC Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
34.6 DAC Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
34.7 Analog Comparator Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
34.8 Bandgap Characteristics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
34.9 Brownout Detection Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 4
8067O–AVR–06/2013
34.10 PAD Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
34.11 POR Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
34.12 Reset Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
34.13 Oscillator Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
35. Typical Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
35.1 Active Supply Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
35.2 Idle Supply Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
35.3 Power-down Supply Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
35.4 Power-save Supply Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
35.5 Pin Pull-up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
35.6 Pin Thresholds and Hysteresis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
35.7 Bod Thresholds. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
35.8 Bandgap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
35.9 Analog Comparator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
35.10 Oscillators and Wake-up Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
35.11 PDI Speed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
36. Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
36.1 ATxmega64A1and ATxmega128A1 rev. H. . . . . . . . . . . . . . . . . . . . . . . . . . . 96
36.2 ATxmega64A1 and ATxmega128A1 rev. G . . . . . . . . . . . . . . . . . . . . . . . . . 107
37. Datasheet Revision History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
37.1 8067O – 06/2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
37.2 8067N – 03/2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
37.3 8067M – 09/2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
37.4 8067L – 08/2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
37.5 8067K – 02/2010. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
37.6 8067J – 02/2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
37.7 8067I – 04/2009 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
37.8 8067H – 04/2009 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
37.9 8067G – 11/2008 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
37.10 8067F – 09/2008. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
37.11 8067E – 08/2008. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
37.12 8067D – 07/2008 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
37.13 8067C – 06/2008 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
37.14 8067B – 05/2008. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
37.15 8067A – 02/2008. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1[Not recommended for new designs - Use XMEGA A1U series] XMEGA A1 [DATASHEET] 5
8067O–AVR–06/2013Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 8067O–AVR–06/2013
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation or its
subsidiaries. Other terms and product names may be trademarks of others.
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
USER GUIDE
Atmel SAM4S Xplained Pro
Preface
The Atmel® SAM4S Xplained Pro evaluation kit is a hardware platform to
evaluate the ATSAM4SD32C microcontroller.
Supported by the Atmel Studio integrated development platform, the kit provides
easy access to the features of the Atmel ATSAM4SD32C and explains how to
integrate the device in a custom design.
The Xplained Pro MCU series evaluation kits include an on-board Embedded
Debugger, and no external tools are necessary to program or debug the
ATSAM4SD32C.
The Xplained Pro extension series evaluation kits offers additional peripherals to
extend the features of the board and ease the development of custom designs.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
2
Table of Contents
Preface .......................................................................................... 1
1. Introduction .............................................................................. 3
1.1. Features .............................................................................. 3
1.2. Kit overview ......................................................................... 3
2. Getting started ......................................................................... 5
2.1. Quick-start ........................................................................... 5
2.2. Connecting the kit ................................................................. 5
2.3. Design documentation and related links ..................................... 5
3. Xplained Pro ............................................................................ 6
3.1. Embedded Debugger ............................................................. 6
3.2. Hardware identification system ................................................. 6
3.3. Power supply ....................................................................... 7
3.3.1. Measuring SAM4S power consumption ......................... 7
3.4. Standard headers and connectors ............................................ 7
3.4.1. Xplained Pro extension header .................................... 7
3.4.2. Xplained Pro LCD connector ....................................... 8
3.4.3. Power header ......................................................... 10
4. Hardware user guide ............................................................ 11
4.1. Connectors ......................................................................... 11
4.1.1. I/O extension headers .............................................. 11
4.1.2. LCD extension connector .......................................... 12
4.1.3. Other headers ........................................................ 14
4.2. Peripherals ......................................................................... 14
4.2.1. NAND Flash ........................................................... 14
4.2.2. SD Card connector .................................................. 15
4.2.3. Crystals ................................................................. 15
4.2.4. Mechanical buttons .................................................. 16
4.2.5. LED ...................................................................... 16
4.2.6. Analog reference ..................................................... 16
4.3. Embedded Debugger implementation ...................................... 16
4.3.1. Serial Wire Debug ................................................... 16
4.3.2. Virtual COM port ..................................................... 16
4.3.3. Atmel Data Gateway Interface ................................... 17
5. Hardware revision history and known issues ........................ 18
5.1. Identifying product ID and revision .......................................... 18
5.2. Revision 5 .......................................................................... 18
5.3. Revision 4 .......................................................................... 18
6. Document revision history ..................................................... 19
7. Evaluation board/kit important notice .................................... 20Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
3
1. Introduction
1.1 Features
● Atmel ATSAM4SD32C microcontroller
● Embedded debugger (EDBG)
● USB interface
● Programming and debugging (target) through Serial Wire Debug (SWD)
● Virtual COM-port interface to target via UART
● Atmel Data Gateway Interface (DGI) to target via synchronous SPI or TWI
● Four GPIOs connected to target for code instrumentation
● Digital I/O
● Two mechanical buttons (user and reset button)
● One user LED
● Three extension headers
● LCD display header
● USB interface for host and device function (target)
● 2Gb NAND Flash for non-volatile storage
● SD card connector
● Adjustable analog reference
● Three possible power sources
● External power
● Embedded debugger USB
● Target USB
● 12MHz crystal
● 32kHz crystal
1.2 Kit overview
The Atmel SAM4S Xplained Pro evaluation kit is a hardware platform to evaluate the Atmel ATSAM4SD32C.
The kit offers a set of features that enables the ATSAM4SD32C user to get started using the ATSAM4SD32C
peripherals right away and to get an understanding of how to integrate the device in their own design.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
4
Figure 1.1. SAM4S Xplained Pro evaluation kit overviewAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
5
2. Getting started
2.1 Quick-start
3 Steps to start exploring the Atmel Xplained Pro Platform
● Download and install Atmel Studio1
.
● Launch Atmel Studio.
● Connect an USB cable to the DEBUG USB port.
2.2 Connecting the kit
When connecting Atmel SAM4S Xplained Pro to your computer for the first time, the operating system will do a
driver software installation. The driver file supports both 32-bit and 64-bit versions of Microsoft® Windows® XP
and Windows 7.
Once connected the green power LED will be lit and Atmel Studio will autodetect which Xplained Pro
evaluation- and extension kit(s) that's connected. You'll be presented with relevant information like datasheets
and kit documentation. You also have the option to launch Atmel Software Framework (ASF) example
applications. The target device is programmed and debugged by the on-board Embedded Debugger and no
external programmer or debugger tool is needed. Please refer to the Atmel Studio user guide2
for information
regarding how to compile and program the kit.
2.3 Design documentation and related links
The following list contains links to the most relevant documents and software for SAM4S Xplained Pro.
1. Xplained Pro products 3
- Atmel Xplained Pro is a series of small-sized and easy-to-use evaluation kits
for 8- and 32-bit Atmel microcontrollers. It consists of a series of low cost MCU boards for evaluation and
demonstration of features and capabilities of different MCU families.
2. SAM4S Xplained Pro User Guide 4
- PDF version of this User Guide.
3. SAM4S Xplained Pro Design Documentation 5
- Package containing schematics, BOM, assembly
drawings, 3D plots, layer plots etc.
4. Atmel Studio 6
- Free Atmel IDE for development of C/C++ and assembler code for Atmel
microcontrollers.
5. IAR Embedded Workbench®
7
for ARM®. This is a commercial C/C++ compiler that is available for
ARM. There is a 30 day evaluation version as well as a code size limited kick-start version available from
their website. The code size limit is 16K for devices with M0, M0+ and M1 cores and 32K for devices with
other cores.
6. Atmel sample store 8
- Atmel sample store where you can order samples of devices.
1
http://www.atmel.com/atmelstudio
2
http://www.atmel.com/atmelstudio
3
http://www.atmel.com/XplainedPro
4
http://www.atmel.com/Images/Atmel-42075-SAM4S-Xplained-Pro_User-Guide.pdf
5
http://www.atmel.com/Images/Atmel-42075-SAM4S-Xplained-Pro_User-Guide.zip
6
http://www.atmel.com/atmelstudio
7
http://www.iar.com/en/Products/IAR-Embedded-Workbench/ARM/
8
http://www.atmel.com/system/samplesstoreAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
6
3. Xplained Pro
Xplained Pro is an evaluation platform that provides the full Atmel microcontroller experience. The platform
consists of a series of Microcontroller (MCU) boards and extension boards that are integrated with Atmel
Studio, have Atmel Software Framework (ASF) drivers and demo code, support data streaming and more.
Xplained Pro MCU boards support a wide range of Xplained Pro extension boards that are connected through
a set of standardized headers and connectors. Each extension board has an identification (ID) chip to uniquely
identify which boards are mounted on a Xplained Pro MCU board. This information is used to present relevant
user guides, application notes, datasheets and example code through Atmel Studio. Available Xplained Pro
MCU and extension boards can be purchased in the Atmel Web Store
1
.
3.1 Embedded Debugger
The SAM4S Xplained Pro contains the Atmel® Embedded Debugger (EDBG) for on-board debugging. The
EDBG is a composite USB device of 3 interfaces; a debugger, Virtual COM Port and Data Gateway Interface
(DGI).
In conjunction with Atmel Studio, the EDBG debugger interface can program and debug the ATSAM4SD32C.
On the SAM4S Xplained Pro, the SWD interface is connected between the EDBG and the ATSAM4SD32C.
The Virtual COM Port is connected to a UART port on the ATSAM4SD32C (see section “Embedded Debugger
implementation” on page 16 for pinout), and provides an easy way to communicate with the target
application through a simple terminal software. It offers variable baud rate, parity and stop bit settings. Note
that the settings on the target device UART must match the settings given in the terminal software.
The DGI consists of several physical data interfaces for communication with the host computer. Please,
see section “Embedded Debugger implementation” on page 16 for available interfaces and pinout.
Communication over the interfaces are bidirectional. It can be used to send events and values from the
ATSAM4SD32C, or as a generic printf-style data channel. Traffic over the interfaces can be timestamped on
the EDBG for more accurate tracing of events. Note that timestamping imposes an overhead that reduces
maximal throughput. The DGI uses a proprietary protocol, and is thus only compatible with Atmel Studio.
The EDBG controls two LEDs on SAM4S Xplained Pro, a power LED and a status LED. Table 3.1, “EDBG LED
control” shows how the LEDs are controlled in different operation modes.
Table 3.1. EDBG LED control
Operation mode Power LED Status LED
Normal operation Power LED is lit when power is
applied to the board.
Activity indicator, LED flashes
every time something happens on
the EDBG.
Bootloader mode (idle) The power LED and the status LED blinks simultaneously.
Bootloader mode (firmware
upgrade)
The power LED and the status LED blinks in an alternating pattern.
For further documentation on the EDBG, see the EDBG User Guide.
3.2 Hardware identification system
All Xplained Pro compatible extension boards have an Atmel ATSHA204 crypto authentication chip mounted.
This chip contains information that identifies the extension with its name and some extra data. When an
Xplained Pro extension board is connected to an Xplained Pro MCU board the information is read and sent
to Atmel Studio. The Atmel Kits extension, installed with Atmel Studio, will give relevant information, code
examples and links to relevant documents. Table 3.2, “Xplained Pro ID chip content” shows the data fields
stored in the ID chip with example content.
Table 3.2. Xplained Pro ID chip content
Data Field Data Type Example Content
Manufacturer ASCII string Atmel’\0’
Product Name ASCII string Segment LCD1 Xplained Pro’\0’
Product Revision ASCII string 02’\0’
Product Serial Number ASCII string 1774020200000010’\0’
Minimum Voltage [mV] uint16_t 3000
1
http://store.atmel.com/CBC.aspx?q=c:100113Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
7
Data Field Data Type Example Content
Maximum Voltage [mV] uint16_t 3600
Maximum Current [mA] uint16_t 30
3.3 Power supply
The SAM4S Xplained Pro kit can be powered either by USB or by an external power source through the 4-
pin power header, marked PWR. This connector is described in “Power header” on page 10. The available
power sources and specifications are listed in Table 3.3, “Power sources for SAM4S Xplained Pro”.
Table 3.3. Power sources for SAM4S Xplained Pro
Power input Voltage requirements Current requirements Connector marking
External power 5 V +/- 2 % (+/- 100 mV)
for USB host operation.
4.3 V to 5.5 V if USB
host operation is not
required
Recommended
minimum is 1A to be
able to provide enough
current for connected
USB devices and the
board itself.
Recommended
maximum is 2A due
to the input protection
maximum current
specification.
PWR
Embedded debugger
USB
4.4V to 5.25V
(according to USB spec)
500 mA (according to
USB spec)
DEBUG USB
Target USB 4.4V to 5.25V
(according to USB spec)
500 mA (according to
USB spec)
TARGET USB
The kit will automatically detect which power sources are available and choose which one to use according to
the following priority:
1. External power
2. Embedded debugger USB
3. Target USB
Note External power is required when the 500mA through the USB connector is not enough to power a
connected USB device in a USB host application.
3.3.1 Measuring SAM4S power consumption
As part of an evaluation of the SAM4S it can be of interest to measure its power consumption. Because the
device has a separate power plane (VCC_MCU_P3V3) on this board it is possible to measure the current
consumption by measuring the current that is flowing into this plane. The VCC_MCU_P3V3 plane is connected
via a jumper to the main power plane (VCC_TARGET_P3V3) and by replacing the jumper with an ampere
meter it is possible to determine the current consumption. To locate the current measurement header, please
refer to Figure 1.1, “SAM4S Xplained Pro evaluation kit overview”.
Warning Do not power the board without having the jumper or an ampere meter mounted. This can cause
the SAM4S to be powered through its I/O pins and cause undefined operation of the device.
3.4 Standard headers and connectors
3.4.1 Xplained Pro extension header
All Xplained Pro kits have one or more dual row, 20 pin, 100mil extension headers. Xplained Pro MCU boards
have male headers while Xplained Pro extensions have their female counterparts. Note that all pins are
not always connected. However, all the connected pins follow the defined pin-out described in Table 3.4,
“Xplained Pro extension header”. The extension headers can be used to connect a wide variety of Xplained ProAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
8
extensions to Xplained Pro MCU boards and to access the pins of the target MCU on Xplained Pro MCU board
directly.
Table 3.4. Xplained Pro extension header
Pin number Name Description
1 ID Communication line to the ID chip on extension board.
2 GND Ground
3 ADC(+) Analog to digital converter , alternatively positive part of differential
ADC
4 ADC(-) Analog to digital converter , alternatively negative part of
differential ADC
5 GPIO1 General purpose IO
6 GPIO2 General purpose IO
7 PWM(+) Pulse width modulation , alternatively positive part of differential
PWM
8 PWM(-) Pulse width modulation , alternatively positive part of differential
PWM
9 IRQ/GPIO Interrupt request line and/or general purpose IO.
10 SPI_SS_B/GPIO Slave select for SPI and/or general purpose IO.
11 TWI_SDA Data line for two wire interface. Always implemented, bus type.
12 TWI_SCL Clock line for two wire interface. Always implemented, bus type.
13 USART_RX Receiver line of Universal Synchronous and Asynchronous serial
Receiver and Transmitter
14 USART_TX Transmitter line of Universal Synchronous and Asynchronous
serial Receiver and Transmitter
15 SPI_SS_A Slave select for SPI. Should be unique if possible.
16 SPI_MOSI Master out slave in line of Serial peripheral interface. Always
implemented, bus type
17 SPI_MISO Master in slave out line of Serial peripheral interface. Always
implemented, bus type
18 SPI_SCK Clock for Serial peripheral interface. Always implemented, bus
type
19 GND Ground
20 VCC Power for extension board
3.4.2 Xplained Pro LCD connector
The LCD connector provides the ability to connect to display extensions that have a parallel interface. The
connector implements signals for a MCU parallel bus interface and a LCD controller interface as well as signals
for a touchcontroller. The connector pin-out definition is shown in Table 3.5, “Xplained Pro LCD connector”.
Note that usually only one display interface is implemented, either LCD controller or the MCU bus interface.
A FPC/FFC connector with 50 pins and 0.5mm pitch is used for the LCD connector. The connector
(XF2M-5015-1A) from Omron is used on several designs and can be used as a reference.
Table 3.5. Xplained Pro LCD connector
Pin number Name RGB interface
description
MCU interface
description
1 ID Communication line to ID chip on extension board.
2 GND Ground
3 D0 Data line
4 D1 Data line
5 D2 Data line
6 D3 Data lineAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
9
Pin number Name RGB interface
description
MCU interface
description
7 GND Ground
8 D4 Data line
9 D5 Data line
10 D6 Data line
11 D7 Data line
12 GND Ground
13 D8 Data line
14 D9 Data line
15 D10 Data line
16 D11 Data line
17 GND Ground
18 D12 Data line
19 D12 Data line
20 D14 Data line
21 D15 Data line
22 GND Ground
23 D16 Data line
24 D17 Data line
25 D18 Data line
26 D19 Data line
27 GND Ground
28 D20 Data line
29 D21 Data line
30 D22 Data line
31 D23 Data line
32 GND Ground
33 PCLK /
CMD_DATA_SEL
Pixel clock Command and data
select. One address line
of the MCU for displays
where it is possible to
select either the register
or the data interface.
34 VSYNC / CS Vertical synchronization Chip select
35 HSYNC / WE Horizontal
synchronization
Write enable signal
36 DATA ENABLE / RE Data enable signal Read enable signal
37 SPI SCK Clock for Serial peripheral interface
38 SPI MOSI Master out slave in line of Serial peripheral interface
39 SPI MISO Master in slave out line of Serial peripheral interface
40 SPI SS Slave select for SPI. Should be unique if possible
41 ENABLE Display enable signal
42 TWI SDA I2C data line (maxTouch)
43 TWI SCL I2C clock line (maxTouch)
44 IRQ1 maxTouch interrupt lineAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
10
Pin number Name RGB interface
description
MCU interface
description
45 IRQ2 Interrupt line for other I2C devices
46 PWM Backlight control
47 RESET Reset for both display and maxTouch
48 VCC 3.3V power supply for extension board
49 VCC 3.3V power supply for extension board
50 GND Ground
3.4.3 Power header
The power header can be used to connect external power to the SAM4S Xplained Pro kit. The kit will
automatically detect and switch to the external power if supplied. The power header can also be used as supply
for external peripherals or extension boards. Care must be taken not to exceed the total current limitation of the
on-board regulator for the 3.3V regulated output. To locate the current measurement header, please refer to
Figure 1.1, “SAM4S Xplained Pro evaluation kit overview”
Table 3.6. Power header PWR
Pin number PWR header Pin name Description
1 VEXT_P5V0 External 5V input
2 GND Ground
3 VCC_P5V0 Unregulated 5V (output, derived
from one of the input sources)
4 VCC_P3V3 Regulated 3.3V (output, used as
main power for the kit)
Note If the board is powered from a battery source it is recommended to use the PWR header. If there
is a power source connected to EDBG USB, the EDBG is activated and it will consume more
power.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
11
4. Hardware user guide
4.1 Connectors
This chapter describes the implementation of the relevant connectors and headers on SAM4S Xplained Pro
and their connection to the ATSAM4SD32C. The tables of connections in this chapter also describes which
signals are shared between the headers and on-board functionality.
4.1.1 I/O extension headers
The SAM4S Xplained Pro headers EXT1, EXT2 and EXT3 offers access to the I/O of the microcontroller in
order to expand the board e.g. by connecting extensions to the board. These headers all comply with the
standard extension header specified in Xplained Pro Standard Extension Header. All headers have a pitch of
2.54 mm.
Table 4.1. Extension header EXT1
Pin on EXT1 SAM4S pin Function Shared functionality
1 - - Communication line to ID chip on
extension board.
2 - - GND
3 PA17 AD[0]
4 PA18 AD[1]
5 PA24 GPIO PIOD Interface Header
6 PA25 GPIO PIOD Interface Header
7 PA23 PWMH0 PIOD Interface Header
8 PA19 PWML0
9 PA1 WKUP1/GPIO
10 PA6 GPIO DGI_GPIO0 on EDBG
11 PA3 TWD0 EXT2 and EDBG
12 PA4 TWCK0 EXT2 and EDBG
13 PA21 USART1/RXD1 EXT2
14 PA22 USART1/TXD1 EXT2
15 PA11 SPI/NPCS[0]
16 PA13 SPI/MOSI EXT2, EXT3, LCD connector (EXT4) and
EDBG
17 PA12 SPI/MISO EXT2, EXT3, LCD connector (EXT4) and
EDBG
18 PA14 SPI/SPCK EXT2, EXT3, LCD connector (EXT4) and
EDBG
19 - - GND
20 - - VCC
Table 4.2. Extension header EXT2
Pin on EXT2 SAM4S pin Function Shared functionality
1 - - Communication line to ID chip on
extension board.
2 - - GND
3 PB0 AD[4]
4 PB1 AD[5]
5 PC24 GPIO DGI_GPIO2 on EDBG
6 PC25 GPIO DGI_GPIO3 on EDBG
7 PC19 PWMH1Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
12
Pin on EXT2 SAM4S pin Function Shared functionality
8 PA20 PWML1
9 PC26 GPIO
10 PC27 GPIO
11 PA3 TWD0 EXT1 and EDBG
12 PA4 TWCK0 EXT1 and EDBG
13 PA21 USART1/RXD1 EXT1
14 PA22 USART1/TXD1 EXT1
15 PA9 SPI/NPCS[1] LCD connector (EXT4)
16 PA13 SPI/MOSI EXT1, EXT3, LCD connector (EXT4) and
EDBG
17 PA12 SPI/MISO EXT1, EXT3, LCD connector (EXT4) and
EDBG
18 PA14 SPI/SPCK EXT1, EXT3, LCD connector (EXT4) and
EDBG
19 - - GND
20 - - VCC
Table 4.3. Extension header EXT3
Pin on EXT3 SAM4S pin Function Shared functionality
1 - - Communication line to ID chip on
extension board.
2 - - GND
3 PC29 AD[13]
4 PC30 AD[14]
5 PC21 GPIO
6 PC22 GPIO DGI_GPIO1 on EDBG
7 PC20 PWMH2
8 PA16 PWML2 PIOD Header
9 PA0 WKUP0/GPIO LCD connector (EXT4)
10 PC31 GPIO
11 PB4 TWD1 LCD connector (EXT4)
12 PB5 TWCK1 LCD connector (EXT4)
13 PB2 USART1/RXD1 CDC UART
14 PB3 USART1/TXD1 CDC UART
15 PA10 SPI/NPCS[2] LCD connector (EXT4)
16 PA13 SPI/MOSI EXT1, EXT2, LCD connector (EXT4) and
EDBG
17 PA12 SPI/MISO EXT1, EXT2, LCD connector (EXT4) and
EDBG
18 PA14 SPI/SPCK EXT1, EXT2, LCD connector (EXT4) and
EDBG
19 - - GND
20 - - VCC
4.1.2 LCD extension connector
Extension connector EXT4 is a special connector for LCD displays. The physical connector is an Omron
Electronics XF2M-5015-1A FPC connector.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
13
Table 4.4. LCD display connector EXT4
Pin on EXT4 SAM4S pin Function Shared functionality
1 - - Communication line to ID chip on
extension board.
2 - - GND
3 PC0 D0 NAND Flash
4 PC1 D1 NAND Flash
5 PC2 D2 NAND Flash
6 PC3 D3 NAND Flash
7 - - GND
8 PC4 D4 NAND Flash
9 PC5 D5 NAND Flash
10 PC6 D6 NAND Flash
11 PC7 D7 NAND Flash
12 - - GND
13 - -
14 - -
15 - -
16 - -
17 - - GND
18 - -
19 - -
20 - -
21 - -
22 - - GND
23 - -
24 - -
25 - -
26 - -
27 - - GND
28 - -
29 - -
30 - -
31 - -
32 - - GND
33 PC18 A0
34 PC15 NPCS[1]
35 PC8 NWE
36 PC11 NRD
37
38
39
40
41 PB14 GPIO
42 PB4 TWD1/SDA EXT3Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
14
Pin on EXT4 SAM4S pin Function Shared functionality
43 PB5 TWCK1/SCL EXT3
44 PA0 WKUP0 EXT3
45 - -
46 PA15 PWML3 PIOD Interface header
47 PC28 GPIO
48 - VCC_P3V3
49 - VCC_P3V3 EXT2
50 - GND
4.1.3 Other headers
In addition to the “I/O extension headers” on page 11, SAM4S Xplained Pro has two additional headers
with spare signals that offers access to the I/O of the microcontroller which are otherwise not easily available
elsewhere or might be favourable to have collected toghether. All headers have a pitch of 2.54mm.
Table 4.5. SPARE SIGNALS header
Pin on header SAM4S pin Function Shared functionality
1 PA2 DATRG User button, SW0
2 PA9 PWMF10 EXT2
3 PA26 TI0A2 SD Card and PIOD Interface header
4 PA27 TI0B2 SD Card and PIOD Interface header
5 PA28 TCLK1 SD Card and PIOD Interface header
6 PA29 TCLK2 SD Card and PIOD Interface header
7 PA31 PCK2 SD Card and PIOD Interface header
8 PB0 RTCOUT0 EXT2
9 PB1 RTCOUT1 EXT2
10 PB13 DAC0
11 PB14 DAC1
12 - - GND
Table 4.6. PIOD INTERFACE header
Pin on header SAM4S pin Function Shared functionality
1 PA15 PIODCEN1 LCD connector
2 PA16 PIODCEN2 EXT3
3 PA23 PIODCCLK EXT1
4 PA24 PIODC0 EXT1
5 PA25 PIODC1 EXT1
6 PA26 PIODC2 SD Card and SPARE Signals header
7 PA27 PIODC3 SD Card and SPARE Signals header
8 PA28 PIODC4 SD Card and SPARE Signals header
9 PA29 PIODC5 SD Card and SPARE Signals header
10 PA30 PIODC6 SD Card
11 PA31 PIODC7 SD Card and SPARE Signals header
12 - - GND
4.2 Peripherals
4.2.1 NAND Flash
The SAM4S Xplained Pro kit has one 2Gb NAND Flash connected to the external bus interface of the SAM4S.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
15
Table 4.7. NAND Flash connections
SAM4S pin Function NAND Flash
function
Shared functionality
PC0 D0 IO0 LCD connector
PC1 D1 IO1 LCD connector
PC2 D2 IO2 LCD connector
PC3 D3 IO3 LCD connector
PC4 D4 IO4 LCD connector
PC5 D5 IO5 LCD connector
PC6 D6 IO6 LCD connector
PC7 D7 IO7 LCD connector
PC9 NANDOE RE (active low)
PC10 NANDWE WE (active low)
PC13 GPIO R (active high)/ B
(active low)
PC14 NCS[0] CE (active low)
PC16 NANDALE ALE (active low)
PC17 NANDCLE CLE
4.2.2 SD Card connector
The SAM4S Xplained Pro kit has one SD card connector which is connected to High Speed Multimedia Card
Interface (HSMCI) of the SAM4S
Table 4.8. SD Card connections
SAM4S pin Function SD Card function Shared functionality
PA26 MCDA2 DAT2 SPARE Signal and PIOD Interface
headers
PA27 MCDA3 DAT3 SPARE Signal and PIOD Interface
headers
PA28 MCCDA CMD SPARE Signal and PIOD Interface
headers
PA29 MCCK CLK SPARE Signal and PIOD Interface
headers
PA30 MCDA0 DAT0 PIOD Interface header
PA31 MCDA1 DAT1 SPARE Signal and PIOD Interface
headers
PC12 GPIO Card Detect
4.2.3 Crystals
The SAM4S Xplained Pro kit contains two crystals that can be used as clock sources for the SAM4S device.
Each crystal has a cut-strap next to it that can be used to measure the oscillator safety factor. This is done by
cutting the strap and adding a resistor across the strap. More information about oscillator allowance and safety
factor can be found in appnote AVR4100
1
.
Table 4.9. External 32.768kHz crystals
Pin on SAM4S Function
PA49 XIN32
PA48 XOUT32
1
http://www.atmel.com/images/doc8333.pdfAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
16
Table 4.10. External 12MHz crystals
Pin on SAM4S Function
PB9 XIN0
PB8 XOUT0
4.2.4 Mechanical buttons
SAM4S Xplained Pro contains two mechanical buttons. One button is the RESET button connected to the
SAM4S reset line and the other is a generic user configurable button. When a button is pressed it will drive the
I/O line to GND.
Table 4.11. Mechanical buttons
Pin on SAM4S Silkscreen text
NRST RESET
PC24 SW0
4.2.5 LED
There is one yellow LED available on the SAM4S Xplained Pro board that can be turned on and off. The LED
can be activated by driving the connected I/O line to GND.
Table 4.12. LED connections
Pin on SAM4S LED
PC23 Yellow LED0
4.2.6 Analog reference
An adjustable voltage reference is implemented on the kit to have a reference for the ADC or DAC. The
reference can be adjusted with the on-board multiturn trimmer potentiometer. Next to the potentiometer, a 2-pin
header is available to measure the reference voltage for the AREF pin of the SAM4S. The voltage output range
for the reference is 0V - 3.36V.
4.3 Embedded Debugger implementation
SAM4S Xplained Pro contains an Embedded Debugger (EDBG) that can be used to program and debug the
ATSAM4SD32C using Serial Wire Debug (SWD). The Embedded Debugger also include a Virtual Com port
interface over UART, an Atmel Data Gateway Interface over SPI and TWI and it monitors four of the SAM4S
GPIOs. Atmel Studio can be used as a front end for the Embedded Debugger.
4.3.1 Serial Wire Debug
The Serial Wire Debug (SWD) use two pins to communicate with the target. For further information on how to
use the programming and debugging capabilities of the EDBG, see “Embedded Debugger” on page 6.
Table 4.13. SWD connections
Pin on SAM4S Function
PB7 SWD clock
PB6 SWD data
PB5 SWD trace output
PB12 Erase
4.3.2 Virtual COM port
The Embedded Debugger act as a Virtual Com Port gateway by using one of the ATSAM4SD32C UARTs. For
further information on how to use the Virtual COM port see “Embedded Debugger” on page 6.
Table 4.14. Virtual COM port connections
Pin on SAM4S Function
PB3 UART TXD (SAM4S TX line)Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
17
Pin on SAM4S Function
PB2 UART RXD (SAM4S RX line)
4.3.3 Atmel Data Gateway Interface
The Embedded Debugger features an Atmel Data Gateway Interface (DGI) by using either a SPI or TWI port.
The DGI can be used to send a variety of data from the SAM4S to the host PC. For further information on how
to use the DGI interface see “Embedded Debugger” on page 6.
Table 4.15. DGI interface connections when using SPI
Pin on SAM4S Function
PA5 Slave select (SAM4S is Master)
PA12 SPI MISO (Master In, Slave Out)
PA13 SPI MOSI (Master Out, Slave in)
PA14 SPI SCK (Clock Out)
Table 4.16. DGI interface connections when using TWI
Pin on SAM4S Function
PA3 SDA (Data line)
PA4 SCL (Clock line)
Four GPIO lines are connected to the Embedded Debugger. The EDBG can monitor these lines and time
stamp pin value changes. This makes it possible to accurately time stamp events in the SAM4S application
code. For further information on how to configure and use the GPIO monitoring features see “Embedded
Debugger” on page 6.
Table 4.17. GPIO lines connected to the EDBG
Pin on SAM4S Function
PA6 GPIO0
PA22 GPIO1
PA24 GPIO2
PA25 GPIO3Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
18
5. Hardware revision history and known issues
5.1 Identifying product ID and revision
The revision and product identifier of Xplained Pro boards can be found in two ways, through Atmel Studio or
by looking at the sticker on the bottom side of the PCB.
By connecting a Xplained Pro MCU board to a computer with Atmel Studio running, an information window will
pop up. The first 6 digits of the serial number, which is listed under kit details, contain the product identifier and
revision. Information about connected Xplained Pro extension boards will also appear in the Atmel Kits window.
The same information can be found on the sticker on the bottom side of the PCB. Most kits will print the
identifier and revision in plain text as A09-nnnn\rr where nnnn is the identifier and rr is the revision. Boards with
limited space have a sticker with only a QR-code which contains a serial number string.
The serial number string has the following format:
"nnnnrrssssssssss"
n = product identifier
r = revision
s = serial number
The kit identifier for SAM4S Xplained Pro is 1803.
5.2 Revision 5
On this revision, the SPI clock net is improved to reduce any issues that might be caused by reflections. The
SPI has been removed from the LCD (EXT4 connector) to reduce load on the clock net. The remaining clock
lines have been divided into four terminated nets for each SPI source (EXT1, EXT2, EXT3, and EDBG) and
routed in a star like layout. A series terminator resistor of 43ohm is placed on each clock net, close to the SPI
clock pin. This reduces any issues that might be caused by reflections comming back from unterminated/
unused clock lines. It also reduces the rise/fall time of the clock edges and that will also help to reduce any
reflection issues.
5.3 Revision 4
Known issues
● SAM4S has an on-die series termination of the SPI CLK which makes this signal not usable for a multi
drop clock distribution because all devices along the line will see a fraction of VCC until the signal is
reflected from the end of the transmission line. On the SAM4S Xplained Pro revision 4 this signal is
routed to each extension connector with EXT1 at the end of the line. That means extensions that are
connected along the transission line e.g. EXT3 header is likely to fail due to a non-monotinic edge caused
by relections and the fraction of VCC that is present for a short time until the reflection comes back from
the end of the line.
Workaround:
● By slowing down the clock rise time with a capacitor, and thus effectively increasing the line length at
which point it becomes a transmission line, it is possible to remove the clock issue. A 56pF capacitor
has been mounted on the bottom side of the board between the SPI clock and GND. This however
reduces the maximum SPI clock speed and it is recommended to not run this faster than 30MHz (this
also depends on how much additional capacitance is added by connected extensions and needs to
be checked case by case). The capacitor was added on revision 4 on the bottom side of the EXT3
header.Atmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
19
6. Document revision history
Doc. Rev. Date Comment
B 15/03/2013 Added information about changes done on rev 5
A 11/02/2013 First releaseAtmel SAM4S Xplained Pro [USER GUIDE]
Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
20
7. Evaluation board/kit important notice
This evaluation board/kit is intended for use for FURTHER ENGINEERING, DEVELOPMENT,
DEMONSTRATION, OR EVALUATION PURPOSES ONLY. It is not a finished product and may not (yet)
comply with some or any technical or legal requirements that are applicable to finished products, including,
without limitation, directives regarding electromagnetic compatibility, recycling (WEEE), FCC, CE or UL
(except as may be otherwise noted on the board/kit). Atmel supplied this board/kit "AS IS," without any
warranties, with all faults, at the buyer's and further users' sole risk. The user assumes all responsibility
and liability for proper and safe handling of the goods. Further, the user indemnifies Atmel from all claims
arising from the handling or use of the goods. Due to the open construction of the product, it is the user's
responsibility to take any and all appropriate precautions with regard to electrostatic discharge and any other
technical or legal concerns.
EXCEPT TO THE EXTENT OF THE INDEMNITY SET FORTH ABOVE, NEITHER USER NOR
ATMEL SHALL BE LIABLE TO EACH OTHER FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES.
No license is granted under any patent right or other intellectual property right of Atmel covering or relating
to any machine, process, or combination in which such Atmel products or services might be or are used.
Mailing Address: Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USAAtmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com
© 2013 Atmel Corporation. All rights reserved. / Rev.: Atmel-42075B-MCU-Atmel SAM4S Xplained Pro-USER GUIDE-03/2013
Atmel®, Atmel logo and combinations thereof, AVR®, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel
Corporation or its subsidiaries. Windows® is a registered trademark of Microsoft Corporation in U.S. and or other countries. ARM® is a registered
trademark of ARM Ltd. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted
by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE,
ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR
ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to
specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise,
Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended
to support or sustain life.
APPLICATION NOTE
Atmel AVR600: STK600 Expansion, Routing and Socket
Boards
Atmel Microcontrollers
Introduction
This application note describes the process of developing new routing, socket and
expansion cards for the Atmel STK®
600. It also describes the physical parameters for
creating such cards.
The STK600 starter kit from Atmel has a sandwich design to match a specific part
package and pin out to the generic pin headers. It also features an expansion area
where most part pins are available.
While the variety of IC packages is relatively limited, the number of possible pinouts
increases rapidly with the number of pins. I.e. a 6-pin IC can have 720 (6!) different
pinouts!
The routing / socket card design provides a lowcost solution to support upcoming
devices as the socket is the cost driving factor.
STK600 users might also want to create their own routing cards to include
specialized hardware to prototype their own design.
Figure 1. STK600 router and socket card.
8170C−AVR−03/2013Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
2
Table of Contents
1. Routing Cards ...................................................................................... 3
1.1 Connector footprints .......................................................................................... 3
1.2 Physical dimensions and component placement .............................................. 4
1.3 Atmel STK600 socket connectors pinout .......................................................... 5
1.3.1 Signal descriptions .............................................................................. 8
2. Socket Cards ..................................................................................... 10
2.1 Power design issues ....................................................................................... 10
2.2 Connector MPN ............................................................................................... 10
2.3 Physical dimensions and component placement ............................................ 10
3. Expansion Cards ................................................................................ 11
3.1 Connector MPN ............................................................................................... 11
3.2 Physical dimensions and component placement ............................................ 12
3.3 Atmel STK600 expansion connectors pinout .................................................. 13
4. ID System .......................................................................................... 17
4.1 Signal usage ................................................................................................... 17
4.2 ID functions ..................................................................................................... 18
4.3 Examples ........................................................................................................ 19
5. Design Example ................................................................................. 20
6. Revision History ................................................................................. 22Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
3
1. Routing Cards
The routing cards sit between the generic socket card and the Atmel STK600. It has one pair of electric pads
underneath to mate with the STK600 spring loaded connector, and one pair of pads on top where the socket card
connector connects. A part specific card with the target IC soldered on can be viewed as a routing card without the top
pads.
1.1 Connector footprints
A routing card should have pads to mate with the following spring loaded connectors:
Table 1-1. Router card connectors.
Manufacturer and MPN Quantity Comment
SAMTEC, FSI-140-03-G-D-AD 2 80-pins to socket card (top)
SAMTEC, FSI-150-03-G-D-AD 2 100-pins to STK600 (bottom)
Figure 1-1. PCB land pattern for mating to FSI connectors. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
4
1.2 Physical dimensions and component placement
Figure 1-2. Routing card connector pad placement and dimensions.
Figure 1-3. Clip hole dimensions.
The board thickness should be 1.6mm to be compatible with the clips.
Note: Components on the main board might conflict with through hole mounted or secondary side mounted components.
Areas with such components are highlighted in Figure 1-4. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
5
Figure 1-4. Height restricted areas due to main board components.
1.3 Atmel STK600 socket connectors pinout
Figure 1-5 shows the pinout for the STK600 headers. This corresponds to the routing card connectors J1 and J2.
Figure 1-5. STK600 socket connectors’ pinout. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
6
Table 1-2. Atmel STK600 J201 left, routing card connector J1 pinout.
Signal name Pin number Signal name
VTG 2 1 GND
PA1 4 3 PA0
PA3 6 5 PA2
PA5 8 7 PA4
PA7 10 9 PA6
VTG 12 11 GND
PB1 14 13 PB0
PB3 16 15 PB2
PB5 18 17 PB4
PB7 20 19 PB6
VTG 22 21 GND
PC1 24 23 PC0
PC3 26 25 PC2
PC5 28 27 PC4
PC7 30 29 PC6
VTG 32 31 GND
PD1 34 33 PD0
PD3 36 35 PD2
PD5 38 37 PD4
PD7 40 39 PD6
VTG 42 41 GND
PE1 44 43 PE0
PE3 46 45 PE2
PE5 48 47 PE4
PE7 50 49 PE6
VTG 52 51 GND
PF1 54 53 PF0
PF3 56 55 PF2
PF5 58 57 PF4
PF7 60 59 PF6
VTG 62 61 GND
PG1 64 63 PG0
PG3 66 65 PG2
PG5 68 67 PG4
PG7 70 69 PG6
VTG 72 71 GND
PH1 74 73 PH0
PH3 76 75 PH2
PH5 78 77 PH4 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
7
PH7 80 79 PH6
VTG 82 81 GND
AREF0 84 83 XTAL1
AREF1 86 85 XTAL2
TGT_MOSI 88 87 GND
TGT_MISO 90 89 TOSC1
TGT_SCK 92 91 TOSC2
TDI 94 93 TGT_RESET
TDO 96 95 GND
TMS 98 97 Vext
TCK 100 99 Vcc
Table 1-3. Atmel STK600 J202 right, routing card connector J2 pinout.
Signal name Pin number Signal name
VTG 2 1 GND
PJ1 4 3 PJ0
PJ3 6 5 PJ2
PJ5 8 7 PJ4
PJ7 10 9 PJ6
VTG 12 11 GND
PK1 14 13 PK0
PK3 16 15 PK2
PK5 18 17 PK4
PK7 20 19 PK6
VTG 22 21 GND
PL1 24 23 PL0
PL3 26 25 PL2
PL5 28 27 PL4
PL7 30 29 PL6
VTG 32 31 GND
PM1 34 33 PM0
PM3 36 35 PM2
PM5 38 37 PM4
PM7 40 39 PM6
VTG 42 41 GND
PN1 44 43 PN0
PN3 46 45 PN2
PN5 48 47 PN4
PN7 50 49 PN6
VTG 52 51 GND
PP1 54 53 PP0 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
8
PP3 56 55 PP2
PP5 58 57 PP4
PP7 60 59 PP6
VTG 62 61 GND
PQ1 64 63 PQ0
PQ3 66 65 PQ2
PQ5 68 67 PQ4
PQ7 70 69 PQ6
VBUST 72 71 DP
UVCON 74 73 DN
Vcc 76 75 UID
Vext 78 77 GND
TGT_PDATA1 80 79 TGT_PDATA0
TGT_PDATA3 82 81 TGT_PDATA2
TGT_PDATA5 84 83 TGT_PDATA4
TGT_PDATA7 86 85 TGT_PDATA6
TGT_PCTRL1 88 87 TGT_PCTRL0
TGT_PCTRL3 90 89 TGT_PCTRL2
TGT_PCTRL5 92 91 TGT_PCTRL4
TGT_PCTRL7 94 93 TGT_PCTRL6
BOARD_ID1 96 95 BOARD_ID0
BOARD_ID3 98 97 BOARD_ID2
BOARD_ID5 100 99 BOARD_ID4
1.3.1 Signal descriptions
Table 1-4. Socket card connector pin description.
Atmel STK600 signal name MCU Comment
PAx, PBx etc PAx, PBx etc 1-to-1 MCU pin mapping
VTG Vcc Target supply rail controlled by Atmel AVR Studio®
/ STK600
GND GND
AREFx AREF Analog reference voltage, controlled by AVR Studio / STK600
XTALx XTALx Clock pins connected to oscillator on STK600
TGT_SCK, TGT_MISO, TGT_MOSI ISP pins ISP programming interface
TGT_TDI, TGT_TDO, TGT_TMS,
TGT_TCK JTAG pins JTAG programming interface
VBUST VBUS VBUS (sense) for USB
UID UID ID pin for USB OTG
UVCON UVCON
USB VBUS generation control for USB OTG. A low level on this
signal enables VBUS generation
DP, DN DP, DN USB differential pair
TGT_PDATA(0-7) (HV) data pins Data pins for high voltage (PP/HVSP) programming Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
9
TGT_CTRL0 (HV) BS2
Control signals for High voltage Parallel Programming / Serial
Programming. Refer to AVR datasheet for further information.
On AVRs with common XA1/BS2, XA1 is used.
On AVRs with common BS1/PAGEL, BS1 is used.
TGT_CTRL1 (HV) Ready/Busy
TGT_CTRL2 (HV) /OE
TGT_CTRL3 (HV) /WR
TGT_CTRL4 (HV) BS1
TGT_CTRL5 (HV) XA0
TGT_CTRL6 (HV) XA1
TGT_CTRL7 (HV) PAGEL
BOARD_IDn none
ID system for router / socket / expansion cards, see Chapter 4 -
ID System
Notes: 1. Not all AVR will have every pin (ex. two aref pins, tosc or usb).
2. A MCU pin will fan-out to both Pnx pin and to the programming interface(s) located at that pin. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
10
2. Socket Cards
Socket cards route each pin from the IC socket to separate pins on the spring loaded connectors on the bottom side,
facing the routing card.
2.1 Power design issues
As all routing is handled by the routing card, even power lines and power decoupling is ignored at the socket card. This
produces less than ideal power design, which may lead to unwanted noise, ground bounce, and other effects. It should
therefore be expected that heavily loaded designs cannot run at full speed on the Atmel STK600. Likewise, such power
design is not recommended for custom designs.
2.2 Connector MPN
Table 2-1. Socket card connector.
Manufacturer and MPN Quantity Comment
SAMTEC, FSI-140-03-G-D-AD 2 Spring loaded 80-pin connector
2.3 Physical dimensions and component placement
Figure 2-1. Socket card connector placement and dimensions.
ST1
J1 J2
45°
Note!
105mm
94mm
66mm
7mm
The board thickness should be 1.6mm to be compatible with the clips. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
11
3. Expansion Cards
The Atmel STK600 features an expansion area where cards for custom peripherals like memory expansion, LCD etc
can be placed. STK600 routes all part pins and power to the expansion card connectors.
3.1 Connector MPN
Table 3-1. Expansion card connector.
Manufacturer and MPN Quantity Comment
FCI, 61082-101402LF 2 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
12
3.2 Physical dimensions and component placement
Figure 3-1. Expansion card connector placement and dimensions.
There is no requirement to board thickness. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
13
3.3 Atmel STK600 expansion connectors pinout
Figure 3-2. Pinout for expansion connectors.
Table 3-2. STK600 J301 “expand0” connector pinout.
Signal name Pin number Signal name
VTG 2 1 GND
PA1 4 3 PA0
PA3 6 5 PA2
PA5 8 7 PA4
PA7 10 9 PA6
VTG 12 11 GND
PB1 14 13 PB0
PB3 16 15 PB2
PB5 18 17 PB4
PB7 20 19 PB6
VTG 22 21 GND
PC1 24 23 PC0
PC3 26 25 PC2
PC5 28 27 PC4
PC7 30 29 PC6
VTG 32 31 GND
PD1 34 33 PD0 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
14
PD3 36 35 PD2
PD5 38 37 PD4
PD7 40 39 PD6
VTG 42 41 GND
PE1 44 43 PE0
PE3 46 45 PE2
PE5 48 47 PE4
PE7 50 49 PE6
VTG 52 51 GND
PF1 54 53 PF0
PF3 56 55 PF2
PF5 58 57 PF4
PF7 60 59 PF6
VTG 62 61 GND
PG1 64 63 PG0
PG3 66 65 PG2
PG5 68 67 PG4
PG7 70 69 PG6
VTG 72 71 GND
PH1 74 73 PH0
PH3 76 75 PH2
PH5 78 77 PH4
PH7 80 79 PH6
VTG 82 81 GND
AREF0 84 83 XTAL1
AREF1 86 85 XTAL2
TGT_MOSI 88 87 GND
TGT_MISO 90 89 TOSC1
TGT_SCK 92 91 TOSC2
TDI 94 93 TGT_RESET
TDO 96 95 Vcc6
TMS 98 97 GND
TCK 100 99 Vcc6
Table 3-3. Atmel STK600 J302 “expand1” connector pinout.
Signal name Pin number Signal name
VTG 2 1 GND
PJ1 4 3 PJ0
PJ3 6 5 PJ2
PJ5 8 7 PJ4
PJ7 10 9 PJ6 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
15
VTG 12 11 GND
PK1 14 13 PK0
PK3 16 15 PK2
PK5 18 17 PK4
PK7 20 19 PK6
VTG 22 21 GND
PL1 24 23 PL0
PL3 26 25 PL2
PL5 28 27 PL4
PL7 30 29 PL6
VTG 32 31 GND
PM1 34 33 PM0
PM3 36 35 PM2
PM5 38 37 PM4
PM7 40 39 PM6
VTG 42 41 GND
PN1 44 43 PN0
PN3 46 45 PN2
PN5 48 47 PN4
PN7 50 49 PN6
VTG 52 51 GND
PP1 54 53 PP0
PP3 56 55 PP2
PP5 58 57 PP4
PP7 60 59 PP6
VTG 62 61 GND
PQ1 64 63 PQ0
PQ3 66 65 PQ2
PQ5 68 67 PQ4
PQ7 70 69 PQ6
Vext 72 71 GND
Vext 74 73 GND
GND 76 75 Vcc
GND 78 77 Vcc
TGT_PDATA1 80 79 TGT_PDATA0
TGT_PDATA3 82 81 TGT_PDATA2
TGT_PDATA5 84 83 TGT_PDATA4
TGT_PDATA7 86 85 TGT_PDATA6
TGT_PCTRL1 88 87 TGT_PCTRL0
TGT_PCTRL3 90 89 TGT_PCTRL2
TGT_PCTRL5 92 91 TGT_PCTRL4 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
16
TGT_PCTRL7 94 93 TGT_PCTRL6
Vcc3 96 95 GND
BOARD_ID1 98 97 BOARD_ID0
BOARD_ID7 100 99 BOARD_ID6 Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
17
4. ID System
The Atmel STK600 features an ID system to identify which routing, socket and expansion card is attached. The STK600
can impose voltage limitations based on the IDs, and Atmel AVR Studio will notify the user if the combination is
incorrect.
The ID system consists of two common output and two board unique input signals. Each input is one of sixteen possible
values based in the input signals – giving a total ID space of 256.
Three IDs are reserved for custom use and can be implemented without use of ICs.
Table 4-1. IDs reserved for custom use.
Type ID
Board limited to 1.8V 0xCA
Board limited to 3.3V 0xCC
No limit on voltage 0xCF
The ID 0xff indicates no board present.
4.1 Signal usage
Table 4-2. ID system signal usage.
Name Direction Function
BOARD_ID0 Output (A) Common output to functions
BOARD_ID1 Output (B) Common output to functions
BOARD_ID2 Input Input from routing card
BOARD_ID3 Input Input from routing card
BOARD_ID4 Input Input from socket card
BOARD_ID5 Input Input from socket card
BOARD_ID6 Input Input from expansion card
BOARD_ID7 Input Input from expansion card Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
18
4.2 ID functions
The functions and their output according to input A and B:
B A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
Functions as logic expressions:
Function Expression ID
0 0 0x0
1 A + B 0x1
2 AB 0x2
3 B 0x3
4 AB 0x4
5 A 0x5
6 ⊕ BA 0x6
7 AB 0x7
8 AB 0x8
9 ⊕ BA 0x9
10 A 0xA
11 B + AB 0xB
12 B 0xC
13 B A⋅+ B 0xD
14 A + B 0xE
15 1 0xF Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
19
4.3 Examples
For a socket card to report the ID 0xCA:
Route BOARD_ID1 to BOARD_ID4 and BOARD_ID0 to BOARD_ID5
Figure 4-1. Socket card ID example.
For an expansion card to report the ID 0xCF:
Route BOARD_ID0 to BOARD_ID6 and VCC to BOARD_ID7
Figure 4-2. Expansion card ID example.
For a router card to report the ID 0xCC:
Route BOARD_ID1 to both BOARD_ID2 and BOARD_ID3.
Figure 4-3. Routing card ID example. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
20
5. Design Example
To support a new package type one would typically start with designing the socket card. The pinout between the socket
card and routing card is not defined and left to the designer. An example is given in Figure 5-1.
Next is the design of the routing card (Figure 5-3). The routing card’s role is to connect each pin from the socket card to
the corresponding pin on the Atmel STK600. In addition to decoupling etc, the routing card should also fan-out the
correct signals to programming headers.
Each card in the stack has its own board_id pins; the routing card is responsible for passing on the signal to the socket
card.
Figure 5-1. Schema capture of socket card.
Both the socket and routing card must also include the clip holes:
Figure 5-2. Clip holes included in schematic. Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
21
Figure 5-3. Schema capture of routing card.
Copyright © 2008, Atmel Corporation Atmel AVR600: STK600 Expansion, Routing and Socket Boards [APPLICATION NOTE] 8170C−AVR−03/2013
22
6. Revision History
Doc. Rev. Date Comments
8170C 03/2013 Example schematics for the ID system are updated
8170B 12/2010
8170A 10/2008 Initial document release
Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1)(408) 441-0311
Fax: (+1)(408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Building
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81)(3) 6417-0300
Fax: (+81)(3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 8170C−AVR−03/2013
Atmel®, Atmel logo and combinations thereof, AVR®, AVR Studio®, Enabling Unlimited Possibilities®, STK®, and others are registered trademarks or trademarks of
Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
8159E–AVR–02/2013
Features
• High-performance, Low-power Atmel®AVR® 8-bit Microcontroller
• Advanced RISC Architecture
– 130 Powerful Instructions – Most Single-clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 16MIPS Throughput at 16MHz
– On-chip 2-cycle Multiplier
• High Endurance Non-volatile Memory segments
– 8KBytes of In-System Self-programmable Flash program memory
– 512Bytes EEPROM
– 1KByte Internal SRAM
– Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
– Data retention: 20 years at 85C/100 years at 25C(1)
– Optional Boot Code Section with Independent Lock Bits
• In-System Programming by On-chip Boot Program
• True Read-While-Write Operation
– Programming Lock for Software Security
• Atmel QTouch® library support
– Capacitive touch buttons, sliders and wheels
– Atmel QTouch and QMatrix acquisition
– Up to 64 sense channels
• Peripheral Features
– Two 8-bit Timer/Counters with Separate Prescaler, one Compare Mode
– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode
– Real Time Counter with Separate Oscillator
– Three PWM Channels
– 8-channel ADC in TQFP and QFN/MLF package
• Eight Channels 10-bit Accuracy
– 6-channel ADC in PDIP package
• Six Channels 10-bit Accuracy
– Byte-oriented Two-wire Serial Interface
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
• Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated RC Oscillator
– External and Internal Interrupt Sources
– Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and Standby
• I/O and Packages
– 23 Programmable I/O Lines
– 28-lead PDIP, 32-lead TQFP, and 32-pad QFN/MLF
• Operating Voltages
– 2.7 - 5.5V
– 0 - 16MHz
• Power Consumption at 4MHz, 3V, 25C
– Active: 3.6mA
– Idle Mode: 1.0mA
– Power-down Mode: 0.5µA
8-bit Atmel Microcontroller with 8KB In-System Programmable Flash
ATmega8AATmega8A [DATASHEET] 2
8159E–AVR–02/2013
1. Pin Configurations
Figure 1-1. Pinout ATmega8A
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
(INT1) PD3
(XCK/T0) PD4
GND
VCC
GND
VCC
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
PC1 (ADC1)
PC0 (ADC0)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK)
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
(OC1A) PB1
(SS/OC1B) PB2
(MOSI/OC2) PB3
(MISO) PB4
PD2 (INT0)
PD1 (TXD)
PD0 (RXD)
PC6 (RESET)
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
TQFP Top View
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
(RESET) PC6
(RXD) PD0
(TXD) PD1
(INT0) PD2
(INT1) PD3
(XCK/T0) PD4
VCC
GND
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
PC1 (ADC1)
PC0 (ADC0)
GND
AREF
AVCC
PB5 (SCK)
PB4 (MISO)
PB3 (MOSI/OC2)
PB2 (SS/OC1B)
PB1 (OC1A)
PDIP
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
MLF Top View
(INT1) PD3
(XCK/T0) PD4
GND
VCC
GND
VCC
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
PC1 (ADC1)
PC0 (ADC0)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK)
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
(OC1A) PB1
(SS/OC1B) PB2
(MOSI/OC2) PB3
(MISO) PB4
PD2 (INT0)
PD1 (TXD)
PD0 (RXD)
PC6 (RESET)
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
NOTE:
The large center pad underneath the MLF
packages is made of metal and internally
connected to GND. It should be soldered
or glued to the PCB to ensure good
mechanical stability. If the center pad is
left unconneted, the package might
loosen from the PCB.ATmega8A [DATASHEET] 3
8159E–AVR–02/2013
2. Overview
The Atmel®AVR® ATmega8A is a low-power CMOS 8-bit microcontroller based on the AVR RISC architecture. By
executing powerful instructions in a single clock cycle, the ATmega8A achieves throughputs approaching 1 MIPS
per MHz, allowing the system designer to optimize power consumption versus processing speed.
2.1 Block Diagram
Figure 2-1. Block Diagram
INTERNAL
OSCILLATOR
OSCILLATOR
WATCHDOG
TIMER
MCU CTRL.
& TIMING
OSCILLATOR
TIMERS/
COUNTERS
INTERRUPT
UNIT
STACK
POINTER
EEPROM
SRAM
STATUS
REGISTER
USART
PROGRAM
COUNTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
PROGRAMMING
LOGIC SPI
ADC
INTERFACE
COMP.
INTERFACE
PORTC DRIVERS/BUFFERS
PORTC DIGITAL INTERFACE
GENERAL
PURPOSE
REGISTERS
X
Y
Z
ALU
+
-
PORTB DRIVERS/BUFFERS
PORTB DIGITAL INTERFACE
PORTD DIGITAL INTERFACE
PORTD DRIVERS/BUFFERS
XTAL1
XTAL2
CONTROL
LINES
VCC
GND
MUX &
ADC
AGND
AREF
PC0 - PC6 PB0 - PB7
PD0 - PD7
AVR CPU
TWI
RESETATmega8A [DATASHEET] 4
8159E–AVR–02/2013
The Atmel®AVR® AVR core combines a rich instruction set with 32 general purpose working registers. All the 32
registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be
accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient
while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
The ATmega8A provides the following features: 8K bytes of In-System Programmable Flash with Read-WhileWrite
capabilities, 512 bytes of EEPROM, 1K byte of SRAM, 23 general purpose I/O lines, 32 general purpose
working registers, three flexible Timer/Counters with compare modes, internal and external interrupts, a serial programmable
USART, a byte oriented Two-wire Serial Interface, a 6-channel ADC (eight channels in TQFP and
QFN/MLF packages) with 10-bit accuracy, a programmable Watchdog Timer with Internal Oscillator, an SPI serial
port, and five software selectable power saving modes. The Idle mode stops the CPU while allowing the SRAM,
Timer/Counters, SPI port, and interrupt system to continue functioning. The Power-down mode saves the register
contents but freezes the Oscillator, disabling all other chip functions until the next Interrupt or Hardware Reset. In
Power-save mode, the asynchronous timer continues to run, allowing the user to maintain a timer base while the
rest of the device is sleeping. The ADC Noise Reduction mode stops the CPU and all I/O modules except asynchronous
timer and ADC, to minimize switching noise during ADC conversions. In Standby mode, the
crystal/resonator Oscillator is running while the rest of the device is sleeping. This allows very fast start-up combined
with low-power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The Flash Program memory
can be reprogrammed In-System through an SPI serial interface, by a conventional non-volatile memory
programmer, or by an On-chip boot program running on the AVR core. The boot program can use any interface to
download the application program in the Application Flash memory. Software in the Boot Flash Section will continue
to run while the Application Flash Section is updated, providing true Read-While-Write operation. By
combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel
ATmega8A is a powerful microcontroller that provides a highly-flexible and cost-effective solution to many embedded
control applications.
The Atmel AVR ATmega8A is supported with a full suite of program and system development tools, including C
compilers, macro assemblers, program simulators and evaluation kits.
2.2 Pin Descriptions
2.2.1 VCC
Digital supply voltage.
2.2.2 GND
Ground.
2.2.3 Port B (PB7:PB0) – XTAL1/XTAL2/TOSC1/TOSC2
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers
have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are
externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
Depending on the clock selection fuse settings, PB6 can be used as input to the inverting Oscillator amplifier and
input to the internal clock operating circuit.
Depending on the clock selection fuse settings, PB7 can be used as output from the inverting Oscillator amplifier.
If the Internal Calibrated RC Oscillator is used as chip clock source, PB7:6 is used as TOSC2:1 input for the Asynchronous
Timer/Counter2 if the AS2 bit in ASSR is set.ATmega8A [DATASHEET] 5
8159E–AVR–02/2013
The various special features of Port B are elaborated in “Alternate Functions of Port B” on page 56 and “System
Clock and Clock Options” on page 24.
2.2.4 Port C (PC5:PC0)
Port C is an 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers
have symmetrical drive characteristics with both high sink and source capability. As inputs, Port C pins that are
externally pulled low will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
2.2.5 PC6/RESET
If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical characteristics of PC6 differ
from those of the other pins of Port C.
If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low level on this pin for longer than the
minimum pulse length will generate a Reset, even if the clock is not running. The minimum pulse length is given in
Table 26-3 on page 228. Shorter pulses are not guaranteed to generate a Reset.
The various special features of Port C are elaborated on page 59.
2.2.6 Port D (PD7:PD0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers
have symmetrical drive characteristics with both high sink and source capability. As inputs, Port D pins that are
externally pulled low will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
Port D also serves the functions of various special features of the ATmega8A as listed on page 61.
2.2.7 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock
is not running. The minimum pulse length is given in Table 26-3 on page 228. Shorter pulses are not guaranteed to
generate a reset.
2.2.8 AVCC
AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). It should be externally connected
to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter.
Note that Port C (5:4) use digital supply voltage, VCC.
2.2.9 AREF
AREF is the analog reference pin for the A/D Converter.
2.2.10 ADC7:6 (TQFP and QFN/MLF Package Only)
In the TQFP and QFN/MLF package, ADC7:6 serve as analog inputs to the A/D converter. These pins are powered
from the analog supply and serve as 10-bit ADC channels.ATmega8A [DATASHEET] 6
8159E–AVR–02/2013
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for download on
http://www.atmel.com/avr.
Note: 1.
4. Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20
years at 85°C or 100 years at 25°C.
5. About Code Examples
This datasheet contains simple code examples that briefly show how to use various parts of the device. These
code examples assume that the part specific header file is included before compilation. Be aware that not all C
compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent.
Please confirm with the C compiler documentation for more details.
6. Capacitive touch sensing
The Atmel® QTouch® Library provides a simple to use solution to realize touch sensitive interfaces on most Atmel
AVR® microcontrollers. The QTouch Library includes support for the QTouch and QMatrix® acquisition methods.
Touch sensing can be added to any application by linking the appropriate Atmel QTouch Library for the AVR Microcontroller.
This is done by using a simple set of APIs to define the touch channels and sensors, and then calling the
touch sensing API’s to retrieve the channel information and determine the touch sensor states.
The QTouch Library is FREE and downloadable from the Atmel website at the following location:
www.atmel.com/qtouchlibrary. For implementation details and other information, refer to the Atmel QTouch Library
User Guide - also available for download from the Atmel website.ATmega8A [DATASHEET] 7
8159E–AVR–02/2013
7. AVR CPU Core
7.1 Overview
This section discusses the Atmel®AVR® core architecture in general. The main function of the CPU core is to
ensure correct program execution. The CPU must therefore be able to access memories, perform calculations,
control peripherals, and handle interrupts.
Figure 7-1. Block Diagram of the AVR MCU Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with separate memories
and buses for program and data. Instructions in the Program memory are executed with a single level pipelining.
While one instruction is being executed, the next instruction is pre-fetched from the Program memory. This concept
enables instructions to be executed in every clock cycle. The Program memory is In-System Reprogrammable
Flash memory.
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle
access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands
are output from the Register File, the operation is executed, and the result is stored back in the Register File
– in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing –
enabling efficient address calculations. One of the these address pointers can also be used as an address pointer
for look up tables in Flash Program memory. These added function registers are the 16-bit X-, Y-, and Z-register,
described later in this section.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
i/O Module 2
i/O Module1
i/O Module nATmega8A [DATASHEET] 8
8159E–AVR–02/2013
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single
register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated
to reflect information about the result of the operation.
The Program flow is provided by conditional and unconditional jump and call instructions, able to directly address
the whole address space. Most AVR instructions have a single 16-bit word format. Every Program memory
address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot program section and the Application program
section. Both sections have dedicated Lock Bits for write and read/write protection. The SPM instruction that writes
into the Application Flash memory section must reside in the Boot program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack
is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total
SRAM size and the usage of the SRAM. All user programs must initialize the SP in the reset routine (before subroutines
or interrupts are executed). The Stack Pointer SP is read/write accessible in the I/O space. The data
SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional global interrupt enable bit in
the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have
priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the
priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other
I/O functions. The I/O Memory can be accessed directly, or as the Data Space locations following those of the Register
File, 0x20 - 0x5F.
7.2 Arithmetic Logic Unit – ALU
The high-performance Atmel®AVR® ALU operates in direct connection with all the 32 general purpose working registers.
Within a single clock cycle, arithmetic operations between general purpose registers or between a register
and an immediate are executed. The ALU operations are divided into three main categories – arithmetic, logical,
and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both
signed/unsigned multiplication and fractional format. See the “Instruction Set” section for a detailed description.
7.3 Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This
information can be used for altering program flow in order to perform conditional operations. Note that the Status
Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases
remove the need for using the dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored when returning
from an interrupt. This must be handled by software.
7.3.1 SREG – The AVR Status Register
Bit 7 6 5 4 3 2 1 0
I T H S V N Z C SREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 9
8159E–AVR–02/2013
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control
is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts
are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an
interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set
and cleared by the application with the SEI and CLI instructions, as described in the Instruction Set Reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated
bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be
copied into a bit in a register in the Register File by the BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful in BCD arithmetic.
See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement Overflow Flag V. See
the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the “Instruction Set Description”
for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction Set Description” for
detailed information.
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a Carry in an arithmetic or logic operation. See the “Instruction Set Description” for
detailed information.
7.4 General Purpose Register File
The Register File is optimized for the Atmel®AVR® Enhanced RISC instruction set. In order to achieve the required
performance and flexibility, the following input/output schemes are supported by the Register File:
• One 8-bit output operand and one 8-bit result input.
• Two 8-bit output operands and one 8-bit result input.
• Two 8-bit output operands and one 16-bit result input.
• One 16-bit output operand and one 16-bit result input.
Figure 7-2 shows the structure of the 32 general purpose working registers in the CPU.ATmega8A [DATASHEET] 10
8159E–AVR–02/2013
Figure 7-2. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single
cycle instructions.
As shown in Figure 7-2, each register is also assigned a Data memory address, mapping them directly into the first
32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory
organization provides great flexibility in access of the registers, as the X-, Y-, and Z-pointer Registers can be set to
index any register in the file.
7.4.1 The X-register, Y-register and Z-register
The registers R26:R31 have some added functions to their general purpose usage. These registers are 16-bit
address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y and Z are
defined as described in Figure 7-3.
Figure 7-3. The X-, Y- and Z-Registers
In the different addressing modes these address registers have functions as fixed displacement, automatic increment,
and automatic decrement (see the Instruction Set Reference for details).
7.5 Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses
after interrupts and subroutine calls. Note that the Stack is implemented as growing from higher to lower memory
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte
15 XH XL 0
X-register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 7 0 7 0
R31 (0x1F) R30 (0x1E)ATmega8A [DATASHEET] 11
8159E–AVR–02/2013
locations. The Stack Pointer Register always points to the top of the Stack. The Stack Pointer points to the data
SRAM Stack area where the Subroutine and Interrupt Stacks are located. A Stack PUSH command will decrease
the Stack Pointer.
The Stack in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts
are enabled. Initial Stack Pointer value equals the last address of the internal SRAM and the Stack Pointer must be
set to point above start of the SRAM, see Figure 8-2 on page 16.
See Table 7-1 for Stack Pointer details.
The Atmel®AVR® Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually
used is implementation dependent. Note that the data space in some implementations of the AVR architecture is
so small that only SPL is needed. In this case, the SPH Register will not be present.
7.5.1 SPH and SPL – Stack Pointer High and Low Register
7.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The Atmel®AVR®CPU is
driven by the CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock
division is used.
Figure 7-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture
and the fast-access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with
the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit.
Table 7-1. Stack Pointer instructions
Instruction Stack pointer Description
PUSH Decremented by 1 Data is pushed onto the stack
CALL
ICALL
RCALL
Decremented by 2 Return address is pushed onto the stack with a subroutine call or
interrupt
POP Incremented by 1 Data is popped from the stack
RET
RETI
Incremented by 2 Return address is popped from the stack with return from
subroutine or return from interrupt
Bit 15 14 13 12 11 10 9 8
SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
00000000ATmega8A [DATASHEET] 12
8159E–AVR–02/2013
Figure 7-4. The Parallel Instruction Fetches and Instruction Executions
Figure 7-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using
two register operands is executed, and the result is stored back to the destination register.
Figure 7-5. Single Cycle ALU Operation
7.7 Reset and Interrupt Handling
The Atmel®AVR® provides several different interrupt sources. These interrupts and the separate Reset Vector
each have a separate Program Vector in the Program memory space. All interrupts are assigned individual enable
bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to
enable the interrupt. Depending on the Program Counter value, interrupts may be automatically disabled when
Boot Lock Bits BLB02 or BLB12 are programmed. This feature improves software security. See the section “Memory
Programming” on page 207 for details.
The lowest addresses in the Program memory space are by default defined as the Reset and Interrupt Vectors.
The complete list of Vectors is shown in “Interrupts” on page 44. The list also determines the priority levels of the
different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next
is INT0 – the External Interrupt Request 0. The Interrupt Vectors can be moved to the start of the boot Flash section
by setting the Interrupt Vector Select (IVSEL) bit in the General Interrupt Control Register (GICR). Refer to
“Interrupts” on page 44 for more information. The Reset Vector can also be moved to the start of the boot Flash
section by programming the BOOTRST Fuse, see “Boot Loader Support – Read-While-Write Self-Programming”
on page 194.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software
can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current
interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. For
these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPUATmega8A [DATASHEET] 13
8159E–AVR–02/2013
handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing
a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding
interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the
flag is cleared by software. Similarly, if one or more interrupt conditions occur while the global interrupt enable bit is
cleared, the corresponding Interrupt Flag(s) will be set and remembered until the global interrupt enable bit is set,
and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily
have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will
not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction
before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when
returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be
executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example
shows how this can be used to avoid interrupts during the timed EEPROM write sequence.
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending
interrupts, as shown in the following example.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMWE ; start EEPROM write
sbi EECR, EEWE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1< xxx
:. :. :.
Table 12-2. Reset and Interrupt Vectors Placement
BOOTRST(1) IVSEL Reset Address Interrupt Vectors Start Address
1 0 0x000 0x001
1 1 0x000 Boot Reset Address + 0x001
0 0 Boot Reset Address 0x001
0 1 Boot Reset Address Boot Reset Address + 0x001ATmega8A [DATASHEET] 46
8159E–AVR–02/2013
When the BOOTRST Fuse is unprogrammed, the boot section size set to 2K bytes and the IVSEL bit in the GICR
Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and
Interrupt Vector Addresses is:
AddressLabels Code Comments
$000 rjmp RESET ; Reset handler
;
$001 RESET:ldi r16,high(RAMEND); Main program start
$002 out SPH,r16 ; Set Stack Pointer to top of RAM
$003 ldi r16,low(RAMEND)
$004 out SPL,r16
$005 sei ; Enable interrupts
$006 xxx
;
.org $c01
$c01 rjmp EXT_INT0 ; IRQ0 Handler
$c02 rjmp EXT_INT1 ; IRQ1 Handler
:. :. :. ;
$c12 rjmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST Fuse is programmed and the boot section size set to 2K bytes, the most typical and general
program setup for the Reset and Interrupt Vector Addresses is:
AddressLabels Code Comments
.org $001
$001 rjmp EXT_INT0 ; IRQ0 Handler
$002 rjmp EXT_INT1 ; IRQ1 Handler
:. :. :. ;
$012 rjmp SPM_RDY ; Store Program Memory Ready Handler
;
.org $c00
$c00 rjmp RESET ; Reset handler
;
$c01 RESET:ldi r16,high(RAMEND); Main program start
$c02 out SPH,r16 ; Set Stack Pointer to top of RAM
$c03 ldi r16,low(RAMEND)
$c04 out SPL,r16
$c05 sei ; Enable interrupts
$c06 xxxATmega8A [DATASHEET] 47
8159E–AVR–02/2013
When the BOOTRST Fuse is programmed, the boot section size set to 2K bytes, and the IVSEL bit in the GICR
Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and
Interrupt Vector Addresses is:
AddressLabels Code Comments
;
.org $c00
$c00 rjmp RESET ; Reset handler
$c01 rjmp EXT_INT0 ; IRQ0 Handler
$c02 rjmp EXT_INT1 ; IRQ1 Handler
:. :. :. ;
$c12 rjmp SPM_RDY ; Store Program Memory Ready Handler
$c13 RESET: ldi r16,high(RAMEND); Main program start
$c14 out SPH,r16 ; Set Stack Pointer to top of RAM
$c15 ldi r16,low(RAMEND)
$c16 out SPL,r16
$c17 sei ; Enable interrupts
$c18 xxx
12.1.1 Moving Interrupts Between Application and Boot Space
The General Interrupt Control Register controls the placement of the Interrupt Vector table.
12.2 Register Description
12.2.1 GICR – General Interrupt Control Register
• Bit 1 – IVSEL: Interrupt Vector Select
When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash memory. When this
bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual
address of the start of the boot Flash section is determined by the BOOTSZ Fuses. Refer to the section “Boot
Loader Support – Read-While-Write Self-Programming” on page 194 for details. To avoid unintentional changes of
Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit:
1. Write the Interrupt Vector Change Enable (IVCE) bit to one.
2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE
is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts
remain disabled for four cycles. The I-bit in the Status Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed, interrupts
are disabled while executing from the Application section. If Interrupt Vectors are placed in the Application section
and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer
to the section “Boot Loader Support – Read-While-Write Self-Programming” on page 194 for details on Boot Lock
Bits.
Bit 7 6 5 4 3 2 1 0
INT1 INT0 – – – – IVSEL IVCE GICR
Read/Write R/W R/W R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 48
8159E–AVR–02/2013
• Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four
cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the
IVSEL description above. See Code Example below.
Assembly Code Example
Move_interrupts:
; Enable change of Interrupt Vectors
ldi r16, (1< CSn2:0 > 1). The number
of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution. However, care
must be taken if the other Timer/Counter that shares the same prescaler also uses prescaling. A prescaler reset
will affect the prescaler period for all Timer/Counters it is connected to.
16.4 External Clock Source
An external clock source applied to the T1/T0 pin can be used as Timer/Counter clock (clkT1/clkT0). The T1/T0 pin
is sampled once every system clock cycle by the pin synchronization logic. The synchronized (sampled) signal is
then passed through the edge detector. Figure 16-1 shows a functional equivalent block diagram of the T1/T0 synchronization
and edge detector logic. The registers are clocked at the positive edge of the internal system clock
(clkI/O). The latch is transparent in the high period of the internal system clock.
The edge detector generates one clkT1/clkT0 pulse for each positive (CSn2:0 = 7) or negative (CSn2:0 = 6) edge it
detects.
Figure 16-1. T1/T0 Pin Sampling
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has
been applied to the T1/T0 pin to the counter is updated.
Tn_sync
(To Clock
Select Logic)
Synchronization Edge Detector
D Q D Q
LE
Tn D Q
clkI/OATmega8A [DATASHEET] 72
8159E–AVR–02/2013
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least one system clock
cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling.
The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2)
given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it
can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system
clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended
that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 16-2. Prescaler for Timer/Counter0 and Timer/Counter1(1)
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 16-1.
16.5 Register Description
16.5.1 SFIOR – Special Function IO Register
• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0
When this bit is written to one, the Timer/Counter1 and Timer/Counter0 prescaler will be reset. The bit will be
cleared by hardware after the operation is performed. Writing a zero to this bit will have no effect. Note that
Timer/Counter1 and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both timers.
This bit will always be read as zero.
PSR10
Clear
clkT1 clkT0
T1
T0
clkI/O
Synchronization
Synchronization
Bit 7 6 5 4 3 2 1 0
– – – – ACME PUD PSR2 PSR10 SFIOR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 73
8159E–AVR–02/2013
17. 16-bit Timer/Counter1
17.1 Features • True 16-bit Design (i.e., allows 16-bit PWM)
• Two Independent Output Compare Units
• Double Buffered Output Compare Registers
• One Input Capture Unit
• Input Capture Noise Canceler
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• External Event Counter
• Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)
17.2 Overview
The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation,
and signal timing measurement. Most register and bit references in this section are written in general form. A lower
case “n” replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit channel.
However, when using the register or bit defines in a program, the precise form must be used i.e., TCNT1 for
accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 17-1. For the actual placement of I/O
pins, refer to “Pin Configurations” on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are
shown in bold. The device-specific I/O Register and bit locations are listed in the “Register Description” on page 92.ATmega8A [DATASHEET] 74
8159E–AVR–02/2013
Figure 17-1. 16-bit Timer/Counter Block Diagram(1)
Note: 1. Refer to “Pin Configurations” on page 2, Table 13-2 on page 56, and Table 13-8 on page 61 for Timer/Counter1 pin
placement and description.
17.2.1 Registers
The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Register (ICR1) are all
16-bit registers. Special procedures must be followed when accessing the 16-bit registers. These procedures are
described in the section “Accessing 16-bit Registers” on page 75. The Timer/Counter Control Registers
(TCCR1A/B) are 8-bit registers and have no CPU access restrictions. Interrupt requests (abbreviated to Int.Req. in
the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked
with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these registers
are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T1 pin. The
Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement)
its value. The Timer/Counter is inactive when no clock source is selected. The output from the clock select logic is
referred to as the timer clock (clkT1).
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter value at all time.
The result of the compare can be used by the waveform generator to generate a PWM or variable frequency output
on the Output Compare Pin (OC1A/B). See “Output Compare Units” on page 81. The Compare Match event will
also set the Compare Match Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request.
Clock Select
Timer/Counter
DATA BUS
OCRnA
OCRnB
ICRn
=
=
TCNTn
Waveform
Generation
Waveform
Generation
OCnA
OCnB
Noise
Canceler
ICPn
=
Fixed
TOP
Values
Edge
Detector
Control Logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(Int. Req.)
OCFnA
(Int. Req.)
OCFnB
(Int.Req.)
ICFn (Int.Req.)
TCCRnA TCCRnB
( From Analog
Comparator Ouput )
Tn Edge
Detector
( From Prescaler )
clkTnATmega8A [DATASHEET] 75
8159E–AVR–02/2013
The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered) event on
either the Input Capture Pin (ICP1) or on the Analog Comparator pins (see “Analog Comparator” on page 179).
The Input Capture unit includes a digital filtering unit (Noise Canceler) for reducing the chance of capturing noise
spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined by either the
OCR1A Register, the ICR1 Register, or by a set of fixed values. When using OCR1A as TOP value in a PWM
mode, the OCR1A Register can not be used for generating a PWM output. However, the TOP value will in this
case be double buffered allowing the TOP value to be changed in run time. If a fixed TOP value is required, the
ICR1 Register can be used as an alternative, freeing the OCR1A to be used as PWM output.
17.2.2 Definitions
The following definitions are used extensively throughout the document:
17.2.3 Compatibility
The 16-bit Timer/Counter has been updated and improved from previous versions of the 16-bit AVR Timer/Counter.
This 16-bit Timer/Counter is fully compatible with the earlier version regarding:
• All 16-bit Timer/Counter related I/O Register address locations, including Timer Interrupt Registers.
• Bit locations inside all 16-bit Timer/Counter Registers, including Timer Interrupt Registers.
• Interrupt Vectors.
• The following control bits have changed name, but have same functionality and register location:
• PWM10 is changed to WGM10.
• PWM11 is changed to WGM11.
• CTC1 is changed to WGM12.
The following bits are added to the 16-bit Timer/Counter Control Registers:
• FOC1A and FOC1B are added to TCCR1A.
• WGM13 is added to TCCR1B.
The 16-bit Timer/Counter has improvements that will affect the compatibility in some special cases.
17.3 Accessing 16-bit Registers
The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus.
The 16-bit register must be byte accessed using two read or write operations. The 16-bit timer has a single 8-bit
register for temporary storing of the High byte of the 16-bit access. The same temporary register is shared between
all 16-bit registers within the 16-bit timer. Accessing the Low byte triggers the 16-bit read or write operation. When
the Low byte of a 16-bit register is written by the CPU, the High byte stored in the temporary register, and the Low
byte written are both copied into the 16-bit register in the same clock cycle. When the Low byte of a 16-bit register
is read by the CPU, the High byte of the 16-bit register is copied into the temporary register in the same clock cycle
as the Low byte is read.
Table 17-1. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be one of the fixed values:
0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCR1A or ICR1 Register.
The assignment is dependent of the mode of operation.ATmega8A [DATASHEET] 76
8159E–AVR–02/2013
Not all 16-bit accesses uses the temporary register for the High byte. Reading the OCR1A/B 16-bit registers does
not involve using the temporary register.
To do a 16-bit write, the High byte must be written before the Low byte. For a 16-bit read, the Low byte must be
read before the High byte.
The following code examples show how to access the 16-bit Timer Registers assuming that no interrupts updates
the temporary register. The same principle can be used directly for accessing the OCR1A/B and ICR1 Registers.
Note that when using “C”, the compiler handles the 16-bit access.
Note: 1. See “About Code Examples” on page 6.
The assembly code example returns the TCNT1 value in the r17:r16 Register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two
instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the
same or any other of the 16-bit Timer Registers, then the result of the access outside the interrupt will be corrupted.
Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable
the interrupts during the 16-bit access.
Assembly Code Example(1)
:.
; Set TCNT1 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT1H,r17
out TCNT1L,r16
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
:.
C Code Example(1)
unsigned int i;
:.
/* Set TCNT1 to 0x01FF */
TCNT1 = 0x1FF;
/* Read TCNT1 into i */
i = TCNT1;
:.ATmega8A [DATASHEET] 77
8159E–AVR–02/2013
The following code examples show how to do an atomic read of the TCNT1 Register contents. Reading any of the
OCR1A/B or ICR1 Registers can be done by using the same principle.
Note: 1. See “About Code Examples” on page 6.
The assembly code example returns the TCNT1 value in the r17:r16 Register pair.
Assembly Code Example(1)
TIM16_ReadTCNT1:
; Save Global Interrupt Flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore Global Interrupt Flag
out SREG,r18
ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save Global Interrupt Flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore Global Interrupt Flag */
SREG = sreg;
return i;
}ATmega8A [DATASHEET] 78
8159E–AVR–02/2013
The following code examples show how to do an atomic write of the TCNT1 Register contents. Writing any of the
OCR1A/B or ICR1 Registers can be done by using the same principle.
Note: 1. See “About Code Examples” on page 6.
The assembly code example requires that the r17:r16 Register pair contains the value to be written to TCNT1.
17.3.1 Reusing the Temporary High Byte Register
If writing to more than one 16-bit register where the High byte is the same for all registers written, then the High
byte only needs to be written once. However, note that the same rule of atomic operation described previously also
applies in this case.
17.4 Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the
clock select logic which is controlled by the clock select (CS12:0) bits located in the Timer/Counter Control Register
B (TCCR1B). For details on clock sources and prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers”
on page 71.
17.5 Counter Unit
The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit. Figure 17-2 shows
a block diagram of the counter and its surroundings.
Assembly Code Example(1)
TIM16_WriteTCNT1:
; Save Global Interrupt Flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore Global Interrupt Flag
out SREG,r18
ret
C Code Example(1)
void TIM16_WriteTCNT1( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save Global Interrupt Flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore Global Interrupt Flag */
SREG = sreg;
}ATmega8A [DATASHEET] 79
8159E–AVR–02/2013
Figure 17-2. Counter Unit Block Diagram
Signal description (internal signals):
count Increment or decrement TCNT1 by 1.
direction Select between increment and decrement.
clear Clear TCNT1 (set all bits to zero).
clkT1 Timer/Counter clock.
TOP Signalize that TCNT1 has reached maximum value.
BOTTOM Signalize that TCNT1 has reached minimum value (zero).
The 16-bit counter is mapped into two 8-bit I/O memory locations: counter high (TCNT1H) containing the upper
eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight bits. The TCNT1H Register can
only be indirectly accessed by the CPU. When the CPU does an access to the TCNT1H I/O location, the CPU
accesses the High byte temporary register (TEMP). The temporary register is updated with the TCNT1H value
when the TCNT1L is read, and TCNT1H is updated with the temporary register value when TCNT1L is written. This
allows the CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. It is
important to notice that there are special cases of writing to the TCNT1 Register when the counter is counting that
will give unpredictable results. The special cases are described in the sections where they are of importance.
Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer
clock (clkT1). The clkT1 can be generated from an external or internal clock source, selected by the clock select bits
(CS12:0). When no clock source is selected (CS12:0 = 0) the timer is stopped. However, the TCNT1 value can be
accessed by the CPU, independent of whether clkT1 is present or not. A CPU write overrides (has priority over) all
counter clear or count operations.
The counting sequence is determined by the setting of the Waveform Generation mode bits (WGM13:0) located in
the Timer/Counter Control Registers A and B (TCCR1A and TCCR1B). There are close connections between how
the counter behaves (counts) and how waveforms are generated on the Output Compare Outputs OC1x. For more
details about advanced counting sequences and waveform generation, see “Modes of Operation” on page 84.
The Timer/Counter Overflow (TOV1) fLag is set according to the mode of operation selected by the WGM13:0 bits.
TOV1 can be used for generating a CPU interrupt.
17.6 Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give them a timestamp
indicating time of occurrence. The external signal indicating an event, or multiple events, can be applied via
the ICP1 pin or alternatively, via the Analog Comparator unit. The time-stamps can then be used to calculate freTEMP
(8-bit)
DATA BUS (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit) Control Logic
count
clear
direction
TOVn
(Int. Req.)
Clock Select
TOP BOTTOM
Tn Edge
Detector
( From Prescaler )
clkTnATmega8A [DATASHEET] 80
8159E–AVR–02/2013
quency, duty-cycle, and other features of the signal applied. Alternatively the time-stamps can be used for creating
a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 17-3. The elements of the block diagram
that are not directly a part of the Input Capture unit are gray shaded. The small “n” in register and bit names indicates
the Timer/Counter number.
Figure 17-3. Input Capture Unit Block Diagram
When a change of the logic level (an event) occurs on the Input Capture Pin (ICP1), alternatively on the Analog
Comparator Output (ACO), and this change confirms to the setting of the edge detector, a capture will be triggered.
When a capture is triggered, the 16-bit value of the counter (TCNT1) is written to the Input Capture Register
(ICR1). The Input Capture Flag (ICF1) is set at the same system clock as the TCNT1 value is copied into ICR1
Register. If enabled (TICIE1 = 1), the Input Capture Flag generates an Input Capture interrupt. The ICF1 Flag is
automatically cleared when the interrupt is executed. Alternatively the ICF1 Flag can be cleared by software by
writing a logical one to its I/O bit location.
Reading the 16-bit value in the Input Capture Register (ICR1) is done by first reading the Low byte (ICR1L) and
then the High byte (ICR1H). When the Low byte is read the High byte is copied into the High byte temporary register
(TEMP). When the CPU reads the ICR1H I/O location it will access the TEMP Register.
The ICR1 Register can only be written when using a Waveform Generation mode that utilizes the ICR1 Register for
defining the counter’s TOP value. In these cases the Waveform Generation mode (WGM13:0) bits must be set
before the TOP value can be written to the ICR1 Register. When writing the ICR1 Register the High byte must be
written to the ICR1H I/O location before the Low byte is written to ICR1L.
For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers” on page 75.
17.6.1 Input Capture Pin Source
The main trigger source for the Input Capture unit is the Input Capture Pin (ICP1). Timer/Counter 1 can alternatively
use the Analog Comparator Output as trigger source for the Input Capture unit. The Analog Comparator is
selected as trigger source by setting the Analog Comparator Input Capture (ACIC) bit in the Analog Comparator
ICFn (Int. Req.)
Analog
Comparator
WRITE ICRn (16-bit Register)
ICRnH (8-bit)
Noise
Canceler
ICPn
Edge
Detector
TEMP (8-bit)
DATA BUS (8-bit)
ICRnL (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
ACO* ACIC* ICNC ICESATmega8A [DATASHEET] 81
8159E–AVR–02/2013
Control and Status Register (ACSR). Be aware that changing trigger source can trigger a capture. The Input Capture
Flag must therefore be cleared after the change.
Both the Input Capture Pin (ICP1) and the Analog Comparator Output (ACO) inputs are sampled using the same
technique as for the T1 pin (Figure 16-1 on page 71). The edge detector is also identical. However, when the noise
canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system
clock cycles. Note that the input of the noise canceler and edge detector is always enabled unless the Timer/Counter
is set in a Waveform Generation mode that uses ICR1 to define TOP.
An Input Capture can be triggered by software by controlling the port of the ICP1 pin.
17.6.2 Noise Canceler
The noise canceler improves noise immunity by using a simple digital filtering scheme. The noise canceler input is
monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge
detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC1) bit in Timer/Counter Control
Register B (TCCR1B). When enabled the noise canceler introduces additional four system clock cycles of delay
from a change applied to the input, to the update of the ICR1 Register. The noise canceler uses the system clock
and is therefore not affected by the prescaler.
17.6.3 Using the Input Capture Unit
The main challenge when using the Input Capture unit is to assign enough processor capacity for handling the
incoming events. The time between two events is critical. If the processor has not read the captured value in the
ICR1 Register before the next event occurs, the ICR1 will be overwritten with a new value. In this case the result of
the capture will be incorrect.
When using the Input Capture interrupt, the ICR1 Register should be read as early in the interrupt handler routine
as possible. Even though the Input Capture interrupt has relatively high priority, the maximum interrupt response
time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests.
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is actively changed during
operation, is not recommended.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after each capture.
Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. After a
change of the edge, the Input Capture Flag (ICF1) must be cleared by software (writing a logical one to the I/O bit
location). For measuring frequency only, the clearing of the ICF1 Flag is not required (if an interrupt handler is
used).
17.7 Output Compare Units
The 16-bit comparator continuously compares TCNT1 with the Output Compare Register (OCR1x). If TCNT equals
OCR1x the comparator signals a match. A match will set the Output Compare Flag (OCF1x) at the next timer clock
cycle. If enabled (OCIE1x = 1), the Output Compare Flag generates an Output Compare interrupt. The OCF1x Flag
is automatically cleared when the interrupt is executed. Alternatively the OCF1x Flag can be cleared by software
by writing a logical one to its I/O bit location. The waveform generator uses the match signal to generate an output
according to operating mode set by the Waveform Generation mode (WGM13:0) bits and Compare Output mode
(COM1x1:0) bits. The TOP and BOTTOM signals are used by the waveform generator for handling the special
cases of the extreme values in some modes of operation (See “Modes of Operation” on page 84.)
A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (i.e. counter resolution).
In addition to the counter resolution, the TOP value defines the period time for waveforms generated by the
waveform generator.ATmega8A [DATASHEET] 82
8159E–AVR–02/2013
Figure 17-4 shows a block diagram of the Output Compare unit. The small “n” in the register and bit names indicates
the device number (n = 1 for Timer/Counter 1), and the “x” indicates Output Compare unit (A/B). The
elements of the block diagram that are not directly a part of the Output Compare unit are gray shaded.
Figure 17-4. Output Compare Unit, Block Diagram
The OCR1x Register is double buffered when using any of the twelve Pulse Width Modulation (PWM) modes. For
the normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double
buffering synchronizes the update of the OCR1x Compare Register to either TOP or BOTTOM of the counting
sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby
making the output glitch-free.
The OCR1x Register access may seem complex, but this is not case. When the double buffering is enabled, the
CPU has access to the OCR1x Buffer Register, and if double buffering is disabled the CPU will access the OCR1x
directly. The content of the OCR1x (Buffer or Compare) Register is only changed by a write operation (the
Timer/Counter does not update this register automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is
not read via the High byte temporary register (TEMP). However, it is a good practice to read the Low byte first as
when accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Register since the
compare of all 16-bit is done continuously. The High byte (OCR1xH) has to be written first. When the High byte I/O
location is written by the CPU, the TEMP Register will be updated by the value written. Then when the Low byte
(OCR1xL) is written to the lower eight bits, the High byte will be copied into the upper 8-bits of either the OCR1x
buffer or OCR1x Compare Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers” on page 75.
17.7.1 Force Output Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by writing a one to
the Force Output Compare (FOC1x) bit. Forcing Compare Match will not set the OCF1x Flag or reload/clear the
timer, but the OC1x pin will be updated as if a real Compare Match had occurred (the COM1x1:0 bits settings
define whether the OC1x pin is set, cleared or toggled).
OCFnx (Int.Req.)
= (16-bit Comparator )
OCRnx Buffer (16-bit Register)
OCRnxH Buf. (8-bit)
OCnx
TEMP (8-bit)
DATA BUS (8-bit)
OCRnxL Buf. (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
WGMn3:0 COMnx1:0
OCRnx (16-bit Register)
OCRnxH (8-bit) OCRnxL (8-bit)
Waveform Generator
TOP
BOTTOMATmega8A [DATASHEET] 83
8159E–AVR–02/2013
17.7.2 Compare Match Blocking by TCNT1 Write
All CPU writes to the TCNT1 Register will block any Compare Match that occurs in the next timer clock cycle, even
when the timer is stopped. This feature allows OCR1x to be initialized to the same value as TCNT1 without triggering
an interrupt when the Timer/Counter clock is enabled.
17.7.3 Using the Output Compare Unit
Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock cycle, there are
risks involved when changing TCNT1 when using any of the Output Compare channels, independent of whether
the Timer/Counter is running or not. If the value written to TCNT1 equals the OCR1x value, the Compare Match will
be missed, resulting in incorrect waveform generation. Do not write the TCNT1 equal to TOP in PWM modes with
variable TOP values. The Compare Match for the TOP will be ignored and the counter will continue to 0xFFFF.
Similarly, do not write the TCNT1 value equal to BOTTOM when the counter is downcounting.
The setup of the OC1x should be performed before setting the Data Direction Register for the port pin to output.
The easiest way of setting the OC1x value is to use the Force Output Compare (FOC1x) strobe bits in Normal
mode. The OC1x Register keeps its value even when changing between Waveform Generation modes.
Be aware that the COM1x1:0 bits are not double buffered together with the compare value. Changing the
COM1x1:0 bits will take effect immediately.
17.8 Compare Match Output Unit
The Compare Output mode (COM1x1:0) bits have two functions. The waveform generator uses the COM1x1:0 bits
for defining the Output Compare (OC1x) state at the next Compare Match. Secondly the COM1x1:0 bits control the
OC1x pin output source. Figure 17-5 shows a simplified schematic of the logic affected by the COM1x1:0 bit setting.
The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port
Control Registers (DDR and PORT) that are affected by the COM1x1:0 bits are shown. When referring to the OC1x
state, the reference is for the internal OC1x Register, not the OC1x pin. If a System Reset occur, the OC1x Register
is reset to “0”.
Figure 17-5. Compare Match Output Unit, Schematic
PORT
DDR
D Q
D Q
OCnx
OCnx Pin
D Q Waveform
Generator
COMnx1
COMnx0
0
1
DATABUS
FOCnx
clkI/OATmega8A [DATASHEET] 84
8159E–AVR–02/2013
The general I/O port function is overridden by the Output Compare (OC1x) from the waveform generator if either of
the COM1x1:0 bits are set. However, the OC1x pin direction (input or output) is still controlled by the Data Direction
Register (DDR) for the port pin. The Data Direction Register bit for the OC1x pin (DDR_OC1x) must be set as output
before the OC1x value is visible on the pin. The port override function is generally independent of the
Waveform Generation mode, but there are some exceptions. Refer to Table 17-2, Table 17-3 and Table 17-4 for
details.
The design of the Output Compare Pin logic allows initialization of the OC1x state before the output is enabled.
Note that some COM1x1:0 bit settings are reserved for certain modes of operation. See “Register Description” on
page 92.
The COM1x1:0 bits have no effect on the Input Capture unit.
17.8.1 Compare Output Mode and Waveform Generation
The waveform generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes. For all modes, setting
the COM1x1:0 = 0 tells the waveform generator that no action on the OC1x Register is to be performed on the
next Compare Match. For compare output actions in the non-PWM modes refer to Table 17-2 on page 93. For fast
PWM mode refer to Table 17-3 on page 93, and for phase correct and phase and frequency correct PWM refer to
Table 17-4 on page 93.
A change of the COM1x1:0 bits state will have effect at the first Compare Match after the bits are written. For nonPWM
modes, the action can be forced to have immediate effect by using the FOC1x strobe bits.
17.9 Modes of Operation
The mode of operation (i.e., the behavior of the Timer/Counter and the Output Compare pins) is defined by the
combination of the Waveform Generation mode (WGM13:0) and Compare Output mode (COM1x1:0) bits. The
Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do.
The COM1x1:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted
PWM). For non-PWM modes the COM1x1:0 bits control whether the output should be set, cleared or toggle at a
Compare Match. See “Compare Match Output Unit” on page 83.
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 91.
17.9.1 Normal Mode
The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting direction is always
up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum
16-bit value (MAX = 0xFFFF) and then restarts from the BOTTOM (0x0000). In normal operation the Timer/Counter
Overflow Flag (TOV1) will be set in the same timer clock cycle as the TCNT1 becomes zero. The TOV1 Flag in
this case behaves like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow
interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by software. There are no
special cases to consider in the Normal mode, a new counter value can be written anytime.
The Input Capture unit is easy to use in Normal mode. However, observe that the maximum interval between the
external events must not exceed the resolution of the counter. If the interval between events are too long, the timer
overflow interrupt or the prescaler must be used to extend the resolution for the capture unit.
The Output Compare units can be used to generate interrupts at some given time. Using the Output Compare to
generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time.
17.9.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register are used to manipulate
the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT1) matches
either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 = 12). The OCR1A or ICR1 define the top value for theATmega8A [DATASHEET] 85
8159E–AVR–02/2013
counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also
simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 17-6. The counter value (TCNT1) increases until a Compare
Match occurs with either OCR1A or ICR1, and then counter (TCNT1) is cleared.
Figure 17-6. CTC Mode, Timing Diagram
An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or
ICF1 Flag according to the register used to define the TOP value. If the interrupt is enabled, the interrupt handler
routine can be used for updating the TOP value. However, changing the TOP to a value close to BOTTOM when
the counter is running with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR1A or ICR1 is lower than the current value of
TCNT1, the counter will miss the Compare Match. The counter will then have to count to its maximum value
(0xFFFF) and wrap around starting at 0x0000 before the Compare Match can occur. In many cases this feature is
not desirable. An alternative will then be to use the fast PWM mode using OCR1A for defining TOP (WGM13:0 =
15) since the OCR1A then will be double buffered.
For generating a waveform output in CTC mode, the OC1A output can be set to toggle its logical level on each
Compare Match by setting the Compare Output mode bits to toggle mode (COM1A1:0 = 1). The OC1A value will
not be visible on the port pin unless the data direction for the pin is set to output (DDR_OC1A = 1). The waveform
generated will have a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). The waveform
frequency is defined by the following equation:
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that the counter counts
from MAX to 0x0000.
17.9.3 Fast PWM Mode
The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5, 6, 7, 14, or 15) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM options by its single-slope operation.
The counter counts from BOTTOM to TOP then restarts from BOTTOM. In non-inverting Compare Output mode,
the Output Compare (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x, and set at BOTTOM.
In inverting Compare Output mode output is set on Compare Match and cleared at BOTTOM. Due to the singleslope
operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct and
phase and frequency correct PWM modes that use dual-slope operation. This high frequency makes the fast PWM
TCNTn
OCnA
(Toggle)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4
(COMnA1:0 = 1)
f
OCnA
f
clk_I/O
2 N 1 + OCRnA = --------------------------------------------------ATmega8A [DATASHEET] 86
8159E–AVR–02/2013
mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), hence reduces total system cost.
The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or OCR1A. The minimum
resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum resolution is 16-bit (ICR1 or
OCR1A set to MAX). The PWM resolution in bits can be calculated by using the following equation:
In fast PWM mode the counter is incremented until the counter value matches either one of the fixed values
0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 = 14), or the value in OCR1A
(WGM13:0 = 15). The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
PWM mode is shown in Figure 17-7. The figure shows fast PWM mode when OCR1A or ICR1 is used to define
TOP. The TCNT1 value is in the timing diagram shown as a histogram for illustrating the single-slope operation.
The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1
slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a
Compare Match occurs.
Figure 17-7. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. In addition the OCF1A or
ICF1 Flag is set at the same timer clock cycle as TOV1 is set when either OCR1A or ICR1 is used for defining the
TOP value. If one of the interrupts are enabled, the interrupt handler routine can be used for updating the TOP and
compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of
all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a Compare Match will
never occur between the TCNT1 and the OCR1x. Note that when using fixed TOP values the unused bits are
masked to zero when any of the OCR1x Registers are written.
The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP value. The ICR1
Register is not double buffered. This means that if ICR1 is changed to a low value when the counter is running with
none or a low prescaler value, there is a risk that the new ICR1 value written is lower than the current value of
TCNT1. The result will then be that the counter will miss the Compare Match at the TOP value. The counter will
then have to count to the MAX value (0xFFFF) and wrap around starting at 0x0000 before the Compare Match can
occur. The OCR1A Register, however, is double buffered. This feature allows the OCR1A I/O location to be written
anytime. When the OCR1A I/O location is written the value written will be put into the OCR1A Buffer Register. The
OCR1A Compare Register will then be updated with the value in the Buffer Register at the next timer clock cycle
RFPWM
log TOP + 1
log 2 = -----------------------------------
TCNTn
OCRnx / TOP Update
and TOVn Interrupt Flag
Set and OCnA Interrupt
Flag Set or ICFn
Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4 5 6 7 8
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)ATmega8A [DATASHEET] 87
8159E–AVR–02/2013
the TCNT1 matches TOP. The update is done at the same timer clock cycle as the TCNT1 is cleared and the
TOV1 Flag is set.
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A
Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively
changed (by changing the TOP value), using the OCR1A as TOP is clearly a better choice due to its double buffer
feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting the
COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the
COM1x1:0 to 3. See Table 17-3 on page 93. The actual OC1x value will only be visible on the port pin if the data
direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing)
the OC1x Register at the Compare Match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register
at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM waveform output in
the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output will be a narrow spike for each
TOP+1 timer clock cycle. Setting the OCR1x equal to TOP will result in a constant high or low output (depending
on the polarity of the output set by the COM1x1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC1A to toggle
its logical level on each Compare Match (COM1A1:0 = 1). This applies only if OCR1A is used to define the TOP
value (WGM13:0 = 15). The waveform generated will have a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A
is set to zero (0x0000). This feature is similar to the OC1A toggle in CTC mode, except the double buffer feature of
the Output Compare unit is enabled in the fast PWM mode.
17.9.4 Phase Correct PWM Mode
The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1, 2, 3, 10, or 11) provides a
high resolution phase correct PWM waveform generation option. The phase correct PWM mode is, like the phase
and frequency correct PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM
(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the Output
Compare (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x while upcounting, and set on the
Compare Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope
operation has lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode can be fixed to 8-, 9-, or 10-bit, or defined by either ICR1 or
OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum resolution is
16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated by using the following equation:
In phase correct PWM mode the counter is incremented until the counter value matches either one of the fixed values
0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1 (WGM13:0 = 10), or the value in
OCR1A (WGM13:0 = 11). The counter has then reached the TOP and changes the count direction. The TCNT1
value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown
on Figure 17-8. The figure shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The
TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent
f
OCnxPWM
f
clk_I/O
N 1 + TOP = -----------------------------------
RPCPWM
log TOP + 1
log 2 = -----------------------------------ATmega8A [DATASHEET] 88
8159E–AVR–02/2013
compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a Compare Match
occurs.
Figure 17-8. Phase Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When either OCR1A or
ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set accordingly at the same timer clock cycle as
the OCR1x Registers are updated with the double buffer value (at TOP). The Interrupt Flags can be used to generate
an interrupt each time the counter reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of
all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a Compare Match will
never occur between the TCNT1 and the OCR1x. Note that when using fixed TOP values, the unused bits are
masked to zero when any of the OCR1x Registers are written. As the third period shown in Figure 17-8 illustrates,
changing the TOP actively while the Timer/Counter is running in the Phase Correct mode can result in an unsymmetrical
output. The reason for this can be found in the time of update of the OCR1x Register. Since the OCR1x
update occurs at TOP, the PWM period starts and ends at TOP. This implies that the length of the falling slope is
determined by the previous TOP value, while the length of the rising slope is determined by the new TOP value.
When these two values differ the two slopes of the period will differ in length. The difference in length gives the
unsymmetrical result on the output.
It is recommended to use the Phase and Frequency Correct mode instead of the Phase Correct mode when
changing the TOP value while the Timer/Counter is running. When using a static TOP value there are practically no
differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins. Setting
the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting
the COM1x1:0 to 3. See Table 17-4 on page 93. The actual OC1x value will only be visible on the port pin if the
data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing)
the OC1x Register at the Compare Match between OCR1x and TCNT1 when the counter increments, and
clearing (or setting) the OC1x Register at Compare Match between OCR1x and TCNT1 when the counter decrements.
The PWM frequency for the output when using phase correct PWM can be calculated by the following
equation:
OCRnx / TOP Update and
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TOVn Interrupt Flag Set
(Interrupt on Bottom)
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
f
OCnxPCPWM
f
clk_I/O
2 N TOP = ----------------------------ATmega8A [DATASHEET] 89
8159E–AVR–02/2013
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represent special cases when generating a PWM waveform output in
the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set
equal to TOP the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will
have the opposite logic values.
If OCR1A is used to define the TOP value (WMG13:0 = 11) and COM1A1:0 = 1, the OC1A output will toggle with a
50% duty cycle.
17.9.5 Phase and Frequency Correct PWM Mode
The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM mode (WGM13:0
= 8 or 9) provides a high resolution phase and frequency correct PWM waveform generation option. The phase
and frequency correct PWM mode is, like the phase correct PWM mode, based on a dual-slope operation. The
counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare
Output mode, the Output Compare (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x
while upcounting, and set on the Compare Match while downcounting. In inverting Compare Output mode, the
operation is inverted. The dual-slope operation gives a lower maximum operation frequency compared to the single-slope
operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are
preferred for motor control applications.
The main difference between the phase correct, and the phase and frequency correct PWM mode is the time the
OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 17-8 and Figure 17-9).
The PWM resolution for the phase and frequency correct PWM mode can be defined by either ICR1 or OCR1A.
The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximum resolution is 16-bit
(ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calculated using the following equation:
In phase and frequency correct PWM mode the counter is incremented until the counter value matches either the
value in ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The counter has then reached the TOP and
changes the count direction. The TCNT1 value will be equal to TOP for one timer clock cycle. The timing diagram
for the phase correct and frequency correct PWM mode is shown on Figure 17-9. The figure shows phase and
frequency correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing
diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes represent compare matches between
OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a Compare Match occurs.
RPFCPWM
log TOP + 1
log 2 = -----------------------------------ATmega8A [DATASHEET] 90
8159E–AVR–02/2013
Figure 17-9. Phase and Frequency Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x Registers are updated
with the double buffer value (at BOTTOM). When either OCR1A or ICR1 is used for defining the TOP value, the
OC1A or ICF1 Flag set when TCNT1 has reached TOP. The Interrupt Flags can then be used to generate an interrupt
each time the counter reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or equal to the value of
all of the Compare Registers. If the TOP value is lower than any of the Compare Registers, a Compare Match will
never occur between the TCNT1 and the OCR1x.
As Figure 17-9 shows the output generated is, in contrast to the Phase Correct mode, symmetrical in all periods.
Since the OCR1x Registers are updated at BOTTOM, the length of the rising and the falling slopes will always be
equal. This gives symmetrical output pulses and is therefore frequency correct.
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using ICR1, the OCR1A
Register is free to be used for generating a PWM output on OC1A. However, if the base PWM frequency is actively
changed by changing the TOP value, using the OCR1A as TOP is clearly a better choice due to its double buffer
feature.
In phase and frequency correct PWM mode, the compare units allow generation of PWM waveforms on the OC1x
pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated
by setting the COM1x1:0 to 3. See Table 17-4 on page 93. The actual OC1x value will only be visible on the
port pin if the data direction for the port pin is set as output (DDR_OC1x). The PWM waveform is generated by setting
(or clearing) the OC1x Register at the Compare Match between OCR1x and TCNT1 when the counter
increments, and clearing (or setting) the OC1x Register at Compare Match between OCR1x and TCNT1 when the
counter decrements. The PWM frequency for the output when using phase and frequency correct PWM can be calculated
by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM waveform output in
the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the output will be continuously low and if set
equal to TOP the output will be set to high for non-inverted PWM mode. For inverted PWM the output will have the
opposite logic values.
OCRnx / TOP Update and
TOVn Interrupt Flag Set
(Interrupt on Bottom)
OCnA Interrupt Flag Set or
ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
f
OCnxPFCPWM
f
clk_I/O
2 N TOP = ----------------------------ATmega8A [DATASHEET] 91
8159E–AVR–02/2013
If OCR1A is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output will toggle with a
50% duty cycle.
17.10 Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT1) is therefore shown as a clock enable signal
in the following figures. The figures include information on when Interrupt Flags are set, and when the OCR1x Register
is updated with the OCR1x buffer value (only for modes utilizing double buffering). Figure 17-10 shows a
timing diagram for the setting of OCF1x.
Figure 17-10. Timer/Counter Timing Diagram, Setting of OCF1x, no Prescaling
Figure 17-11 shows the same timing data, but with the prescaler enabled.
Figure 17-11. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)
Figure 17-12 shows the count sequence close to TOP in various modes. When using phase and frequency correct
PWM mode the OCR1x Register is updated at BOTTOM. The timing diagrams will be the same, but TOP should
be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on. The same renaming applies for modes that set the
TOV1 Flag at BOTTOM.
clkTn
(clkI/O/1)
OCFnx
clkI/O
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)ATmega8A [DATASHEET] 92
8159E–AVR–02/2013
Figure 17-12. Timer/Counter Timing Diagram, no Prescaling
Figure 17-13 shows the same timing data, but with the prescaler enabled.
Figure 17-13. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
17.11 Register Description
17.11.1 TCCR1A – Timer/Counter 1 Control Register A
• Bit 7:6 – COM1A1:0: Compare Output Mode for channel A
• Bit 5:4 – COM1B1:0: Compare Output Mode for channel B
The COM1A1:0 and COM1B1:0 control the Output Compare Pins (OC1A and OC1B respectively) behavior. If one
or both of the COM1A1:0 bits are written to one, the OC1A output overrides the normal port functionality of the I/O
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkTn
(clkI/O/1)
clkI/O
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
Bit 7 6 5 4 3 2 1 0
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 TCCR1A
Read/Write R/W R/W R/W R/W W W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 93
8159E–AVR–02/2013
pin it is connected to. If one or both of the COM1B1:0 bit are written to one, the OC1B output overrides the normal
port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding
to the OC1A or OC1B pin must be set in order to enable the output driver.
When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is dependent of the WGM13:0
bits setting. Table 17-2 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to a normal or a CTC
mode (non-PWM).
Table 17-3 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast PWM mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. In this case the Compare
Match is ignored, but the set or clear is done at BOTTOM. See “Fast PWM Mode” on page 85. for more details.
Table 17-4 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct or the phase
and frequency correct, PWM mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. See “Phase Correct PWM
Mode” on page 87. for more details.
Table 17-2. Compare Output Mode, Non-PWM
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 Toggle OC1A/OC1B on Compare Match
1 0 Clear OC1A/OC1B on Compare Match (Set output to low level)
1 1 Set OC1A/OC1B on Compare Match (Set output to high level)
Table 17-3. Compare Output Mode, Fast PWM(1)
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 WGM13:0 = 15: Toggle OC1A on Compare Match, OC1B disconnected
(normal port operation). For all other WGM1 settings, normal port
operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM,
(non-inverting mode)
1 1 Set OC1A/OC1B on Compare Match, clear OC1A/OC1B at BOTTOM,
(inverting mode)
Table 17-4. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM(1)
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 WGM13:0 = 9 or 14: Toggle OC1A on Compare Match, OC1B
disconnected (normal port operation). For all other WGM1 settings,
normal port operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match when up-counting. Set
OC1A/OC1B on Compare Match when downcounting.
1 1 Set OC1A/OC1B on Compare Match when up-counting. Clear
OC1A/OC1B on Compare Match when downcounting.ATmega8A [DATASHEET] 94
8159E–AVR–02/2013
• Bit 3 – FOC1A: Force Output Compare for channel A
• Bit 2 – FOC1B: Force Output Compare for channel B
The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM mode. However, for ensuring
compatibility with future devices, these bits must be set to zero when TCCR1A is written when operating in a
PWM mode. When writing a logical one to the FOC1A/FOC1B bit, an immediate Compare Match is forced on the
waveform generation unit. The OC1A/OC1B output is changed according to its COM1x1:0 bits setting. Note that
the FOC1A/FOC1B bits are implemented as strobes. Therefore it is the value present in the COM1x1:0 bits that
determine the effect of the forced compare.
A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer on Compare Match
(CTC) mode using OCR1A as TOP.
The FOC1A/FOC1B bits are always read as zero.
• Bit 1:0 – WGM11:0: Waveform Generation Mode
Combined with the WGM13:2 bits found in the TCCR1B Register, these bits control the counting sequence of the
counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see
Table 17-5. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on
Compare Match (CTC) mode, and three types of Pulse Width Modulation (PWM) modes. (See “Modes of Operation”
on page 84.)
Note: 1. The CTC1 and PWM11:0 bit definition names are obsolete. Use the WGM12:0 definitions. However, the functionality and
location of these bits are compatible with previous versions of the timer.
Table 17-5. Waveform Generation Mode Bit Description
Mode WGM13
WGM12
(CTC1)
WGM11
(PWM11)
WGM10
(PWM10)
Timer/Counter Mode of
Operation(1) TOP
Update of
OCR1x
TOV1 Flag
Set on
0 0 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM
3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCR1A Immediate MAX
5 0 1 0 1 Fast PWM, 8-bit 0x00FF BOTTOM TOP
6 0 1 1 0 Fast PWM, 9-bit 0x01FF BOTTOM TOP
7 0 1 1 1 Fast PWM, 10-bit 0x03FF BOTTOM TOP
8 1 0 0 0 PWM, Phase and Frequency Correct ICR1 BOTTOM BOTTOM
9 1 0 0 1 PWM, Phase and Frequency Correct OCR1A BOTTOM BOTTOM
10 1 0 1 0 PWM, Phase Correct ICR1 TOP BOTTOM
11 1 0 1 1 PWM, Phase Correct OCR1A TOP BOTTOM
12 1 1 0 0 CTC ICR1 Immediate MAX
13 1 1 0 1 (Reserved) – – –
14 1 1 1 0 Fast PWM ICR1 BOTTOM TOP
15 1 1 1 1 Fast PWM OCR1A BOTTOM TOPATmega8A [DATASHEET] 95
8159E–AVR–02/2013
17.11.2 TCCR1B – Timer/Counter 1 Control Register B
• Bit 7 – ICNC1: Input Capture Noise Canceler
Setting this bit (to one) activates the Input Capture Noise Canceler. When the noise canceler is activated, the input
from the Input Capture Pin (ICP1) is filtered. The filter function requires four successive equal valued samples of
the ICP1 pin for changing its output. The Input Capture is therefore delayed by four Oscillator cycles when the
noise canceler is enabled.
• Bit 6 – ICES1: Input Capture Edge Select
This bit selects which edge on the Input Capture Pin (ICP1) that is used to trigger a capture event. When the
ICES1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ICES1 bit is written to one, a
rising (positive) edge will trigger the capture.
When a capture is triggered according to the ICES1 setting, the counter value is copied into the Input Capture Register
(ICR1). The event will also set the Input Capture Flag (ICF1), and this can be used to cause an Input Capture
Interrupt, if this interrupt is enabled.
When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the TCCR1A and the
TCCR1B Register), the ICP1 is disconnected and consequently the Input Capture function is disabled.
• Bit 5 – Reserved Bit
This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be written to zero
when TCCR1B is written.
• Bit 4:3 – WGM13:2: Waveform Generation Mode
See TCCR1A Register description.
• Bit 2:0 – CS12:0: Clock Select
The three clock select bits select the clock source to be used by the Timer/Counter, see Figure 17-10 and Figure
17-11.
If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the counter even if the
pin is configured as an output. This feature allows software control of the counting.
Bit 7 6 5 4 3 2 1 0
ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 TCCR1B
Read/Write R/W R/W R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 17-6. Clock Select Bit Description
CS12 CS11 CS10 Description
0 0 0 No clock source. (Timer/Counter stopped)
0 0 1 clkI/O/1 (No prescaling)
0 1 0 clkI/O/8 (From prescaler)
0 1 1 clkI/O/64 (From prescaler)
1 0 0 clkI/O/256 (From prescaler)
1 0 1 clkI/O/1024 (From prescaler)
1 1 0 External clock source on T1 pin. Clock on falling edge.
1 1 1 External clock source on T1 pin. Clock on rising edge.ATmega8A [DATASHEET] 96
8159E–AVR–02/2013
17.11.3 TCNT1H and TCNT1L – Timer/Counter 1
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read
and for write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and Low bytes are
read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit
temporary High byte Register (TEMP). This temporary register is shared by all the other 16-bit registers. See
“Accessing 16-bit Registers” on page 75.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a Compare Match between
TCNT1 and one of the OCR1x Registers.
Writing to the TCNT1 Register blocks (removes) the Compare Match on the following timer clock for all compare
units.
17.11.4 OCR1AH and OCR1AL– Output Compare Register 1 A
17.11.5 OCR1BH and OCR1BL – Output Compare Register 1 B
The Output Compare Registers contain a 16-bit value that is continuously compared with the counter value
(TCNT1). A match can be used to generate an Output Compare Interrupt, or to generate a waveform output on the
OC1x pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and Low bytes are written simultaneously
when the CPU writes to these registers, the access is performed using an 8-bit temporary High byte
Register (TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers”
on page 75.
17.11.6 ICR1H and ICR1L – Input Capture Register 1
The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the ICP1 pin (or
optionally on the Analog Comparator Output for Timer/Counter1). The Input Capture can be used for defining the
counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and Low bytes are read simultaneously
when the CPU accesses these registers, the access is performed using an 8-bit temporary High byte Register
Bit 7 6 5 4 3 2 1 0
TCNT1[15:8] TCNT1H
TCNT1[7:0] TCNT1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1A[15:8] OCR1AH
OCR1A[7:0] OCR1AL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1B[15:8] OCR1BH
OCR1B[7:0] OCR1BL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
ICR1[15:8] ICR1H
ICR1[7:0] ICR1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 97
8159E–AVR–02/2013
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit Registers” on
page 75.
17.11.7 TIMSK(1) – Timer/Counter Interrupt Mask Register
Note: 1. This register contains interrupt control bits for several Timer/Counters, but only Timer1 bits are described in this
section. The remaining bits are described in their respective timer sections.
• Bit 5 – TICIE1: Timer/Counter1, Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the
Timer/Counter1 Input Capture Interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page
44) is executed when the ICF1 Flag, located in TIFR, is set.
• Bit 4 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the
Timer/Counter1 Output Compare A match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts”
on page 44) is executed when the OCF1A Flag, located in TIFR, is set.
• Bit 3 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the
Timer/Counter1 Output Compare B match interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts”
on page 44) is executed when the OCF1B Flag, located in TIFR, is set.
• Bit 2 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the
Timer/Counter1 Overflow Interrupt is enabled. The corresponding Interrupt Vector (see “Interrupts” on page 44) is
executed when the TOV1 Flag, located in TIFR, is set.
17.11.8 TIFR(1) – Timer/Counter Interrupt Flag Register
Note: 1. This register contains flag bits for several Timer/Counters, but only Timer1 bits are described in this section. The
remaining bits are described in their respective timer sections.
• Bit 5 – ICF1: Timer/Counter1, Input Capture Flag
This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set by the
WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the counter reaches the TOP value.
ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be
cleared by writing a logic one to its bit location.
• Bit 4 – OCF1A: Timer/Counter1, Output Compare A Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register A
(OCR1A).
Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag.
Bit 7 6 5 4 3 2 1 0
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 98
8159E–AVR–02/2013
OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector is executed. Alternatively,
OCF1A can be cleared by writing a logic one to its bit location.
• Bit 3 – OCF1B: Timer/Counter1, Output Compare B Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Register B
(OCR1B).
Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag.
OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed. Alternatively,
OCF1B can be cleared by writing a logic one to its bit location.
• Bit 2 – TOV1: Timer/Counter1, Overflow Flag
The setting of this flag is dependent of the WGM13:0 bits setting. In normal and CTC modes, the TOV1 Flag is set
when the timer overflows. Refer to Table 17-5 on page 94 for the TOV1 Flag behavior when using another
WGM13:0 bit setting.
TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed. Alternatively, TOV1
can be cleared by writing a logic one to its bit location.ATmega8A [DATASHEET] 99
8159E–AVR–02/2013
18. 8-bit Timer/Counter2 with PWM and Asynchronous Operation
18.1 Features • Single Channel Counter
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, phase Correct Pulse Width Modulator (PWM)
• Frequency Generator
• 10-bit Clock Prescaler
• Overflow and Compare Match Interrupt Sources (TOV2 and OCF2)
• Allows Clocking from External 32kHz Watch Crystal Independent of the I/O Clock
18.2 Overview
Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. A simplified block diagram of
the 8-bit Timer/Counter is shown in Figure 18-1. For the actual placement of I/O pins, refer to “Pin Configurations”
on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O
Register and bit locations are listed in the “Register Description” on page 112.
Figure 18-1. 8-bit Timer/Counter Block Diagram
Timer/Counter
DATA BUS
=
TCNTn
Waveform
Generation OCn
= 0
Control Logic
= 0xFF
BOTTOM TOP
count
clear
direction
TOVn
(Int. Req.)
OCn
(Int. Req.)
Synchronization Unit
OCRn
TCCRn
ASSRn
Status Flags
clkI/O
clkASY
Synchronized Status Flags
asynchronous Mode
Select (ASn)
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkTn
clkI/OATmega8A [DATASHEET] 100
8159E–AVR–02/2013
18.2.1 Registers
The Timer/Counter (TCNT2) and Output Compare Register (OCR2) are 8-bit registers. Interrupt request (shorten
as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked
with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these registers
are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from the TOSC1/2 pins,
as detailed later in this section. The asynchronous operation is controlled by the Asynchronous Status Register
(ASSR). The Clock Select logic block controls which clock source the Timer/Counter uses to increment (or decrement)
its value. The Timer/Counter is inactive when no clock source is selected. The output from the clock select
logic is referred to as the timer clock (clkT2).
The double buffered Output Compare Register (OCR2) is compared with the Timer/Counter value at all times. The
result of the compare can be used by the waveform generator to generate a PWM or variable frequency output on
the Output Compare Pin (OC2). For details, see “Output Compare Unit” on page 101. The Compare Match event
will also set the Compare Flag (OCF2) which can be used to generate an Output Compare interrupt request.
18.2.2 Definitions
Many register and bit references in this document are written in general form. A lower case “n” replaces the
Timer/Counter number, in this case 2. However, when using the register or bit defines in a program, the precise
form must be used (i.e., TCNT2 for accessing Timer/Counter2 counter value and so on).
The definitions in Table 18-1 are also used extensively throughout the document.
18.3 Timer/Counter Clock Sources
The Timer/Counter can be clocked by an internal synchronous or an external asynchronous clock source. The
clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2 bit in the ASSR Register is written to
logic one, the clock source is taken from the Timer/Counter Oscillator connected to TOSC1 and TOSC2. For
details on asynchronous operation, see “Asynchronous Operation of the Timer/Counter” on page 109. For details
on clock sources and prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 71.
18.4 Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 18-2 shows a
block diagram of the counter and its surrounding environment.
Table 18-1. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00).
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR2 Register. The assignment is dependent
on the mode of operation.ATmega8A [DATASHEET] 101
8159E–AVR–02/2013
Figure 18-2. Counter Unit Block Diagram
Signal description (internal signals):
count Increment or decrement TCNT2 by 1.
direction Selects between increment and decrement.
clear Clear TCNT2 (set all bits to zero).
clkT2 Timer/Counter clock.
TOP Signalizes that TCNT2 has reached maximum value.
BOTTOM Signalizes that TCNT2 has reached minimum value (zero).
Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer
clock (clkT2). clkT2 can be generated from an external or internal clock source, selected by the clock select bits
(CS22:0). When no clock source is selected (CS22:0 = 0) the timer is stopped. However, the TCNT2 value can be
accessed by the CPU, regardless of whether clkT2 is present or not. A CPU write overrides (has priority over) all
counter clear or count operations.
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in the Timer/Counter
Control Register (TCCR2). There are close connections between how the counter behaves (counts) and how
waveforms are generated on the Output Compare Output OC2. For more details about advanced counting
sequences and waveform generation, see “Modes of Operation” on page 104.
The Timer/Counter Overflow (TOV2) Flag is set according to the mode of operation selected by the WGM21:0 bits.
TOV2 can be used for generating a CPU interrupt.
18.5 Output Compare Unit
The 8-bit comparator continuously compares TCNT2 with the Output Compare Register (OCR2). Whenever
TCNT2 equals OCR2, the comparator signals a match. A match will set the Output Compare Flag (OCF2) at the
next timer clock cycle. If enabled (OCIE2 = 1), the Output Compare Flag generates an Output Compare interrupt.
The OCF2 Flag is automatically cleared when the interrupt is executed. Alternatively, the OCF2 Flag can be
cleared by software by writing a logical one to its I/O bit location. The waveform generator uses the match signal to
generate an output according to operating mode set by the WGM21:0 bits and Compare Output mode (COM21:0)
bits. The max and bottom signals are used by the waveform generator for handling the special cases of the
extreme values in some modes of operation (see “Modes of Operation” on page 104).
Figure 18-3 shows a block diagram of the Output Compare unit.
DATA BUS
TCNTn Control Logic
count
TOVn
(Int. Req.)
BOTTOM TOP
direction
clear
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkI/O
clk TnATmega8A [DATASHEET] 102
8159E–AVR–02/2013
Figure 18-3. Output Compare Unit, Block Diagram
The OCR2 Register is double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal
and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering
synchronizes the update of the OCR2 Compare Register to either top or bottom of the counting sequence. The
synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output
glitch-free.
The OCR2 Register access may seem complex, but this is not case. When the double buffering is enabled, the
CPU has access to the OCR2 Buffer Register, and if double buffering is disabled the CPU will access the OCR2
directly.
18.5.1 Force Output Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by writing a one to
the Force Output Compare (FOC2) bit. Forcing Compare Match will not set the OCF2 Flag or reload/clear the
timer, but the OC2 pin will be updated as if a real Compare Match had occurred (the COM21:0 bits settings define
whether the OC2 pin is set, cleared or toggled).
18.5.2 Compare Match Blocking by TCNT2 Write
All CPU write operations to the TCNT2 Register will block any Compare Match that occurs in the next timer clock
cycle, even when the timer is stopped. This feature allows OCR2 to be initialized to the same value as TCNT2 without
triggering an interrupt when the Timer/Counter clock is enabled.
18.5.3 Using the Output Compare Unit
Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock cycle, there are
risks involved when changing TCNT2 when using the Output Compare channel, independently of whether the
Timer/Counter is running or not. If the value written to TCNT2 equals the OCR2 value, the Compare Match will be
OCFn (Int. Req.)
= (8-bit Comparator )
OCRn
OCxy
DATA BUS
TCNTn
WGMn1:0
Waveform Generator
TOP
FOCn
COMn1:0
BOTTOMATmega8A [DATASHEET] 103
8159E–AVR–02/2013
missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT2 value equal to BOTTOM
when the counter is downcounting.
The setup of the OC2 should be performed before setting the Data Direction Register for the port pin to output. The
easiest way of setting the OC2 value is to use the Force Output Compare (FOC2) strobe bit in Normal mode. The
OC2 Register keeps its value even when changing between waveform generation modes.
Be aware that the COM21:0 bits are not double buffered together with the compare value. Changing the COM21:0
bits will take effect immediately.
18.6 Compare Match Output Unit
The Compare Output mode (COM21:0) bits have two functions. The waveform generator uses the COM21:0 bits
for defining the Output Compare (OC2) state at the next Compare Match. Also, the COM21:0 bits control the OC2
pin output source. Figure 18-4 shows a simplified schematic of the logic affected by the COM21:0 bit setting. The
I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control
Registers (DDR and PORT) that are affected by the COM21:0 bits are shown. When referring to the OC2 state, the
reference is for the internal OC2 Register, not the OC2 pin.
Figure 18-4. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC2) from the waveform generator if either of
the COM21:0 bits are set. However, the OC2 pin direction (input or output) is still controlled by the Data Direction
Register (DDR) for the port pin. The Data Direction Register bit for the OC2 pin (DDR_OC2) must be set as output
before the OC2 value is visible on the pin. The port override function is independent of the Waveform Generation
mode.
PORT
DDR
D Q
D Q
OCn
OCn Pin
D Q Waveform
Generator
COMn1
COMn0
0
1
DATABUS
FOCn
clkI/OATmega8A [DATASHEET] 104
8159E–AVR–02/2013
The design of the Output Compare Pin logic allows initialization of the OC2 state before the output is enabled. Note
that some COM21:0 bit settings are reserved for certain modes of operation. See “Register Description” on page
112.
18.6.1 Compare Output Mode and Waveform Generation
The Waveform Generator uses the COM21:0 bits differently in normal, CTC, and PWM modes. For all modes, setting
the COM21:0 = 0 tells the waveform generator that no action on the OC2 Register is to be performed on the
next Compare Match. For compare output actions in the non-PWM modes refer to Table 18-3 on page 112. For
fast PWM mode, refer to Table 18-4 on page 113, and for phase correct PWM refer to Table 18-5 on page 113.
A change of the COM21:0 bits state will have effect at the first Compare Match after the bits are written. For nonPWM
modes, the action can be forced to have immediate effect by using the FOC2 strobe bits.
18.7 Modes of Operation
The mode of operation (i.e., the behavior of the Timer/Counter and the Output Compare pins) is defined by the
combination of the Waveform Generation mode (WGM21:0) and Compare Output mode (COM21:0) bits. The
Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do.
The COM21:0 bits control whether the PWM output generated should be inverted or not (inverted or non-inverted
PWM). For non-PWM modes the COM21:0 bits control whether the output should be set, cleared, or toggled at a
Compare Match (see “Compare Match Output Unit” on page 103).
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 108.
18.7.1 Normal Mode
The simplest mode of operation is the Normal mode (WGM21:0 = 0). In this mode the counting direction is always
up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-
bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow
Flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case
behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV2 Flag, the timer resolution can be increased by software. There are no special
cases to consider in the Normal mode, a new counter value can be written anytime.
The Output Compare unit can be used to generate interrupts at some given time. Using the Output Compare to
generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time.
18.7.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare or CTC mode (WGM21:0 = 2), the OCR2 Register is used to manipulate the counter
resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2. The
OCR2 defines the top value for the counter, hence also its resolution. This mode allows greater control of the Compare
Match output frequency. It also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 18-5. The counter value (TCNT2) increases until a Compare
Match occurs between TCNT2 and OCR2, and then counter (TCNT2) is cleared.ATmega8A [DATASHEET] 105
8159E–AVR–02/2013
Figure 18-5. CTC Mode, Timing Diagram
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF2 Flag. If the
interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing the
TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done
with care since the CTC mode does not have the double buffering feature. If the new value written to OCR2 is
lower than the current value of TCNT2, the counter will miss the Compare Match. The counter will then have to
count to its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur.
For generating a waveform output in CTC mode, the OC2 output can be set to toggle its logical level on each Compare
Match by setting the Compare Output mode bits to toggle mode (COM21:0 = 1). The OC2 value will not be
visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a
maximum frequency of fOC2 = fclk_I/O/2 when OCR2 is set to zero (0x00). The waveform frequency is defined by the
following equation:
The N variable represents the prescaler factor (1, 8, 32, 64, 128, 256, or 1024).
As for the Normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the counter counts
from MAX to 0x00.
18.7.3 Fast PWM Mode
The fast Pulse Width Modulation or fast PWM mode (WGM21:0 = 3) provides a high frequency PWM waveform
generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter
counts from BOTTOM to MAX then restarts from BOTTOM. In non-inverting Compare Output mode, the Output
Compare (OC2) is cleared on the Compare Match between TCNT2 and OCR2, and set at BOTTOM. In inverting
Compare Output mode, the output is set on Compare Match and cleared at BOTTOM. Due to the single-slope
operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode
that uses dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation,
rectification, and DAC applications. High frequency allows physically small sized external components (coils,
capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the MAX value. The counter is then
cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 18-6. The
TCNT2 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent
compare matches between OCR2 and TCNT2.
TCNTn
OCn
(Toggle)
OCn Interrupt Flag Set
Period 1 2 3 4
(COMn1:0 = 1)
f
OCn
f
clk_I/O
2 N 1 + OCRn = ----------------------------------------------ATmega8A [DATASHEET] 106
8159E–AVR–02/2013
Figure 18-6. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches MAX. If the interrupt is enabled, the
interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2 pin. Setting the COM21:0
bits to 2 will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM21:0
to 3 (see Table 18-4 on page 113). The actual OC2 value will only be visible on the port pin if the data direction for
the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC2 Register at the
Compare Match between OCR2 and TCNT2, and clearing (or setting) the OC2 Register at the timer clock cycle the
counter is cleared (changes from MAX to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescaler factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2 Register represent special cases when generating a PWM waveform output in
the fast PWM mode. If the OCR2 is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer
clock cycle. Setting the OCR2 equal to MAX will result in a constantly high or low output (depending on the polarity
of the output set by the COM21:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC2 to toggle
its logical level on each Compare Match (COM21:0 = 1). The waveform generated will have a maximum frequency
of foc2 = fclk_I/O/2 when OCR2 is set to zero. This feature is similar to the OC2 toggle in CTC mode, except the double
buffer feature of the Output Compare unit is enabled in the fast PWM mode.
18.7.4 Phase Correct PWM Mode
The phase correct PWM mode (WGM21:0 = 1) provides a high resolution phase correct PWM waveform generation
option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from
BOTTOM to MAX and then from MAX to BOTTOM. In non-inverting Compare Output mode, the Output Compare
(OC2) is cleared on the Compare Match between TCNT2 and OCR2 while upcounting, and set on the Compare
Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation
TCNTn
OCRn Update
and
TOVn Interrupt Flag Set
Period 1 2 3
OCn
OCn
(COMn1:0 = 2)
(COMn1:0 = 3)
OCRn Interrupt Flag Set
4 5 6 7
f
OCnPWM
f
clk_I/O
N 256 = ------------------ATmega8A [DATASHEET] 107
8159E–AVR–02/2013
has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the
dual-slope PWM modes, these modes are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct PWM mode the counter
is incremented until the counter value matches MAX. When the counter reaches MAX, it changes the count
direction. The TCNT2 value will be equal to MAX for one timer clock cycle. The timing diagram for the phase correct
PWM mode is shown on Figure 18-7. The TCNT2 value is in the timing diagram shown as a histogram for
illustrating the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal
line marks on the TCNT2 slopes represent compare matches between OCR2 and TCNT2.
Figure 18-7. Phase Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The Interrupt Flag can
be used to generate an interrupt each time the counter reaches the BOTTOM value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC2 pin. Setting the
COM21:0 bits to 2 will produce a non-inverted PWM. An inverted PWM output can be generated by setting the
COM21:0 to 3 (see Table 18-5 on page 113). The actual OC2 value will only be visible on the port pin if the data
direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC2 Register
at the Compare Match between OCR2 and TCNT2 when the counter increments, and setting (or clearing) the
OC2 Register at Compare Match between OCR2 and TCNT2 when the counter decrements. The PWM frequency
for the output when using phase correct PWM can be calculated by the following equation:
The N variable represents the prescaler factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2 Register represent special cases when generating a PWM waveform output in
the phase correct PWM mode. If the OCR2 is set equal to BOTTOM, the output will be continuously low and if set
equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will
have the opposite logic values.
TOVn Interrupt Flag Set
OCn Interrupt Flag Set
1 2 3
TCNTn
Period
OCn
OCn
(COMn1:0 = 2)
(COMn1:0 = 3)
OCRn Update
f
OCnPCPWM
f
clk_I/O
N 510 = ------------------ATmega8A [DATASHEET] 108
8159E–AVR–02/2013
At the very start of period 2 in Figure 18-7 OCn has a transition from high to low even though there is no Compare
Match. The point of this transition is to guarantee symmetry around BOTTOM. There are two cases that give a
transition without Compare Match:
• OCR2A changes its value from MAX, like in Figure 18-7. When the OCR2A value is MAX the OCn pin value is
the same as the result of a down-counting Compare Match. To ensure symmetry around BOTTOM the OCn
value at MAX must correspond to the result of an up-counting Compare Match.
• The timer starts counting from a value higher than the one in OCR2A, and for that reason misses the Compare
Match and hence the OCn change that would have happened on the way up.
18.8 Timer/Counter Timing Diagrams
The following figures show the Timer/Counter in Synchronous mode, and the timer clock (clkT2) is therefore shown
as a clock enable signal. In Asynchronous mode, clkI/O should be replaced by the Timer/Counter Oscillator clock.
The figures include information on when Interrupt Flags are set. Figure 18-8 contains timing data for basic
Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than
phase correct PWM mode.
Figure 18-8. Timer/Counter Timing Diagram, no Prescaling
Figure 18-9 shows the same timing data, but with the prescaler enabled.
Figure 18-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
Figure 18-10 shows the setting of OCF2 in all modes except CTC mode.
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)ATmega8A [DATASHEET] 109
8159E–AVR–02/2013
Figure 18-10. Timer/Counter Timing Diagram, Setting of OCF2, with Prescaler (fclk_I/O/8)
Figure 18-11 shows the setting of OCF2 and the clearing of TCNT2 in CTC mode.
Figure 18-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Prescaler (fclk_I/O/8)
18.9 Asynchronous Operation of the Timer/Counter
18.9.1 Asynchronous Operation of Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken.
• Warning: When switching between asynchronous and synchronous clocking of Timer/Counter2, the Timer
Registers TCNT2, OCR2, and TCCR2 might be corrupted. A safe procedure for switching clock source is:
1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2.
2. Select clock source by setting AS2 as appropriate.
3. Write new values to TCNT2, OCR2, and TCCR2.
4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, and TCR2UB.
5. Clear the Timer/Counter2 Interrupt Flags.
6. Enable interrupts, if needed.
OCFn
OCRn
TCNTn
OCRn Value
OCRn - 1 OCRn OCRn + 1 OCRn + 2
clkI/O
clkTn
(clkI/O/8)
OCFn
OCRn
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)ATmega8A [DATASHEET] 110
8159E–AVR–02/2013
• The Oscillator is optimized for use with a 32.768 kHz watch crystal. Applying an external clock to the TOSC1 pin
may result in incorrect Timer/Counter2 operation. The CPU main clock frequency must be more than four times
the Oscillator frequency.
• When writing to one of the registers TCNT2, OCR2, or TCCR2, the value is transferred to a temporary register,
and latched after two positive edges on TOSC1. The user should not write a new value before the contents of
the temporary register have been transferred to its destination. Each of the three mentioned registers have their
individual temporary register, which means that e.g. writing to TCNT2 does not disturb an OCR2 write in
progress. To detect that a transfer to the destination register has taken place, the Asynchronous Status Register
– ASSR has been implemented.
• When entering Power-save mode after having written to TCNT2, OCR2, or TCCR2, the user must wait until the
written register has been updated if Timer/Counter2 is used to wake up the device. Otherwise, the MCU will
enter sleep mode before the changes are effective. This is particularly important if the Output Compare2
interrupt is used to wake up the device, since the Output Compare function is disabled during writing to OCR2
or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode before the OCR2UB bit returns to
zero, the device will never receive a Compare Match interrupt, and the MCU will not wake up.
• If Timer/Counter2 is used to wake the device up from Power-save mode, precautions must be taken if the user
wants to re-enter one of these modes: The interrupt logic needs one TOSC1 cycle to be reset. If the time
between wake-up and re-entering sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the
device will fail to wake up. If the user is in doubt whether the time before re-entering Power-save or Extended
Standby mode is sufficient, the following algorithm can be used to ensure that one TOSC1 cycle has elapsed:
1. Write a value to TCCR2, TCNT2, or OCR2.
2. Wait until the corresponding Update Busy Flag in ASSR returns to zero.
3. Enter Power-save or Extended Standby mode.
• When the asynchronous operation is selected, the 32.768kHz Oscillator for Timer/Counter2 is always running,
except in Power-down and Standby modes. After a Power-up Reset or Wake-up from Power-down or Standby
mode, the user should be aware of the fact that this Oscillator might take as long as one second to stabilize. The
user is advised to wait for at least one second before using Timer/Counter2 after Power-up or Wake-up from
Power-down or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost after a
wake-up from Power-down or Standby mode due to unstable clock signal upon start-up, no matter whether the
Oscillator is in use or a clock signal is applied to the TOSC1 pin.
• Description of wake up from Power-save or Extended Standby mode when the timer is clocked asynchronously:
When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that
is, the timer is always advanced by at least one before the processor can read the counter value. After wake-up,
the MCU is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction
following SLEEP.
• Reading of the TCNT2 Register shortly after wake-up from Power-save may give an incorrect result. Since
TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be done through a register
synchronized to the internal I/O clock domain. Synchronization takes place for every rising TOSC1 edge. When
waking up from Power-save mode, and the I/O clock (clkI/O) again becomes active, TCNT2 will read as the
previous value (before entering sleep) until the next rising TOSC1 edge. The phase of the TOSC clock after
waking up from Power-save mode is essentially unpredictable, as it depends on the wake-up time. The
recommended procedure for reading TCNT2 is thus as follows:
1. Write any value to either of the registers OCR2 or TCCR2.
2. Wait for the corresponding Update Busy Flag to be cleared.
3. Read TCNT2.
• During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer takes
three processor cycles plus one timer cycle. The timer is therefore advanced by at least one before the ATmega8A [DATASHEET] 111
8159E–AVR–02/2013
processor can read the timer value causing the setting of the Interrupt Flag. The Output Compare Pin is
changed on the timer clock and is not synchronized to the processor clock.
18.10 Timer/Counter Prescaler
Figure 18-12. Prescaler for Timer/Counter2
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main system I/O clock
clkI/O. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously clocked from the TOSC1 pin. This
enables use of Timer/Counter2 as a Real Time Counter (RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected
from Port B. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an
independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal. Applying
an external clock source to TOSC1 is not recommended.
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64, clkT2S/128, clkT2S/256, and
clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected. Setting the PSR2 bit in SFIOR resets the prescaler.
This allows the user to operate with a predictable prescaler.
10-BIT T/C PRESCALER
TIMER/COUNTER2 CLOCK SOURCE
clkI/O clkT2S
TOSC1
AS2
CS20
CS21
CS22
clkT2S/8
clkT2S/64
clkT2S/128
clkT2S/1024
clkT2S/256
clkT2S/32
0 PSR2
Clear
clkT2ATmega8A [DATASHEET] 112
8159E–AVR–02/2013
18.11 Register Description
18.11.1 TCCR2 – Timer/Counter Control Register
• Bit 7 – FOC2: Force Output Compare
The FOC2 bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with
future devices, this bit must be set to zero when TCCR2 is written when operating in PWM mode. When writing a
logical one to the FOC2 bit, an immediate Compare Match is forced on the waveform generation unit. The OC2
output is changed according to its COM21:0 bits setting. Note that the FOC2 bit is implemented as a strobe. Therefore
it is the value present in the COM21:0 bits that determines the effect of the forced compare.
A FOC2 strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR2 as TOP.
The FOC2 bit is always read as zero.
• Bit 6,3 – WGM21:0: Waveform Generation Mode
These bits control the counting sequence of the counter, the source for the maximum (TOP) counter value, and
what type of waveform generation to be used. Modes of operation supported by the Timer/Counter unit are: Normal
mode, Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes. See
Table 18-2 and “Modes of Operation” on page 104.
Note: 1. The CTC2 and PWM2 bit definition names are now obsolete. Use the WGM21:0 definitions. However, the functionality
and location of these bits are compatible with previous versions of the timer.
• Bit 5:4 – COM21:0: Compare Match Output Mode
These bits control the Output Compare Pin (OC2) behavior. If one or both of the COM21:0 bits are set, the OC2
output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction
Register (DDR) bit corresponding to OC2 pin must be set in order to enable the output driver.
When OC2 is connected to the pin, the function of the COM21:0 bits depends on the WGM21:0 bit setting. Table
18-3 shows the COM21:0 bit functionality when the WGM21:0 bits are set to a normal or CTC mode (non-PWM).
Bit 7 6 5 4 3 2 1 0
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20 TCCR2
Read/Write W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 18-2. Waveform Generation Mode Bit Description
Mode
WGM21
(CTC2)
WGM20
(PWM2)
Timer/Counter Mode of
Operation(1) TOP
Update of
OCR2
TOV2 Flag
Set
0 0 0 Normal 0xFF Immediate MAX
1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM
2 1 0 CTC OCR2 Immediate MAX
3 1 1 Fast PWM 0xFF BOTTOM MAX
Table 18-3. Compare Output Mode, Non-PWM Mode
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected.
0 1 Toggle OC2 on Compare Match
1 0 Clear OC2 on Compare Match
1 1 Set OC2 on Compare MatchATmega8A [DATASHEET] 113
8159E–AVR–02/2013
Table 18-4 shows the COM21:0 bit functionality when the WGM21:0 bits are set to fast PWM mode.
Note: 1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, the Compare Match is ignored, but
the set or clear is done at BOTTOM. See “Fast PWM Mode” on page 105 for more details.
Table 18-5 shows the COM21:0 bit functionality when the WGM21:0 bits are set to phase correct PWM mode.
Note: 1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, the Compare Match is ignored, but
the set or clear is done at TOP. See “Phase Correct PWM Mode” on page 106 for more details.
• Bit 2:0 – CS22:0: Clock Select
The three clock select bits select the clock source to be used by the Timer/Counter, see Table 18-6.
18.11.2 TCNT2 – Timer/Counter Register
Table 18-4. Compare Output Mode, Fast PWM Mode(1)
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected.
0 1 Reserved
1 0 Clear OC2 on Compare Match, set OC2 at BOTTOM,
(non-inverting mode)
1 1 Set OC2 on Compare Match, clear OC2 at BOTTOM,
(inverting mode)
Table 18-5. Compare Output Mode, Phase Correct PWM Mode(1)
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected.
0 1 Reserved
1 0 Clear OC2 on Compare Match when up-counting. Set OC2 on Compare Match
when downcounting.
1 1 Set OC2 on Compare Match when up-counting. Clear OC2 on Compare Match
when downcounting.
Table 18-6. Clock Select Bit Description
CS22 CS21 CS20 Description
0 0 0 No clock source (Timer/Counter stopped).
0 0 1 clkT2S/(No prescaling)
0 1 0 clkT2S/8 (From prescaler)
0 1 1 clkT2S/32 (From prescaler)
1 0 0 clkT2S/64 (From prescaler)
1 0 1 clkT2S/128 (From prescaler)
1 1 0 clkT2S/256 (From prescaler)
1 1 1 clkT2S/1024 (From prescaler)
Bit 7 6 5 4 3 2 1 0
TCNT2[7:0] TCNT2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 114
8159E–AVR–02/2013
The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit
counter. Writing to the TCNT2 Register blocks (removes) the Compare Match on the following timer clock. Modifying
the counter (TCNT2) while the counter is running, introduces a risk of missing a Compare Match between
TCNT2 and the OCR2 Register.
18.11.3 OCR2 – Output Compare Register
The Output Compare Register contains an 8-bit value that is continuously compared with the counter value
(TCNT2). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the
OC2 pin.
18.11.4 ASSR – Asynchronous Status Register
• Bit 3 – AS2: Asynchronous Timer/Counter2
When AS2 is written to zero, Timer/Counter 2 is clocked from the I/O clock, clkI/O. When AS2 is written to one,
Timer/Counter 2 is clocked from a crystal Oscillator connected to the Timer Oscillator 1 (TOSC1) pin. When the
value of AS2 is changed, the contents of TCNT2, OCR2, and TCCR2 might be corrupted.
• Bit 2 – TCN2UB: Timer/Counter2 Update Busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set. When TCNT2 has
been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates
that TCNT2 is ready to be updated with a new value.
• Bit 1 – OCR2UB: Output Compare Register2 Update Busy
When Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomes set. When OCR2 has been
updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates that
OCR2 is ready to be updated with a new value.
• Bit 0 – TCR2UB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomes set. When TCCR2 has
been updated from the temporary storage register, this bit is cleared by hardware. A logical zero in this bit indicates
that TCCR2 is ready to be updated with a new value.
If a write is performed to any of the three Timer/Counter2 Registers while its update busy flag is set, the updated
value might get corrupted and cause an unintentional interrupt to occur.
The mechanisms for reading TCNT2, OCR2, and TCCR2 are different. When reading TCNT2, the actual timer
value is read. When reading OCR2 or TCCR2, the value in the temporary storage register is read.
Bit 7 6 5 4 3 2 1 0
OCR2[7:0] OCR2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – – – AS2 TCN2UB OCR2UB TCR2UB ASSR
Read/Write R R R R R/W R R R
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 115
8159E–AVR–02/2013
18.11.5 TIMSK – Timer/Counter Interrupt Mask Register
• Bit 7 – OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable
When the OCIE2 bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare
Match interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter2 occurs
(i.e., when the OCF2 bit is set in the Timer/Counter Interrupt Flag Register – TIFR).
• Bit 6 – TOIE2: Timer/Counter2 Overflow Interrupt Enable
When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the Timer/Counter2 Overflow
interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter2 occurs (i.e., when
the TOV2 bit is set in the Timer/Counter Interrupt Flag Register – TIFR).
18.11.6 TIFR – Timer/Counter Interrupt Flag Register
• Bit 7 – OCF2: Output Compare Flag 2
The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2 and the data in OCR2 –
Output Compare Register2. OCF2 is cleared by hardware when executing the corresponding interrupt Handling
Vector. Alternatively, OCF2 is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE2
(Timer/Counter2 Compare Match Interrupt Enable), and OCF2 are set (one), the Timer/Counter2 Compare Match
Interrupt is executed.
• Bit 6 – TOV2: Timer/Counter2 Overflow Flag
The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware when executing
the corresponding interrupt Handling Vector. Alternatively, TOV2 is cleared by writing a logic one to the flag.
When the SREG I-bit, TOIE2 (Timer/Counter2 Overflow Interrupt Enable), and TOV2 are set (one), the
Timer/Counter2 Overflow interrupt is executed. In PWM mode, this bit is set when Timer/Counter2 changes counting
direction at 0x00.
18.11.7 SFIOR – Special Function IO Register
• Bit 1 – PSR2: Prescaler Reset Timer/Counter2
When this bit is written to one, the Timer/Counter2 prescaler will be reset. The bit will be cleared by hardware after
the operation is performed. Writing a zero to this bit will have no effect. This bit will always be read as zero if
Timer/Counter2 is clocked by the internal CPU clock. If this bit is written when Timer/Counter2 is operating in Asynchronous
mode, the bit will remain one until the prescaler has been reset.
Bit 7 6 5 4 3 2 1 0
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – – – ACME PUD PSR2 PSR10 SFIOR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATmega8A [DATASHEET] 116
8159E–AVR–02/2013
19. Serial Peripheral Interface – SPI
19.1 Features • Full-duplex, Three-wire Synchronous Data Transfer
• Master or Slave Operation
• LSB First or MSB First Data Transfer
• Seven Programmable Bit Rates
• End of Transmission Interrupt Flag
• Write Collision Flag Protection
• Wake-up from Idle Mode
• Double Speed (CK/2) Master SPI Mode
19.2 Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega8A and
peripheral devices or between several AVR devices.
Figure 19-1. SPI Block Diagram(1)
Note: 1. Refer to “Pin Configurations” on page 2, and Table 13-2 on page 56 for SPI pin placement.
The interconnection between Master and Slave CPUs with SPI is shown in Figure 19-2. The system consists of two
Shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low SPI2X SPI2X
DIVIDER
/2/4/8/16/32/64/128ATmega8A [DATASHEET] 117
8159E–AVR–02/2013
the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective Shift
Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always
shifted from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the Master In –
Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling high the Slave
Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by
user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the
SPI clock generator, and the hardware shifts the eight bits into the Slave. After shifting one byte, the SPI clock generator
stops, setting the end of Transmission Flag (SPIF). If the SPI interrupt enable bit (SPIE) in the SPCR
Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer
Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is
driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not
be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely
shifted, the end of Transmission Flag, SPIF is set. If the SPI interrupt enable bit, SPIE, in the SPCR
Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before
reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 19-2. SPI Master-Slave Interconnection
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that
bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When
receiving data, however, a received character must be read from the SPI Data Register before the next character
has been completely shifted in. Otherwise, the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of
the clock signal, the minimum low and high periods should be:
Low period: longer than 2 CPU clock cycles
High period: longer than 2 CPU clock cycles.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to
Table 19-1. For more details on automatic port overrides, refer to “Alternate Port Functions” on page 54.
MSB MASTER LSB
8 BIT SHIFT REGISTER
MSB SLAVE LSB
8 BIT SHIFT REGISTER
MISO
MOSI
SPI
CLOCK GENERATOR
SCK
SS
MISO
MOSI
SCK
SS
VCC
SHIFT
ENABLEATmega8A [DATASHEET] 118
8159E–AVR–02/2013
Note: 1. See “Port B Pins Alternate Functions” on page 56 for a detailed description of how to define the direction of the
user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission.
DDR_SPI in the examples must be replaced by the actual Data Direction Register controlling the SPI pins.
DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI
is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB.
Table 19-1. SPI Pin Overrides(1)
Pin Direction, Master SPI Direction, Slave SPI
MOSI User Defined Input
MISO Input User Defined
SCK User Defined Input
SS User Defined InputATmega8A [DATASHEET] 119
8159E–AVR–02/2013
Note: 1. See “About Code Examples” on page 6.
Assembly Code Example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi r17,(1<>8);
UBRRL = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSRB = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}ATmega8A [DATASHEET] 137
8159E–AVR–02/2013
20.6.9 Receive Compete Flag and Interrupt
The USART Receiver has one flag that indicates the Receiver state.
The Receive Complete (RXC) Flag indicates if there are unread data present in the receive buffer. This flag is one
when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any
unread data). If the Receiver is disabled (RXEN = 0), the receive buffer will be flushed and consequently the RXC
bit will become zero.
When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive Complete Interrupt
will be executed as long as the RXC Flag is set (provided that global interrupts are enabled). When interrupt-driven
data reception is used, the receive complete routine must read the received data from UDR in order to clear the
RXC Flag, otherwise a new interrupt will occur once the interrupt routine terminates.
20.6.10 Receiver Error Flags
The USART Receiver has three error flags: Frame Error (FE), Data OverRun (DOR) and Parity Error (PE). All can
be accessed by reading UCSRA. Common for the error flags is that they are located in the receive buffer together
with the frame for which they indicate the error status. Due to the buffering of the error flags, the UCSRA must be
read before the receive buffer (UDR), since reading the UDR I/O location changes the buffer read location. Another
equality for the error flags is that they can not be altered by software doing a write to the flag location. However, all
flags must be set to zero when the UCSRA is written for upward compatibility of future USART implementations.
None of the error flags can generate interrupts.
The Frame Error (FE) Flag indicates the state of the first stop bit of the next readable frame stored in the receive
buffer. The FE Flag is zero when the stop bit was correctly read (as one), and the FE Flag will be one when the
stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions
and protocol handling. The FE Flag is not affected by the setting of the USBS bit in UCSRC since the Receiver
ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing
to UCSRA.
The Data OverRun (DOR) Flag indicates data loss due to a Receiver buffer full condition. A Data OverRun occurs
when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a
new start bit is detected. If the DOR Flag is set there was one or more serial frame lost between the frame last read
from UDR, and the next frame read from UDR. For compatibility with future devices, always write this bit to zero
when writing to UCSRA. The DOR Flag is cleared when the frame received was successfully moved from the Shift
Register to the receive buffer.
The Parity Error (PE) Flag indicates that the next frame in the receive buffer had a parity error when received. If
parity check is not enabled the PE bit will always be read zero. For compatibility with future devices, always set this
bit to zero when writing to UCSRA. For more details see “Parity Bit Calculation” on page 130 and “Parity Checker”
on page 137.
20.6.11 Parity Checker
The Parity Checker is active when the high USART Parity mode (UPM1) bit is set. Type of parity check to be performed
(odd or even) is selected by the UPM0 bit. When enabled, the Parity Checker calculates the parity of the
data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the
check is stored in the receive buffer together with the received data and stop bits. The Parity Error (PE) Flag can
then be read by software to check if the frame had a parity error.
The PE bit is set if the next character that can be read from the receive buffer had a parity error when received and
the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the receive buffer (UDR) is read.
20.6.12 Disabling the Receiver
In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing receptions will therefore
be lost. When disabled (i.e., the RXEN is set to zero) the Receiver will no longer override the normal functionATmega8A [DATASHEET] 138
8159E–AVR–02/2013
of the RxD port pin. The Receiver buffer FIFO will be flushed when the Receiver is disabled. Remaining data in the
buffer will be lost.
20.6.13 Flushing the Receive Buffer
The Receiver buffer FIFO will be flushed when the Receiver is disabled (i.e., the buffer will be emptied of its contents).
Unread data will be lost. If the buffer has to be flushed during normal operation, due to for instance an error
condition, read the UDR I/O location until the RXC Flag is cleared. The following code example shows how to flush
the receive buffer.
Note: 1. See “About Code Examples” on page 6.
20.7 Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The
clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous
serial frames at the RxD pin. The data recovery logic samples and low pass filters each incoming bit, thereby
improving the noise immunity of the Receiver. The asynchronous reception operational range depends on the
accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
20.7.1 Asynchronous Clock Recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 20-5 illustrates the sampling
process of the start bit of an incoming frame. The sample rate is 16 times the baud rate for Normal mode, and
eight times the baud rate for Double Speed mode. The horizontal arrows illustrate the synchronization variation
due to the sampling process. Note the larger time variation when using the Double Speed mode (U2X = 1) of operation.
Samples denoted zero are samples done when the RxD line is idle (i.e., no communication activity).
Figure 20-5. Start Bit Sampling
When the clock recovery logic detects a high (idle) to low (start) transition on the RxD line, the start bit detection
sequence is initiated. Let sample 1 denote the first zero-sample as shown in the figure. The clock recovery logic
Assembly Code Example(1)
USART_Flush:
sbis UCSRA, RXC
ret
in r16, UDR
rjmp USART_Flush
C Code Example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRA & (1< 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck 12MHz
High: > 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck 12MHz
25.9.1 Serial Programming Algorithm
When writing serial data to the ATmega8A, data is clocked on the rising edge of SCK.
When reading data from the ATmega8A, data is clocked on the falling edge of SCK. See Figure 25-8 for timing
details.
Table 25-14. Pin Mapping Serial Programming
Symbol Pins I/O Description
MOSI PB3 I Serial data in
MISO PB4 O Serial data out
SCK PB5 I Serial clock
VCC
GND
XTAL1
SCK
MISO
MOSI
RESET
PB3
PB4
PB5
+2.7 - 5.5V
AVCC
+2.7 - 5.5V (2)ATmega8A [DATASHEET] 221
8159E–AVR–02/2013
To program and verify the ATmega8A in the Serial Programming mode, the following sequence is recommended
(See four byte instruction formats in Table 25-16):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems, the programmer
can not guarantee that SCK is held low during Power-up. In this case, RESET must be given a
positive pulse of at least two CPU clock cycles duration after SCK has been set to “0”.
2. Wait for at least 20 ms and enable Serial Programming by sending the Programming Enable serial instruction
to pin MOSI.
3. The Serial Programming instructions will not work if the communication is out of synchronization. When in
sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable
instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the
0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The page size is found in Table 25-5 on page 210. The
memory page is loaded one byte at a time by supplying the 5LSB of the address and data together with
the Load Program memory Page instruction. To ensure correct loading of the page, the data Low byte
must be loaded before data High byte is applied for a given address. The Program memory Page is stored
by loading the Write Program memory Page instruction with the 7 MSB of the address. If polling is not
used, the user must wait at least tWD_FLASH before issuing the next page. (See Table 25-15).
5. Note: If other commands than polling (read) are applied before any write operation (FLASH, EEPROM,
Lock Bits, Fuses) is completed, it may result in incorrect programming.
6. The EEPROM array is programmed one byte at a time by supplying the address and data together with
the appropriate Write instruction. An EEPROM memory location is first automatically erased before new
data is written. If polling is not used, the user must wait at least tWD_EEPROM before issuing the next byte.
(See Table 25-15 on page 222). In a chip erased device, no 0xFFs in the data file(s) need to be
programmed.
7. Any memory location can be verified by using the Read instruction which returns the content at the
selected address at serial output MISO.
8. At the end of the programming session, RESET can be set high to commence normal operation.
9. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off
25.9.2 Data Polling Flash
When a page is being programmed into the Flash, reading an address location within the page being programmed
will give the value 0xFF. At the time the device is ready for a new page, the programmed value will read correctly.
This is used to determine when the next page can be written. Note that the entire page is written simultaneously
and any address within the page can be used for polling. Data polling of the Flash will not work for the value 0xFF,
so when programming this value, the user will have to wait for at least tWD_FLASH before programming the next
page. As a chip-erased device contains 0xFF in all locations, programming of addresses that are meant to contain
0xFF, can be skipped. See Table 97 for tWD_FLASH value.
25.9.3 Data Polling EEPROM
When a new byte has been written and is being programmed into EEPROM, reading the address location being
programmed will give the value 0xFF. At the time the device is ready for a new byte, the programmed value will
read correctly. This is used to determine when the next byte can be written. This will not work for the value 0xFF,
but the user should have the following in mind: As a chip-erased device contains 0xFF in all locations, programming
of addresses that are meant to contain 0xFF, can be skipped. This does not apply if the EEPROM is Re-ATmega8A [DATASHEET] 222
8159E–AVR–02/2013
programmed without chip-erasing the device. In this case, data polling cannot be used for the value 0xFF, and the
user will have to wait at least tWD_EEPROM before programming the next byte. See Table 25-15 for tWD_EEPROM value.
Figure 25-8. Serial Programming Waveforms
Table 25-15. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FUSE 4.5 ms
tWD_FLASH 4.5 ms
tWD_EEPROM 9.0 ms
tWD_ERASE 9.0 ms
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUTATmega8A [DATASHEET] 223
8159E–AVR–02/2013
Note: a = address high bits
b = address low bits
H = 0 – Low byte, 1 – High byte
o = data out
i = data in
x = don’t care
Table 25-16. Serial Programming Instruction Set
Instruction
Instruction Format
Byte 1 Byte 2 Byte 3 Byte4 Operation
Programming Enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable Serial Programming after
RESET goes low.
Chip Erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip Erase EEPROM and Flash.
Read Program Memory 0010 H000 0000 aaaa bbbb bbbb oooo oooo Read H (high or low) data o from
Program memory at word address
a:b.
Load Program Memory
Page
0100 H000 0000 xxxx xxxb bbbb iiii iiii Write H (high or low) data i to
Program memory page at word
address b. Data Low byte must be
loaded before Data High byte is
applied within the same address.
Write Program Memory
Page
0100 1100 0000 aaaa bbbx xxxx xxxx xxxx Write Program memory Page at
address a:b.
Read EEPROM Memory 1010 0000 00xx xxxa bbbb bbbb oooo oooo Read data o from EEPROM
memory at address a:b.
Write EEPROM Memory 1100 0000 00xx xxxa bbbb bbbb iiii iiii Write data i to EEPROM memory
at address a:b.
Read Lock Bits 0101 1000 0000 0000 xxxx xxxx xxoo oooo Read Lock Bits. “0” = programmed,
“1” = unprogrammed. See Table
25-1 on page 207 for details.
Write Lock Bits 1010 1100 111x xxxx xxxx xxxx 11ii iiii Write Lock Bits. Set bits = “0” to
program Lock Bits. See Table 25-
1 on page 207 for details.
Read Signature Byte 0011 0000 00xx xxxx xxxx xxbb oooo oooo Read Signature Byte o at address
b.
Write Fuse Bits 1010 1100 1010 0000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram. See Table 25-4 on
page 209 for details.
Write Fuse High Bits 1010 1100 1010 1000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram. See Table 25-3 on
page 208 for details.
Read Fuse Bits 0101 0000 0000 0000 xxxx xxxx oooo oooo Read Fuse Bits. “0” = programmed,
“1” = unprogrammed. See Table
25-4 on page 209 for details.
Read Fuse High Bits 0101 1000 0000 1000 xxxx xxxx oooo oooo Read Fuse high bits. “0” = programmed,
“1” = unprogrammed.
See Table 25-3 on page 208 for
details.
Read Calibration Byte 0011 1000 00xx xxxx 0000 00bb oooo oooo Read Calibration ByteATmega8A [DATASHEET] 224
8159E–AVR–02/2013
25.9.4 SPI Serial Programming Characteristics
For characteristics of the SPI module, see “SPI Timing Characteristics” on page 230.ATmega8A [DATASHEET] 225
8159E–AVR–02/2013
26. Electrical Characteristics – TA = -40°C to 85°C
Note: Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured
on the same process technology. Min and Max values will be available after the device is characterized.
26.2 DC Characteristics
26.1 Absolute Maximum Ratings*
Operating Temperature.................................. -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ................................................ 40.0mA
DC Current VCC and GND Pins................................. 300.0mA
TA = -40C to 85C, VCC = 2.7V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min Typ Max Units
VIL
Input Low Voltage except
XTAL1 and RESET pins VCC = 2.7V - 5.5V -0.5 0.2 VCC(1) V
VIH
Input High Voltage except
XTAL1 and RESET pins VCC = 2.7V - 5.5V 0.6 VCC(2) VCC + 0.5 V
VIL1
Input Low Voltage
XTAL1 pin
VCC = 2.7V - 5.5V -0.5 0.1 VCC(1) V
VIH1
Input High Voltage
XTAL 1 pin
VCC = 2.7V - 5.5V 0.8 VCC(2) VCC + 0.5 V
VIL2
Input Low Voltage
RESET pin
VCC = 2.7V - 5.5V -0.5 0.2 VCC V
VIH2
Input High Voltage
RESET pin
VCC = 2.7V - 5.5V 0.9 VCC(2) VCC + 0.5 V
VIL3
Input Low Voltage
RESET pin as I/O VCC = 2.7V - 5.5V -0.5 0.2 VCC V
VIH3
Input High Voltage
RESET pin as I/O VCC = 2.7V - 5.5V 0.6 VCC(2)
0.7 VCC(2) VCC + 0.5 V
VOL
Output Low Voltage(3)
(Ports B,C,D)
I
OL = 20mA, VCC = 5V
IOL = 10mA, VCC = 3V
0.9
0.6
V
V
VOH
Output High Voltage(4)
(Ports B,C,D)
I
OH = -20mA, VCC = 5V
IOH = -10mA, VCC = 3V
4.2
2.2
V
V
IIL
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin low
(absolute value) 1 µA
IIH
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin high
(absolute value) 1 µAATmega8A [DATASHEET] 226
8159E–AVR–02/2013
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOL, for all ports, should not exceed 300mA.
2] The sum of all IOL, for ports C0 - C5 should not exceed 100mA.
3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOH, for all ports, should not exceed 300mA.
2] The sum of all IOH, for port C0 - C5, should not exceed 100mA.
3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
5. Minimum VCC for Power-down is 2.5V.
RRST Reset Pull-up Resistor 30 80 k
Rpu I/O Pin Pull-up Resistor 20 50 k
I
CC
Power Supply Current
Active 4MHz, VCC = 3V 2 5 mA
Active 8MHz, VCC = 5V 6 15 mA
Idle 4MHz, VCC = 3V 0.5 2 mA
Idle 8MHz, VCC = 5V 2.2 7 mA
Power-down mode(5) WDT enabled, VCC = 3V <10 28 µA
WDT disabled, VCC = 3V <1 3 µA
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 40 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nA
tACPD
Analog Comparator
Propagation Delay
VCC = 2.7V
VCC = 5.0V
750
500 ns
TA = -40C to 85C, VCC = 2.7V to 5.5V (unless otherwise noted) (Continued)
Symbol Parameter Condition Min Typ Max UnitsATmega8A [DATASHEET] 227
8159E–AVR–02/2013
26.3 Speed Grades
Figure 26-1. Maximum Frequency vs. Vcc
26.4 Clock Characteristics
26.4.1 External Clock Drive Waveforms
Figure 26-2. External Clock Drive Waveforms
26.4.2 External Clock Drive
2.7V 4.5V 5.5V
Safe Operating Area
16 MHz
8 MHz
VIL1
VIH1
Table 26-1. External Clock Drive
Symbol Parameter
VCC = 2.7V to 5.5V VCC = 4.5V to 5.5V
Min Max Min Max Units
1/tCLCL Oscillator Frequency 0 8 0 16 MHz
tCLCL Clock Period 125 62.5 ns
tCHCX High Time 50 25 ns
tCLCX Low Time 50 25 ns
tCLCH Rise Time 1.6 0.5 s
tCHCL Fall Time 1.6 0.5 s
tCLCL
Change in period from one
clock cycle to the next 2 2%ATmega8A [DATASHEET] 228
8159E–AVR–02/2013
Notes: 1. R should be in the range 3 k - 100 k, and C should be at least 20 pF. The C values given in the table includes pin
capacitance. This will vary with package type.
2. The frequency will vary with package type and board layout.
26.5 System and Reset Characteristics
Notes: 1. The Power-on Reset will not work unless the supply voltage has been below VPOT (falling).
2. VBOT may be below nominal minimum operating voltage for some devices. For devices where this is the case, the
device is tested down to VCC = VBOT during the production test. This guarantees that a Brown-out Reset will occur
before VCC drops to a voltage where correct operation of the microcontroller is no longer guaranteed. The test is
performed using BODLEVEL = 1 and BODLEVEL = 0 for ATmega8A.
Table 26-2. External RC Oscillator, Typical Frequencies
R [k]
(1) C [pF] f(2)
33 22 650kHz
10 22 2.0MHz
Table 26-3. Reset, Brown-out and Internal Voltage Reference Characteristics
Symbol Parameter Condition Min Typ Max Units
VPOT
Power-on Reset Threshold Voltage
(rising)(1) 1.4 2.3 V
Power-on Reset Threshold Voltage
(falling) 1.3 2.3 V
VRST RESET Pin Threshold Voltage 0.2 0.9 VCC
tRST Minimum pulse width on RESET Pin 1.5 µs
VBOT
Brown-out Reset Threshold Voltage(2) BODLEVEL = 1 2.40 2.60 2.90
V
BODLEVEL = 0 3.70 4.00 4.50
tBOD
Minimum low voltage period for Brownout
Detection
BODLEVEL = 1 2 µs
BODLEVEL = 0 2 µs
VHYST Brown-out Detector hysteresis 130 mV
VBG Bandgap reference voltage 1.15 1.23 1.35 V
tBG Bandgap reference start-up time 40 70 µs
IBG Bandgap reference current consumption 10 µsATmega8A [DATASHEET] 229
8159E–AVR–02/2013
26.6 Two-wire Serial Interface Characteristics
Table 26-4 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega8A Two-wire Serial
Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 26-3.
Notes: 1. In ATmega8A, this parameter is characterized and not 100% tested.
2. Required only for fSCL > 100kHz.
Table 26-4. Two-wire Serial Bus Requirements
Symbol Parameter Condition Min Max Units
VIL Input Low-voltage -0.5 0.3 VCC V
VIH Input High-voltage 0.7 VCC VCC + 0.5 V
Vhys(1) Hysteresis of Schmitt Trigger Inputs 0.05 VCC(2) – V
VOL(1) Output Low-voltage 3mA sink current 0 0.4 V
tr
(1) Rise Time for both SDA and SCL 20 + 0.1Cb
(3)(2) 300 ns
tof
(1) Output Fall Time from VIHmin to VILmax 10 pF < Cb < 400 pF(3) 20 + 0.1Cb
(3)(2) 250 ns
tSP(1) Spikes Suppressed by Input Filter 0 50(2) ns
Ii Input Current each I/O Pin 0.1VCC < Vi
< 0.9VCC -10 10 µA
Ci
(1) Capacitance for each I/O Pin – 10 pF
fSCL SCL Clock Frequency fCK(4) > max(16fSCL, 250kHz)(5) 0 400 kHz
Rp Value of Pull-up resistor
fSCL 100kHz
fSCL > 100kHz
tHD;STA Hold Time (repeated) START Condition
fSCL 100kHz 4.0 – µs
fSCL > 100kHz 0.6 – µs
tLOW Low Period of the SCL Clock
fSCL 100kHz(6) 4.7 – µs
fSCL > 100kHz(7) 1.3 – µs
tHIGH High period of the SCL clock
fSCL 100kHz 4.0 – µs
fSCL > 100kHz 0.6 – µs
tSU;STA Set-up time for a repeated START condition
fSCL 100kHz 4.7 – µs
fSCL > 100kHz 0.6 – µs
tHD;DAT Data hold time
fSCL 100kHz 0 3.45 µs
fSCL > 100kHz 0 0.9 µs
tSU;DAT Data setup time
fSCL 100kHz 250 – ns
fSCL > 100kHz 100 – ns
tSU;STO Setup time for STOP condition
fSCL 100kHz 4.0 – µs
fSCL > 100kHz 0.6 – µs
tBUF
Bus free time between a STOP and START
condition
fSCL 100kHz 4.7 – µs
fSCL > 100kHz 1.3 – µs
VCC – 0,4V
3mA ---------------------------- 1000ns
Cb
-------------------
VCC – 0,4V
3mA ---------------------------- 300ns
Cb
---------------- ATmega8A [DATASHEET] 230
8159E–AVR–02/2013
3. Cb = capacitance of one bus line in pF.
4. fCK = CPU clock frequency
5. This requirement applies to all ATmega8A Two-wire Serial Interface operation. Other devices connected to the Two-wire
Serial Bus need only obey the general fSCL requirement.
6. The actual low period generated by the ATmega8A Two-wire Serial Interface is (1/fSCL - 2/fCK), thus fCK must be greater than
6MHz for the low time requirement to be strictly met at fSCL = 100kHz.
7. The actual low period generated by the ATmega8A Two-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement
will not be strictly met for fSCL > 308kHz when fCK = 8MHz. Still, ATmega8A devices connected to the bus may communicate
at full speed (400kHz) with other ATmega8A devices, as well as any other device with a proper tLOW acceptance margin.
Figure 26-3. Two-wire Serial Bus Timing
26.7 SPI Timing Characteristics
See Figure 26-4 and Figure 26-5 for details.
Note: 1. In SPI Programming mode the minimum SCK high/low period is:
- 2tCLCL for fCK < 12MHz
- 3tCLCL for fCK > 12MHz
t
SU;STA
t
LOW
t
HIGH
t
LOW
t
of
t
HD;STA t
HD;DAT t
SU;DAT t
SU;STO
t
BUF
SCL
SDA
t
r
Table 26-5. SPI Timing Parameters
Description Mode Min Typ Max
1 SCK period Master See Table 19-4
ns
2 SCK high/low Master 50% duty cycle
3 Rise/Fall time Master 3.6
4 Setup Master 10
5 Hold Master 10
6 Out to SCK Master 0.5 • tSCK
7 SCK to out Master 10
8 SCK to out high Master 10
9 SS low to out Slave 15
10 SCK period Slave 4 • tck
11 SCK high/low(1) Slave 2 • tck
12 Rise/Fall time Slave 1.6
13 Setup Slave 10
14 Hold Slave 10
15 SCK to out Slave 15
16 SCK to SS high Slave 20
17 SS high to tri-state Slave 10
18 SS low to SCK Salve 2 • tckATmega8A [DATASHEET] 231
8159E–AVR–02/2013
Figure 26-4. SPI interface timing requirements (Master Mode)
Figure 26-5. SPI interface timing requirements (Slave Mode)
MOSI
(Data Output)
SCK
(CPOL = 1)
MISO
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
6 1
2 2
4 5 3
7 8
MISO
(Data Output)
SCK
(CPOL = 1)
MOSI
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
10
11 11
13 14 12
15 17
9
X
16
18ATmega8A [DATASHEET] 232
8159E–AVR–02/2013
26.8 ADC Characteristics
Notes: 1. Values are guidelines only.
2. Minimum for AVCC is 2.7V.
3. Maximum for AVCC is 5.5V.
4. Maximum conversion time is 1/50kHz*25 = 0.5 ms.
Table 26-6. ADC Characteristics
Symbol Parameter Condition Min(1) Typ(1) Max(1) Units
Resolution Single Ended Conversion 10 Bits
Absolute accuracy
(Including INL, DNL,
Quantization Error, Gain,
and Offset Error)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1.75 LSB
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 1MHz
3 LSB
Integral Non-linearity (INL)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz 0.75 LSB
Differential Non-linearity
(DNL)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz 0.5 LSB
Gain Error Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1 LSB
Offset Error Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1 LSB
Conversion Time(4) Free Running Conversion 13 260 µs
Clock Frequency 50 1000 kHz
AVCC Analog Supply Voltage VCC - 0.3(2) VCC + 0.3(3) V
VREF Reference Voltage 2.0 AVCC V
VIN Input voltage GND VREF V
Input bandwidth 38.5 kHz
VINT Internal Voltage Reference 2.3 2.56 2.8 V
RREF Reference Input Resistance 32 k
RAIN Analog Input Resistance 55 100 MATmega8A [DATASHEET] 233
8159E–AVR–02/2013
27. Electrical Characteristics – TA = -40°C to 105°C
Absolute Maximum Ratings*
27.1 DC Characteristics
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
Operating Temperature.................................. -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ............................................... 40.0 mA
DC Current VCC and GND Pins................................ 200.0 mA
TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min. Typ. Max. Units
VIL
Input Low Voltage, Except
XTAL1 and RESET pin VCC = 2.7V - 5.5V -0.5 0.2VCC(1) V
VIL1
Input Low Voltage,
XTAL1 pin VCC = 2.7V - 5.5V -0.5 0.1VCC(1) V
VIL2
Input Low Voltage,
RESET pin VCC = 2.7V - 5.5V -0.5 0.1VCC(1) V
VIH
Input High Voltage,
Except XTAL1 and
RESET pins
VCC = 2.7V - 5.5V 0.6VCC(2) VCC + 0.5 V
VIH1
Input High Voltage,
XTAL1 pin VCC = 2.7V - 5.5V 0.8VCC(2) VCC + 0.5 V
VIH2
Input High Voltage,
RESET pin VCC = 2.7V - 5.5V 0.9VCC(2) VCC + 0.5 V
VOL
Output Low Voltage(3),
Port B (except RESET)
I
OL =20 mA, VCC = 5V
IOL =10 mA, VCC = 3V
0.8
0.6 V
VOH
Output High Voltage(4),
Port B (except RESET)
I
OH = -20 mA, VCC = 5V
IOH = -10 mA, VCC = 3V
4.0
2.2 V
IIL
Input Leakage
Current I/O Pin 3 µA
IIH
Input Leakage
Current I/O Pin 3 µA
RRST Reset Pull-up Resistor 30 80 k
RPU I/O Pin Pull-up Resistor 20 50 k
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 20 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nAATmega8A [DATASHEET] 234
8159E–AVR–02/2013
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOL, for all ports, should not exceed 300 mA.
2] The sum of all IOL, for ports C0 - C5 should not exceed 100 mA.
3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200 mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20 mA at Vcc = 5V, 10 mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOH, for all ports, should not exceed 300 mA.
2] The sum of all IOH, for port C0 - C5, should not exceed 100 mA.
3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200 mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
Note: 1. The current consumption values include input leakage current.
27.1.1 ATmega8A DC Characteristics
Table 27-1. TA = -40C to 105C, VCC = 1.8V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min. Typ. Max. Units
ICC
Power Supply Current
Active 4 MHz, VCC = 3V 6 mA
Active 8 MHz, VCC = 5V 15 mA
Idle 4 MHz, VCC = 3V 3 mA
Idle 8 MHz, VCC = 5V 8 mA
Power-down mode(1) WDT enabled, VCC = 3V 35 µA
WDT disabled, VCC = 3V 6 µAATmega8A [DATASHEET] 235
8159E–AVR–02/2013
28. Typical Characteristics – TA = -40°C to 85°C
The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption
measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A
sine wave generator with Rail-to-Rail output is used as clock source.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating frequency, loading of
I/O pins, switching rate of I/O pins, code executed and ambient temperature. The dominating factors are operating
voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where CL = load capacitance,
VCC = operating voltage and f = average switching frequency of I/O pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to function properly at
frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down
mode with Watchdog Timer disabled represents the differential current drawn by the Watchdog Timer.
28.1 Active Supply Current
Figure 28-1. Active Supply Current vs. Frequency (0.1 - 1.0MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)ATmega8A [DATASHEET] 236
8159E–AVR–02/2013
Figure 28-2. Active Supply Current vs. Frequency (1 - 16MHz)
Figure 28-3. Active Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
0
2
4
6
8
10
12
14
0246 8 10 12 14 16
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
85 °C
25 °C
-40 °C
3
4
5
6
7
8
9
10
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 237
8159E–AVR–02/2013
Figure 28-4. Active Supply Current vs. VCC (Internal RC Oscillator, 4MHz)
Figure 28-5. Active Supply Current vs. VCC (Internal RC Oscillator, 2MHz)
85 °C
25 °C
-40 °C
1.5
2
2.5
3
3.5
4
4.5
5
5.5
6
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
1.2
1.6
2
2.4
2.8
3.2
3.6
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 238
8159E–AVR–02/2013
Figure 28-6. Active Supply Current vs. VCC (Internal RC Oscillator, 1MHz)
Figure 28-7. Active Supply Current vs. VCC (32kHz External Oscillator)
85 °C
25 °C
-40 °C
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
25 °C
40
45
50
55
60
65
70
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)ATmega8A [DATASHEET] 239
8159E–AVR–02/2013
28.2 Idle Supply Current
Figure 28-8. Idle Supply Current vs. Frequency (0.1 - 1.0MHz)
Figure 28-9. Idle Supply Current vs. Frequency (1 - 16MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
0
1
2
3
4
5
6
0246 8 10 12 14 16
Frequency (MHz)
ICC (mA)ATmega8A [DATASHEET] 240
8159E–AVR–02/2013
Figure 28-10. Idle Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
Figure 28-11. Idle Supply Current vs. VCC (Internal RC Oscillator, 4MHz)
85 °C
25 °C
-40 °C
1
1.5
2
2.5
3
3.5
4
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0.6
0.8
1
1.2
1.4
1.6
1.8
2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 241
8159E–AVR–02/2013
Figure 28-12. Idle Supply Current vs. VCC (Internal RC Oscillator, 2MHz)
Figure 28-13. Idle Supply Current vs. VCC (Internal RC Oscillator, 1MHz)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 242
8159E–AVR–02/2013
Figure 28-14. Idle Supply Current vs. VCC (32kHz External Oscillator)
28.3 Power-down Supply Current
Figure 28-15. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
25 °C
0
5
10
15
20
25
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 243
8159E–AVR–02/2013
Figure 28-16. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
28.4 Power-save Supply Current
Figure 28-17. Power-save Supply Current vs. VCC (Watchdog Timer Disabled)
85 °C
25 °C
-40 °C
0
5
10
15
20
25
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25 °C
2
4
6
8
10
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 244
8159E–AVR–02/2013
28.5 Standby Supply Current
Figure 28-18. Standby Supply Current vs. VCC (455kHz Resonator, Watchdog Timer Disabled)
Figure 28-19. Standby Supply Current vs. VCC (1MHz Resonator, Watchdog Timer Disabled)
25 °C
0
10
20
30
40
50
60
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25 °C
0
10
20
30
40
50
60
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 245
8159E–AVR–02/2013
Figure 28-20. Standby Supply Current vs. VCC (1MHz Xtal, Watchdog Timer Disabled)
Figure 28-21. Standby Supply Current vs. VCC (4MHz Resonator, Watchdog Timer Disabled)
25 °C
0
10
20
30
40
50
60
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25 °C
0
15
30
45
60
75
90
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 246
8159E–AVR–02/2013
Figure 28-22. Standby Supply Current vs. VCC (4MHz Xtal, Watchdog Timer Disabled)
Figure 28-23. Standby Supply Current vs. VCC (6MHz Resonator, Watchdog Timer Disabled)
25 °C
0
10
20
30
40
50
60
70
80
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25 °C
0
20
40
60
80
100
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 247
8159E–AVR–02/2013
Figure 28-24. Standby Supply Current vs. VCC (6MHz Xtal, Watchdog Timer Disabled)
28.6 Pin Pull-up
Figure 28-25. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
25 °C
0
20
40
60
80
100
120
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
0
20
40
60
80
100
120
140
0123456
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °CATmega8A [DATASHEET] 248
8159E–AVR–02/2013
Figure 28-26. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
Figure 28-27. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
70
80
0 0.5 1 1.5 2 2.5 3
VOP (V)
IOP (uA)
85 °C
25 °C
-40 °C
0
20
40
60
80
100
120
012345
VRESET (V)
IRESET (uA)ATmega8A [DATASHEET] 249
8159E–AVR–02/2013
Figure 28-28. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
28.7 Pin Driver Strength
Figure 28-29. I/O Pin Output Voltage vs. Source Current (VCC = 5.0V)
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
0 0.5 1 1.5 2 2.5 3
VRESET (V)
IRESET (uA)
85 °C
25 °C
-40 °C
4.3
4.4
4.5
4.6
4.7
4.8
4.9
5
0246 8 10 12 14 16 18 20
IOH (mA)
VOH (
V)ATmega8A [DATASHEET] 250
8159E–AVR–02/2013
Figure 28-30. I/O Pin Output Voltage vs. Source Current (VCC = 3.0V)
Figure 28-31. I/O Pin Output Voltage vs. Sink Current (VCC = 5.0V)
85 °C
25 °C
-40 °C
1
1.5
2
2.5
3
3.5
0 4 8 12 16 20
IOH (mA)
VOH (
V)
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0 4 8 12 16 20
IOL (mA)
VOL (
V)ATmega8A [DATASHEET] 251
8159E–AVR–02/2013
Figure 28-32. I/O Pin Output Voltage vs. Sink Current (VCC = 3.0V)
Figure 28-33. Reset Pin as I/O - Pin Source Current vs. Output Voltage (VCC = 5.0V)
85 °C
25 °C
-40 °C
0
0.2
0.4
0.6
0.8
1
0246 8 10 12 14 16 18 20
IOL (mA)
VOL (
V)
0
1
2
3
4
5
2 2.5 3 3.5 4 4.5
VOH (V)
Current (mA)
85 °C
25 °C
-40 °CATmega8A [DATASHEET] 252
8159E–AVR–02/2013
Figure 28-34. Reset Pin as I/O - Pin Source Current vs. Output Voltage (VCC = 2.7V)
Figure 28-35. Reset Pin as I/O - Pin Sink Current vs. Output Voltage (VCC = 5.0V)
0
0.5
1
1.5
2
2.5
3
3.5
4
0 0.5 1 1.5 2 2.5
VOH (V)
Current (mA)
85 °C
25 °C
-40 °C
85 °C
25 °C
-40 °C
0
2
4
6
8
10
12
14
0 0.5 1 1.5 2
VOL (V)
Current (mA)ATmega8A [DATASHEET] 253
8159E–AVR–02/2013
Figure 28-36. Reset Pin as I/O - Pin Sink Current vs. Output Voltage (VCC = 2.7V)
28.8 Pin Thresholds and Hysteresis
Figure 28-37. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin Read as “1”)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
0 0.5 1 1.5 2
VOL (V)
Current (mA)
85 °C
25 °C
-40 °C
1
1.5
2
2.5
3
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 254
8159E–AVR–02/2013
Figure 28-38. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
Figure 28-39. I/O Pin Input Hysteresis vs. VCC
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)
85 °C
25 °C
-40 °C
0.2
0.25
0.3
0.35
0.4
0.45
0.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (m
V)ATmega8A [DATASHEET] 255
8159E–AVR–02/2013
Figure 28-40. Reset Pin as I/O - Input Threshold Voltage vs. VCC (VIH, Reset Pin Read as “1”)
Figure 28-41. Reset Pin as I/O - Input Threshold Voltage vs. VCC (VIL, Reset Pin Read as “0”)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 256
8159E–AVR–02/2013
Figure 28-42. Reset Pin as I/O - Pin Hysteresis vs. VCC
Figure 28-43. Reset Input Threshold Voltage vs. VCC (VIH, Reset Pin Read as “1”)
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (m
V)
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 257
8159E–AVR–02/2013
Figure 28-44. Reset Input Threshold Voltage vs. VCC (VIL, Reset Pin Read as “0”)
Figure 28-45. Reset Input Pin Hysteresis vs. VCC
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (
V)
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (m
V)ATmega8A [DATASHEET] 258
8159E–AVR–02/2013
28.9 Bod Thresholds and Analog Comparator Offset
Figure 28-46. BOD Thresholds vs. Temperature (BOD Level is 4.0V)
Figure 28-47. BOD Thresholds vs. Temperature (BOD Level is 2.7v)
3.7
3.75
3.8
3.85
3.9
3.95
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Threshold (
V)
Rising Vcc
Falling Vcc
Temperature (°C)
2.5
2.55
2.6
2.65
2.7
2.75
2.8
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90
Temperature (°C)
Threshold (
V)
Rising Vcc
Falling VccATmega8A [DATASHEET] 259
8159E–AVR–02/2013
Figure 28-48. Bandgap Voltage vs. VCC
Figure 28-49. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 5V)
85 °C
25 °C
-40 °C
1.18
1.185
1.19
1.195
1.2
1.205
1.21
1.215
2.5 3 3.5 4 4.5 5 5.5
Vcc (V)
Bandgap
Voltage (
V) Comparator Offset Voltage (V)
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Common Mode Voltage (V)
85 °C
25 °C
-40 °C
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003ATmega8A [DATASHEET] 260
8159E–AVR–02/2013
Figure 28-50. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 2.8V)
28.10 Internal Oscillator Speed
Figure 28-51. Watchdog Oscillator Frequency vs. VCC
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0.25 0.50 0.75 1.00 1.25 1.5 1.75 2.00 2.25 2.75
Common Mode Voltage (V)
2.50
Comparator Offset Voltage (V)
85 °C
25 °C
-40 °C
85 °C
25 °C
-40 °C
925
950
975
1000
1025
1050
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (kHz)ATmega8A [DATASHEET] 261
8159E–AVR–02/2013
Figure 28-52. Calibrated 8MHz RC Oscillator Frequency vs. Temperature
Figure 28-53. Calibrated 8MHz RC Oscillator Frequency vs. VCC
5.5 V
4.0 V
2.7 V
6
6,5
7
7,5
8
8,5
-40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (MHz)
85 °C
25 °C
-40 °C
6
6.5
7
7.5
8
8.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)ATmega8A [DATASHEET] 262
8159E–AVR–02/2013
Figure 28-54. Calibrated 8MHz RC Oscillator Frequency vs. Osccal Value
Figure 28-55. Calibrated 4MHz RC Oscillator Frequency vs. Temperature
25 °C
2
4
6
8
10
12
14
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
FRC (MHz)
5.5 V
4.0 V
2.7 V
3.5
3.6
3.7
3.8
3.9
4
4.1
-40 -20 0 20 40 60 80 100
FRC (MHz)
Temperature (°C)ATmega8A [DATASHEET] 263
8159E–AVR–02/2013
Figure 28-56. Calibrated 4MHz RC Oscillator Frequency vs. VCC
Figure 28-57. Calibrated 4MHz RC Oscillator Frequency vs. Osccal Value
85 °C
25 °C
-40 °C
3.5
3.6
3.7
3.8
3.9
4
4.1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
25 °C
1
2
3
4
5
6
7
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
FRC (MHz)ATmega8A [DATASHEET] 264
8159E–AVR–02/2013
Figure 28-58. Calibrated 2MHz RC Oscillator Frequency vs. Temperature
Figure 28-59. Calibrated 2MHz RC Oscillator Frequency vs. VCC
5.5 V
4.0 V
2.7 V
1.75
1.8
1.85
1.9
1.95
2
2.05
2.1
-40 -20 0 20 40 60 80 100
FRC (MHz)
Temperature (°C)
85 °C
25 °C
-40 °C
1.8
1.85
1.9
1.95
2
2.05
2.1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)ATmega8A [DATASHEET] 265
8159E–AVR–02/2013
Figure 28-60. Calibrated 2MHz RC Oscillator Frequency vs. Osccal Value
Figure 28-61. Calibrated 1MHz RC Oscillator Frequency vs. Temperature
25 °C
0.5
1
1.5
2
2.5
3
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
FRC (MHz)
5.5 V
4.0 V
2.7 V
0.9
0.92
0.94
0.96
0.98
1
1.02
1.04
-40 -20 0 20 40 60 80 100
FRC (MHz)
Temperature (°C)ATmega8A [DATASHEET] 266
8159E–AVR–02/2013
Figure 28-62. Calibrated 1MHz RC Oscillator Frequency vs. VCC
Figure 28-63. Calibrated 1MHz RC Oscillator Frequency vs. Osccal Value
85 °C
25 °C
-40 °C
0,9
0.92
0.94
0.96
0.98
1
1.02
1.04
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
25 °C
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL VALUE
FRC (MHz)ATmega8A [DATASHEET] 267
8159E–AVR–02/2013
28.11 Current Consumption of Peripheral Units
Figure 28-64. Brown-out Detector Current vs. VCC
Figure 28-65. ADC Current vs. VCC (AREF = AVCC)
85 °C
25 °C
-40 °C
0
4
8
12
16
20
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
100
125
150
175
200
225
250
275
300
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 268
8159E–AVR–02/2013
Figure 28-66. AREF External Reference Current vs. VCC
Figure 28-67. 32kHz TOSC Current vs. VCC (Watchdog Timer Disabled)
85 °C
25 °C
-40 °C
40
60
80
100
120
140
160
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
2
4
6
8
10
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 269
8159E–AVR–02/2013
Figure 28-68. Watchdog Timer Current vs. VCC
Figure 28-69. Analog Comparator Current vs. VCC
85 °C
25 °C
-40 °C
0
4
8
12
16
20
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
70
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 270
8159E–AVR–02/2013
Figure 28-70. Programming Current vs. VCC
28.12 Current Consumption in Reset and Reset Pulsewidth
Figure 28-71. Reset Supply Current vs. VCC (0.1 - 1.0MHz, Excluding Current Through The Reset Pull-up)
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
0
0.5
1
1.5
2
2.5
3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)ATmega8A [DATASHEET] 271
8159E–AVR–02/2013
Figure 28-72. Reset Supply Current vs. VCC (1 - 16MHz, Excluding Current Through The Reset Pull-up)
Figure 28-73. Reset Pulse Width vs. VCC
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.3 V
2.7 V
0
2
4
6
8
10
12
0246 8 10 12 14 16
Frequency (MHz)
ICC (mA)
85 °C
25 °C
-40 °C
0
150
300
450
600
750
2,5 3 3,5 4 4,5 5 5,5
V CC (V)
Pulsewidth (ns)ATmega8A [DATASHEET] 272
8159E–AVR–02/2013
29. Typical Characteristics – TA = -40°C to 105°C
The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption
measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A
sine wave generator with rail-to-rail output is used as clock source.
All Active- and Idle current consumption measurements are done with all bits in the PRR registers set and thus, the
corresponding I/O modules are turned off. Also the Analog Comparator is disabled during these measurements.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating frequency, loading of
I/O pins, switching rate of I/O pins, code executed and ambient temperature. The dominating factors are operating
voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where CL = load capacitance,
VCC = operating voltage and f = average switching frequency of I/O pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to function properly at
frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down
mode with Watchdog Timer disabled represents the differential current drawn by the Watchdog Timer.
29.1 ATmega8A Typical Characteristics
29.1.1 Active Supply Current
Figure 29-1. Active Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
105 °C
85 °C
25 °C
-40 °C
2.5
3.5
4.5
5.5
6.5
7.5
8.5
9.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 273
8159E–AVR–02/2013
Figure 29-2. Active Supply Current vs. VCC (Internal RC Oscillator, 4 MHz)
Figure 29-3. Active Supply Current vs. VCC (Internal RC Oscillator, 2 MHz)
105 °C
85 °C
25 °C
-40 °C
1.5
2
2.5
3
3.5
4
4.5
5
5.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
105 °C
85 °C
25 °C
-40 °C
1
1.25
1.5
1.75
2
2.25
2.5
2.75
3
3.25
3.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 274
8159E–AVR–02/2013
Figure 29-4. Active Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
Figure 29-5. Active Supply Current vs. VCC (32 kHz External Oscillator)
105 °C
85 °C
25 °C
-40 °C
0.8
0.9
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
105 °C
85 °C
25 °C
-40 °C
35
38
41
44
47
50
53
56
59
62
65
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 275
8159E–AVR–02/2013
29.1.2 Idle Supply Current
Figure 29-6. Idle Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
Figure 29-7. Idle Supply Current vs. VCC (Internal RC Oscillator, 4 MHz)
105 °C
85 °C
25 °C
-40 °C
1.2
1.5
1.8
2.1
2.4
2.7
3
3.3
3.6
3.9
4.2
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
105 °C
85 °C
25 °C
-40 °C
0.7
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 276
8159E–AVR–02/2013
Figure 29-8. Idle Supply Current vs. VCC (Internal RC Oscillator, 2 MHz)
Figure 29-9. Idle Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
105 °C
85 °C
25 °C
-40 °C
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
105 °C
85 °C
25 °C
-40 °C
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)ATmega8A [DATASHEET] 277
8159E–AVR–02/2013
Figure 29-10. Idle Supply Current vs. VCC (32 kHz External RC Oscillator)
29.1.3 Power-down Supply Current
Figure 29-11. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
105 °C
85 °C
25 °C
-40 °C
6.5
8.5
10.5
12.5
14.5
16.5
18.5
20.5
22.5
24.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)
105 °C
85 °C
25 °C
-40 °C
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 278
8159E–AVR–02/2013
Figure 29-12. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
29.1.4 Power-save Supply Current
Figure 29-13. Power-save Supply Current vs. VCC (Watchdog Timer Disabled)
105 °C
85 °C
25 °C
-40 °C
3
6
9
12
15
18
21
24
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)
105 °C
85 °C
25 °C
-40 °C
4
5
6
7
8
9
10
11
12
13
14
15
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 279
8159E–AVR–02/2013
29.1.5 Standby Supply Current
Figure 29-14. Standby Supply Current vs. VCC (32 kHz External RC Oscillator)
29.1.6 Pin Pull-up
Figure 29-15. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
105 °C
85 °C
25 °C
-40 °C
7
9
11
13
15
17
19
21
23
25
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)
0
20
40
60
80
100
120
140
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VOP (V)
IOP (uA)
105 °C
85 °C
25 °C
-40 °CATmega8A [DATASHEET] 280
8159E–AVR–02/2013
Figure 29-16. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
Figure 29-17. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
105 °C
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
70
80
0 0.3 0.6 0.9 1.2 1.5 1.8 2.1 2.4 2.7
VOP (V)
IOP (uA)
0
10
20
30
40
50
60
70
80
90
100
110
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
VRESET (V)
IRESET (uA)
105 °C
85 °C
25 °C
-40 °CATmega8A [DATASHEET] 281
8159E–AVR–02/2013
Figure 29-18. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
29.1.7 Pin Driver Strength
Figure 29-19. I/O Pin Output Voltage vs. Source Current (VCC = 5V)
105 °C
85 °C
25 °C
-40 °C
0
10
20
30
40
50
60
0 0.3 0.6 0.9 1.2 1.5 1.8 2.1 2.4 2.7
VRESET (V)
IRESET (uA)
105 °C
85 °C
25 °C
-40 °C
4.3
4.4
4.5
4.6
4.7
4.8
4.9
5
5.1
0246 8 10 12 14 16 18 20
IOH (mA)
VOH (
V)ATmega8A [DATASHEET] 282
8159E–AVR–02/2013
Figure 29-20. I/O Pin Output Voltage vs. Source Current (VCC = 3V)
Figure 29-21. I/O Pin Output Voltage vs. Sink Current (VCC = 5V)
1.7
1.9
2.1
2.3
2.5
2.7
2.9
3.1
0246 8 10 12 14 16 18 20
IOH (mA)
VOH (
V)
105 °C
85 °C
25 °C
-40 °C
105 °C
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0246 8 10 12 14 16 18 20
IOL (mA)
VOL (
V)ATmega8A [DATASHEET] 283
8159E–AVR–02/2013
Figure 29-22. I/O Pin Output Voltage vs. Sink Current (VCC = 3V)
29.1.8 Pin Threshold and Hysteresis
Figure 29-23. I/O Pin Input Threshold vs. VCC (VIH , I/O Pin Read as ‘1’)
105 °C
85 °C
25 °C
-40 °C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0246 8 10 12 14 16 18 20
IOL(mA)
VOL (
V)
105 °C
85 °C
25 °C
-40 °C
1.2
1.4
1.6
1.8
2
2.2
2.4
2.6
2.8
3
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 284
8159E–AVR–02/2013
Figure 29-24. I/O Pin Input Threshold vs. VCC (VIL, I/O Pin Read as ‘0’)
Figure 29-25. I/O Pin Input Hysteresis vs. VCC
105 °C
85 °C
25 °C
-40 °C
1
1.3
1.6
1.9
2.2
2.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)
105 °C
85 °C
25 °C
-40 °C
0.25
0.3
0.35
0.4
0.45
0.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Input Hysteresis (m
V)ATmega8A [DATASHEET] 285
8159E–AVR–02/2013
Figure 29-26. Reset Pin as I/O - Input Threshold vs. VCC (VIH , I/O Pin Read as ‘1’)
Figure 29-27. Reset Pin as I/O - Input Threshold vs. VCC (VIL, I/O Pin Read as ‘0’)
105 °C
85 °C
25 °C
-40 °C
1.3
1.6
1.9
2.2
2.5
2.8
3.1
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)
105 °C
85 °C
25 °C
-40 °C
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.3
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 286
8159E–AVR–02/2013
Figure 29-28. Reset Pin as I/O - Pin Hysteresis vs. VCC
Figure 29-29. Reset Input Threshold vs. VCC (VIH , Reset Pin Read as ‘1’)
105 °C
85 °C
25 °C
-40 °C
0.4
0.45
0.5
0.55
0.6
0.65
0.7
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Input Hysteresis (m
V)
105 °C
85 °C
25 °C
-40 °C
0.9
1.1
1.3
1.5
1.7
1.9
2.1
2.3
2.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)ATmega8A [DATASHEET] 287
8159E–AVR–02/2013
Figure 29-30. Reset Input Threshold vs. VCC (VIL, Reset Pin Read as ‘0’)
Figure 29-31. Reset Pin Input Hysteresis vs. VCC
105 °C
85 °C
25 °C
-40 °C
1
1.2
1.4
1.6
1.8
2
2.2
2.4
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Threshold (
V)
105 °C
85 °C
25 °C
-40 °C
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Input Hysteresis (m
V)ATmega8A [DATASHEET] 288
8159E–AVR–02/2013
29.1.9 BOD Threshold
Figure 29-32. BOD Threshold vs. Temperature (VCC = 4.3V)
Figure 29-33. BOD Threshold vs. Temperature (VCC = 2.7V)
Rising Vcc
Falling Vcc
3.8
3.82
3.84
3.86
3.88
3.9
3.92
3.94
3.96
3.98
4
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
Threshold (
V)
Rising Vcc
Falling Vcc
2.47
2.49
2.51
2.53
2.55
2.57
2.59
2.61
2.63
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
Threshold (
V)ATmega8A [DATASHEET] 289
8159E–AVR–02/2013
Figure 29-34. Bandgap Voltage vs. Temperature
Figure 29-35. Bandgap Voltage vs. VCC
5.5V
5.0V
4.0V
3.3V
2.7V
1.8V
1.175
1.18
1.185
1.19
1.195
1.2
1.205
1.21
1.215
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
Bandgap
Voltage (
V)
105 °C
85 °C
25 °C
-40 °C
1.175
1.18
1.185
1.19
1.195
1.2
1.205
1.21
1.215
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Bandgap
Voltage (
V)ATmega8A [DATASHEET] 290
8159E–AVR–02/2013
29.1.10 Internal Oscillator Speed
Figure 29-36. Watchdog Oscillator Frequency vs. VCC
Figure 29-37. Watchdog Oscillator Frequency vs. Temperature
105 °C
85 °C
25 °C
-40 °C
980
1000
1020
1040
1060
1080
1100
1120
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
FRC (kHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
2.7 V
970
990
1010
1030
1050
1070
1090
1110
1130
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
FRC (kHz)ATmega8A [DATASHEET] 291
8159E–AVR–02/2013
Figure 29-38. Calibrated 8 MHz RC Oscillator vs. Temperature
Figure 29-39. Calibrated 8 MHz RC Oscillator vs. VCC
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.0 V
2.7 V
6.6
6.8
7
7.2
7.4
7.6
7.8
8
8.2
8.4
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
FRC (MHz)
105 °C
85 °C
25 °C
-40 °C
6.6
6.8
7
7.2
7.4
7.6
7.8
8
8.2
8.4
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
FRC (MHz)ATmega8A [DATASHEET] 292
8159E–AVR–02/2013
Figure 29-40. Calibrated 8 MHz RC Oscillator vs. OSCCAL Value
Figure 29-41. Calibrated 4 MHz RC Oscillator vs. Temperature
105 °C
85 °C
25 °C
-40 °C
2
4
6
8
10
12
14
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
FRC (MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.0 V
2.7 V
3.55
3.65
3.75
3.85
3.95
4.05
4.15
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
FRC (MHz)ATmega8A [DATASHEET] 293
8159E–AVR–02/2013
Figure 29-42. Calibrated 4 MHz RC Oscillator vs. VCC
Figure 29-43. Calibrated 4 MHz RC Oscillator vs. OSCCAL Value
105 °C
85 °C
25 °C
-40 °C
3.6
3.65
3.7
3.75
3.8
3.85
3.9
3.95
4
4.05
4.1
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
FRC (MHz)
105 °C
85 °C
25 °C
-40 °C
1
2
3
4
5
6
7
8
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
FRC (MHz)ATmega8A [DATASHEET] 294
8159E–AVR–02/2013
Figure 29-44. Calibrated 2 MHz RC Oscillator vs. Temperature
Figure 29-45. Calibrated 2 MHz RC Oscillator vs. VCC
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.0 V
2.7 V
1.78
1.81
1.84
1.87
1.9
1.93
1.96
1.99
2.02
2.05
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
FRC (MHz)
105 °C
85 °C
25 °C
-40 °C
1.8
1.83
1.86
1.89
1.92
1.95
1.98
2.01
2.04
2.07
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
FRC (MHz)ATmega8A [DATASHEET] 295
8159E–AVR–02/2013
Figure 29-46. Calibrated 2 MHz RC Oscillator vs. OSCCAL Value
Figure 29-47. Calibrated 1 MHz RC Oscillator vs. Temperature
105 °C
85 °C
25 °C
-40 °C
0.8
1.1
1.4
1.7
2
2.3
2.6
2.9
3.2
3.5
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
FRC (MHz)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
3.0 V
2.7 V
0.91
0.93
0.95
0.97
0.99
1.01
1.03
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110
Temperature (°C)
FRC (MHz)ATmega8A [DATASHEET] 296
8159E–AVR–02/2013
Figure 29-48. Calibrated 1 MHz RC Oscillator vs. VCC
Figure 29-49. Calibrated 1 MHz RC Oscillator vs. OSCCAL Value
105 °C
85 °C
25 °C
-40 °C
0.9
0.92
0.94
0.96
0.98
1
1.02
1.04
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
FRC (MHz)
105 °C
85 °C
25 °C
-40 °C
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256
OSCCAL (X1)
FRC (MHz)ATmega8A [DATASHEET] 297
8159E–AVR–02/2013
29.1.11 Current Consumption of Peripheral Units
Figure 29-50. Brown-out Detector Current vs. VCC
Figure 29-51. ADC Current vs. VCC (AREF = AVCC)
105 °C
85 °C
25 °C
-40 °C
8
9
10
11
12
13
14
15
16
17
18
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)
105 °C
85 °C
25 °C
-40 °C
140
160
180
200
220
240
260
280
300
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)ATmega8A [DATASHEET] 298
8159E–AVR–02/2013
Figure 29-52. Watchdog Timer Current vs. VCC
Figure 29-53. Analog Comparator Current vs. VCC
4
6
8
10
12
14
16
18
20
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (uA)
105 °C
85 °C
25 °C
-40 °C
32
36
40
44
48
52
56
60
64
68
72
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
105 °C
85 °C
25 °C
-40 °CATmega8A [DATASHEET] 299
8159E–AVR–02/2013
Figure 29-54. Programming Current vs. VCC
29.1.12 Current Consumption in Reset and Reset Pulsewidth
Figure 29-55. Reset Supply Current vs. Vcc (0.1 - 1.0 MHz, Excluding Current Through the Reset Pull-up)
105 °C
85 °C
25 °C
-40 °C
0
1
2
3
4
5
6
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
ICC (mA)
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
2.7 V
0
0.5
1
1.5
2
2.5
3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)ATmega8A [DATASHEET] 300
8159E–AVR–02/2013
Figure 29-56. Reset Supply Current vs. Vcc (1 - 16 MHz, Excluding Current Through the Reset Pull-up)
Figure 29-57. Minimum Reset Pulsewidth vs. Vcc
5.5 V
5.0 V
4.5 V
4.0 V
3.6 V
2.7 V
0
2
4
6
8
10
12
0246 8 10 12 14 16
Frequency (MHz)
ICC (mA)
105 °C
85 °C
25 °C
-40 °C
100
200
300
400
500
600
700
800
2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5
VCC (V)
Pulse
width (ns)ATmega8A [DATASHEET] 301
8159E–AVR–02/2013
30. Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x3F (0x5F) SREG I T H S V N Z C 8
0x3E (0x5E) SPH – – – – – SP10 SP9 SP8 10
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 10
0x3C (0x5C) Reserved
0x3B (0x5B) GICR INT1 INT0 – – – – IVSEL IVCE 47, 65
0x3A (0x5A) GIFR INTF1 INTF0 – – – – – – 65
0x39 (0x59) TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 69, 97, 115
0x38 (0x58) TIFR OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 70, 97, 97
0x37 (0x57) SPMCR SPMIE RWWSB – RWWSRE BLBSET PGWRT PGERS SPMEN 205
0x36 (0x56) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 176
0x35 (0x55) MCUCR SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00 35, 64
0x34 (0x54) MCUCSR – – – – WDRF BORF EXTRF PORF 42
0x33 (0x53) TCCR0 – – – – – CS02 CS01 CS00 69
0x32 (0x52) TCNT0 Timer/Counter0 (8 Bits) 69
0x31 (0x51) OSCCAL Oscillator Calibration Register 31
0x30 (0x50) SFIOR – – – – ACME PUD PSR2 PSR10 55, 72, 115, 180
0x2F (0x4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 92
0x2E (0x4E) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 95
0x2D (0x4D) TCNT1H Timer/Counter1 – Counter Register High byte 96
0x2C (0x4C) TCNT1L Timer/Counter1 – Counter Register Low byte 96
0x2B (0x4B) OCR1AH Timer/Counter1 – Output Compare Register A High byte 96
0x2A (0x4A) OCR1AL Timer/Counter1 – Output Compare Register A Low byte 96
0x29 (0x49) OCR1BH Timer/Counter1 – Output Compare Register B High byte 96
0x28 (0x48) OCR1BL Timer/Counter1 – Output Compare Register B Low byte 96
0x27 (0x47) ICR1H Timer/Counter1 – Input Capture Register High byte 96
0x26 (0x46) ICR1L Timer/Counter1 – Input Capture Register Low byte 96
0x25 (0x45) TCCR2 FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20 112
0x24 (0x44) TCNT2 Timer/Counter2 (8 Bits) 113
0x23 (0x43) OCR2 Timer/Counter2 Output Compare Register 114
0x22 (0x42) ASSR – – – – AS2 TCN2UB OCR2UB TCR2UB 114
0x21 (0x41) WDTCR – – – WDCE WDE WDP2 WDP1 WDP0 42
0x20(1) (0x40)(1) UBRRH URSEL – – – UBRR[11:8] 147
UCSRC URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL 145
0x1F (0x3F) EEARH – – – – – – – EEAR8 18
0x1E (0x3E) EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 18
0x1D (0x3D) EEDR EEPROM Data Register 18
0x1C (0x3C) EECR – – – – EERIE EEMWE EEWE EERE 18
0x1B (0x3B) Reserved
0x1A (0x3A) Reserved
0x19 (0x39) Reserved
0x18 (0x38) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 62
0x17 (0x37) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 62
0x16 (0x36) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 63
0x15 (0x35) PORTC – PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 63
0x14 (0x34) DDRC – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 63
0x13 (0x33) PINC – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 63
0x12 (0x32) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 63
0x11 (0x31) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 63
0x10 (0x30) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 63
0x0F (0x2F) SPDR SPI Data Register 124
0x0E (0x2E) SPSR SPIF WCOL – – – – – SPI2X 124
0x0D (0x2D) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 123
0x0C (0x2C) UDR USART I/O Data Register 143
0x0B (0x2B) UCSRA RXC TXC UDRE FE DOR PE U2X MPCM 144
0x0A (0x2A) UCSRB RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 145
0x09 (0x29) UBRRL USART Baud Rate Register Low byte 147
0x08 (0x28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 180
0x07 (0x27) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 190
0x06 (0x26) ADCSRA ADEN ADSC ADFR ADIF ADIE ADPS2 ADPS1 ADPS0 191
0x05 (0x25) ADCH ADC Data Register High byte 193
0x04 (0x24) ADCL ADC Data Register Low byte 193
0x03 (0x23) TWDR Two-wire Serial Interface Data Register 178
0x02 (0x22) TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE 178
0x01 (0x21) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 177
0x00 (0x20) TWBR Two-wire Serial Interface Bit Rate Register 176ATmega8A [DATASHEET] 302
8159E–AVR–02/2013
Note: 1. Refer to the USART description for details on how to access UBRRH and UCSRC.
2. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on
all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions
work with registers 0x00 to 0x1F only.ATmega8A [DATASHEET] 303
8159E–AVR–02/2013
31. Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd Rd Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd Rd K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z,N,V 1
COM Rd One’s Complement Rd 0xFF Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd 0x00 Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd Rd (0xFF - K) Z,N,V 1
INC Rd Increment Rd Rd + 1 Z,N,V 1
DEC Rd Decrement Rd Rd 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd Rd Rd Z,N,V 1
CLR Rd Clear Register Rd Rd Rd Z,N,V 1
SER Rd Set Register Rd 0xFF None 1
MUL Rd, Rr Multiply Unsigned R1:R0 Rd x Rr Z,C 2
MULS Rd, Rr Multiply Signed R1:R0 Rd x Rr Z,C 2
MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 Rd x Rr Z,C 2
FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 (Rd x Rr) << 1 Z,C 2
FMULS Rd, Rr Fractional Multiply Signed R1:R0 (Rd x Rr) << 1 Z,C 2
FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 (Rd x Rr) << 1 Z,C 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC Z None 2
RCALL k Relative Subroutine Call PC PC + k + 1 None 3
ICALL Indirect Call to (Z) PC Z None 3
RET Subroutine Return PC STACK None 4
RETI Interrupt Return PC STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1 / 2 / 3
CP Rd,Rr Compare Rd Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd Rr C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1 / 2 / 3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1 / 2 / 3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1 / 2 / 3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1 / 2 / 3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1 / 2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 None 1 / 2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1 / 2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1 / 2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1 / 2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1 / 2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1 / 2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1 / 2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1 / 2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1 / 2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1 / 2
BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1 / 2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1 / 2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1 / 2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1 / 2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1 / 2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1 / 2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1 / 2
Mnemonics Operands Description Operation Flags #Clocks
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1 / 2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1 / 2ATmega8A [DATASHEET] 304
8159E–AVR–02/2013
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd K None 1
LD Rd, X Load Indirect Rd (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2
LD Rd, Y Load Indirect Rd (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2
LD Rd, Z Load Indirect Rd (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd (k) None 2
ST X, Rr Store Indirect (X) Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) Rr, X X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2
ST Y, Rr Store Indirect (Y) Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) Rr, Y Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) Rr None 2
ST Z, Rr Store Indirect (Z) Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2
STS k, Rr Store Direct to SRAM (k) Rr None 2
LPM Load Program Memory R0 (Z) None 3
LPM Rd, Z Load Program Memory Rd (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd (Z), Z Z+1 None 3
SPM Store Program Memory (Z) R1:R0 None -
IN Rd, P In Port Rd P None 1
OUT P, Rr Out Port P Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 2
POP Rd Pop Register from Stack Rd STACK None 2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) 0 None 2
LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z,C,N,V 1
ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0:6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3:0)Rd(7:4),Rd(7:4)Rd(3:0) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) T None 1
SEC Set Carry C 1 C1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1 N1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1 Z1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1 I1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1 S1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Twos Complement Overflow. V 1 V1
CLV Clear Twos Complement Overflow V 0 V 1
SET Set T in SREG T 1 T1
Mnemonics Operands Description Operation Flags #Clocks
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1 H1
CLH Clear Half Carry Flag in SREG H 0 H 1
MCU CONTROL INSTRUCTIONS
31. Instruction Set Summary (Continued)ATmega8A [DATASHEET] 305
8159E–AVR–02/2013
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
31. Instruction Set Summary (Continued)ATmega8A [DATASHEET] 306
8159E–AVR–02/2013
32. Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. Tape & Reel
4. See characterization specifications at 105C
Speed (MHz) Power Supply (V) Ordering Code(2) Package(1) Operation Range
16 2.7 - 5.5
ATmega8A-AU
ATmega8A-AUR(3)
ATmega8A-PU
ATmega8A-MU
ATmega8A-MUR(3)
32A
32A
28P3
32M1-A
32M1-A
Industrial
(-40C to 85C)
ATmega8A-AN
ATmega8A-ANR(3)
ATmega8A-PN
ATmega8A-MN
ATmega8A-MNR(3)
32A
32A
28P3
32M1-A
32M1-A
Extended
(-40C to 105C)(4)
Package Type
32A 32-lead, Thin (1.0mm) Plastic Quad Flat Package (TQFP)
28P3 28-lead, 0.300” Wide, Plastic Dual Inline Package (PDIP)
32M1-A 32-pad, 5 x 5 x 1.0 body, Lead Pitch 0.50 mm Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)ATmega8A [DATASHEET] 307
8159E–AVR–02/2013
33. Packaging Information
33.1 32A
TITLE DRAWING NO. REV.
32A, 32-lead, 7 x 7mm body size, 1.0mm body thickness,
0.8mm lead pitch, thin profile plastic quad flat package (TQFP) 32A C
2010-10-20
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
e E1 E
B
Notes:
1. This package conforms to JEDEC reference MS-026, Variation ABA.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.10mm maximum.
A – – 1.20
A1 0.05 – 0.15
A2 0.95 1.00 1.05
D 8.75 9.00 9.25
D1 6.90 7.00 7.10 Note 2
E 8.75 9.00 9.25
E1 6.90 7.00 7.10 Note 2
B 0.30 – 0.45
C 0.09 – 0.20
L 0.45 – 0.75
e 0.80 TYP
COMMON DIMENSIONS
(Unit of measure = mm)
SYMBOL MIN NOM MAX NOTEATmega8A [DATASHEET] 308
8159E–AVR–02/2013
33.2 28P3
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
28P3, 28-lead (0.300"/7.62mm Wide) Plastic Dual
Inline Package (PDIP) 28P3 B
09/28/01
PIN
1
E1
A1
B
REF
E
B1
C
L
SEATING PLANE
A
0º ~ 15º
D
e
eB
B2
(4 PLACES)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A – – 4.5724
A1 0.508 – –
D 34.544 – 34.798 Note 1
E 7.620 – 8.255
E1 7.112 – 7.493 Note 1
B 0.381 – 0.533
B1 1.143 – 1.397
B2 0.762 – 1.143
L 3.175 – 3.429
C 0.203 – 0.356
eB – – 10.160
e 2.540 TYP
Note: 1. Dimensions D and E1 do not include mold Flash or Protrusion.
Mold Flash or Protrusion shall not exceed 0.25mm (0.010"). ATmega8A [DATASHEET] 309
8159E–AVR–02/2013
32M1-A
34. Errata
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
32M1-A, 32-pad, 5 x 5 x 1.0mm Body, Lead Pitch 0.50mm, 32M1-A E
5/25/06
3.10mm Exposed Pad, Micro Lead Frame Package (MLF)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D1
D
E1 E
b e
A3
A2
A1
A
D2
E2
0.08 C
L
1
2
3
P
P
0
1
2
3
A 0.80 0.90 1.00
A1 – 0.02 0.05
A2 – 0.65 1.00
A3 0.20 REF
b 0.18 0.23 0.30
D
D1
D2 2.95 3.10 3.25
4.90 5.00 5.10
4.70 4.75 4.80
4.70 4.75 4.80
4.90 5.00 5.10
E
E1
E2 2.95 3.10 3.25
e 0.50 BSC
L 0.30 0.40 0.50
P – – 0.60
– – 12o
Note: JEDEC Standard MO-220, Fig. 2 (Anvil Singulation), VHHD-2.
TOP VIEW
SIDE VIEW
BOTTOM VIEW
0
Pin 1 ID
Pin #1 Notch
(0.20 R)
K 0.20 – –
K
KATmega8A [DATASHEET] 310
8159E–AVR–02/2013
The revision letter in this section refers to the revision of the ATmega8A device.
34.1 ATmega8A, rev. L
• First Analog Comparator conversion may be delayed
• Interrupts may be lost when writing the timer registers in the asynchronous timer
• Signature may be Erased in Serial Programming Mode
• CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32kHz Oscillator is Used to Clock the
Asynchronous Timer/Counter2
• Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt request
1. First Analog Comparator conversion may be delayed
If the device is powered by a slow rising VCC, the first Analog Comparator conversion will take longer than
expected on some devices.
Problem Fix / Workaround
When the device has been powered or reset, disable then enable theAnalog Comparator before the first
conversion.
2. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronous timer clock is written when the asynchronous
Timer/Counter register (TCNTx) is 0x00.
Problem Fix / Workaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor 0x00 before writing
to the asynchronous Timer Control Register (TCCRx), asynchronous Timer Counter Register (TCNTx), or
asynchronous Output Compare Register (OCRx).
3. Signature may be Erased in Serial Programming Mode
If the signature bytes are read before a chiperase command is completed, the signature may be erased causing
the device ID and calibration bytes to disappear. This is critical, especially, if the part is running on internal
RC oscillator.
Problem Fix / Workaround:
Ensure that the chiperase command has exceeded before applying the next command.
4. CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32kHz Oscillator is Used to
Clock the Asynchronous Timer/Counter2
When the internal RC Oscillator is used as the main clock source, it is possible to run the Timer/Counter2
asynchronously by connecting a 32kHz Oscillator between XTAL1/TOSC1 and XTAL2/TOSC2. But when the
internal RC Oscillator is selected as the main clock source, the CKOPT Fuse does not control the internal
capacitors on XTAL1/TOSC1 and XTAL2/TOSC2. As long as there are no capacitors connected to
XTAL1/TOSC1 and XTAL2/TOSC2, safe operation of the Oscillator is not guaranteed.
Problem Fix / Workaround
Use external capacitors in the range of 20 - 36 pF on XTAL1/TOSC1 and XTAL2/TOSC2. This will be fixed in
ATmega8A Rev. G where the CKOPT Fuse will control internal capacitors also when internal RC Oscillator is
selected as main clock source. For ATmega8A Rev. G, CKOPT = 0 (programmed) will enable the internal
capacitors on XTAL1 and XTAL2. Customers who want compatibility between Rev. G and older revisions,
must ensure that CKOPT is unprogrammed (CKOPT = 1).ATmega8A [DATASHEET] 311
8159E–AVR–02/2013
5. Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt request.
Reading EEPROM by using the ST or STS command to set the EERE bit in the EECR register triggers an
unexpected EEPROM interrupt request.
Problem Fix / Workaround
Always use OUT or SBI to set EERE in EECR.ATmega8A [DATASHEET] 312
8159E–AVR–02/2013
35. Datasheet Revision History
Please note that the referring page numbers in this section are referred to this document. The referring revision in
this section refers to the document revision.
35.1 Rev.8159E – 02/2013
35.2 Rev.8159D – 02/11
35.3 Rev.8159C – 07/09
35.4 Rev.8159B – 05/09
1. Applied the Atmel new page layout for datasheets including new logo and last page.
2. Removed the reference to the debuggers and In-Circuit Emulators.
3. Added “Capacitive touch sensing” on page 6.
4. Added “Electrical Characteristics – TA = -40°C to 105°C” on page 233.
5. Added “Typical Characteristics – TA = -40°C to 105°C” on page 272.
1. Updated the datasheet according to the Atmel new Brand Style Guide.
2. Updated “Performing Page Erase by SPM” on page 200 by adding an extra note.
3. Updated “Ordering Information” on page 306 to include Tape & Reel.
1. Updated “Errata” on page 309.
1. Updated “System and Reset Characteristics” on page 228 with new BODLEVEL values
2. Updated “ADC Characteristics” on page 232 with new VINT values.
3. Updated “Typical Characteristics – TA = -40°C to 85°C” view.
4. Updated “Errata” on page 309. ATmega8A, rev L.
5. Created a new Table Of Contents.ATmega8A [DATASHEET] 313
8159E–AVR–02/2013
35.5 Rev.8159A – 08/08
1. Initial revision (Based on the ATmega8/L datasheet 2486T-AVR-05/08)
2. Changes done compared to ATmega8/L datasheet 2486T-AVR-05/08:
– All Electrical Characteristics are moved to “Electrical Characteristics – TA =
-40°C to 85°C” on page 225.
– Updated “DC Characteristics” on page 225 with new VOL Max (0.9V and
0.6V) and typical value for ICC.
– Added “Speed Grades” on page 227.
– Added a new sub section “System and Reset Characteristics” on page 228.
– Updated “System and Reset Characteristics” on page 228 with new VBOT
BODLEVEL = 0 (3.6V, 4.0V and 4.2V).
– Register descriptions are moved to sub section at the end of each chapter.
– New graphics in “Typical Characteristics – TA = -40°C to 85°C” on page
235.
– New “Ordering Information” on page 306.Enter Title of Manual [DATASHEET] i
8159E–AVR–02/2013
Table of Contents
Features .....................................................................................................1
1 Pin Configurations ...................................................................................2
2 Overview ...................................................................................................3
2.1 Block Diagram ...................................................................................................3
2.2 Pin Descriptions .................................................................................................4
3 Resources .................................................................................................6
4 Data Retention ..........................................................................................6
5 About Code Examples .............................................................................6
6 Capacitive touch sensing ........................................................................6
7 AVR CPU Core ..........................................................................................7
7.1 Overview ............................................................................................................7
7.2 Arithmetic Logic Unit – ALU ...............................................................................8
7.3 Status Register ..................................................................................................8
7.4 General Purpose Register File ..........................................................................9
7.5 Stack Pointer ...................................................................................................10
7.6 Instruction Execution Timing ...........................................................................11
7.7 Reset and Interrupt Handling ...........................................................................12
8 AVR Memories ........................................................................................15
8.1 Overview ..........................................................................................................15
8.2 In-System Reprogrammable Flash Program Memory .....................................15
8.3 SRAM Data Memory ........................................................................................16
8.4 EEPROM Data Memory ..................................................................................17
8.5 I/O Memory ......................................................................................................17
8.6 Register Description ........................................................................................18
9 System Clock and Clock Options .........................................................24
9.1 Clock Systems and their Distribution ...............................................................24
9.2 Clock Sources .................................................................................................25
9.3 Crystal Oscillator .............................................................................................25
9.4 Low-frequency Crystal Oscillator .....................................................................27
9.5 External RC Oscillator .....................................................................................27
9.6 Calibrated Internal RC Oscillator .....................................................................29
9.7 External Clock .................................................................................................30Enter Title of Manual [DATASHEET] ii
8159E–AVR–02/2013
9.8 Timer/Counter Oscillator ..................................................................................30
9.9 Register Description ........................................................................................31
10 Power Management and Sleep Modes .................................................32
10.1 Sleep Modes ....................................................................................................32
10.2 Idle Mode .........................................................................................................32
10.3 ADC Noise Reduction Mode ............................................................................33
10.4 Power-down Mode ...........................................................................................33
10.5 Power-save Mode ............................................................................................33
10.6 Standby Mode .................................................................................................34
10.7 Minimizing Power Consumption ......................................................................34
10.8 Register Description ........................................................................................35
11 System Control and Reset .....................................................................36
11.1 Resetting the AVR ...........................................................................................36
11.2 Reset Sources .................................................................................................36
11.3 Internal Voltage Reference ..............................................................................39
11.4 Watchdog Timer ..............................................................................................40
11.5 Timed Sequences for Changing the Configuration of the Watchdog Timer ....40
11.6 Register Description ........................................................................................42
12 Interrupts .................................................................................................44
12.1 Interrupt Vectors in ATmega8A .......................................................................44
12.2 Register Description ........................................................................................47
13 I/O Ports ..................................................................................................49
13.1 Overview ..........................................................................................................49
13.2 Ports as General Digital I/O .............................................................................50
13.3 Alternate Port Functions ..................................................................................54
13.4 Register Description ........................................................................................62
14 External Interrupts .................................................................................64
14.1 Register Description ........................................................................................64
15 8-bit Timer/Counter0 ..............................................................................66
15.1 Features ..........................................................................................................66
15.2 Overview ..........................................................................................................66
15.3 Timer/Counter Clock Sources .........................................................................67
15.4 Counter Unit ....................................................................................................67
15.5 Operation .........................................................................................................67
15.6 Timer/Counter Timing Diagrams ......................................................................68Enter Title of Manual [DATASHEET] iii
8159E–AVR–02/2013
15.7 Register Description ........................................................................................69
16 Timer/Counter0 and Timer/Counter1 Prescalers .................................71
16.1 Overview ..........................................................................................................71
16.2 Internal Clock Source ......................................................................................71
16.3 Prescaler Reset ...............................................................................................71
16.4 External Clock Source .....................................................................................71
16.5 Register Description ........................................................................................72
17 16-bit Timer/Counter1 ............................................................................73
17.1 Features ..........................................................................................................73
17.2 Overview ..........................................................................................................73
17.3 Accessing 16-bit Registers ..............................................................................75
17.4 Timer/Counter Clock Sources .........................................................................78
17.5 Counter Unit ....................................................................................................78
17.6 Input Capture Unit ...........................................................................................79
17.7 Output Compare Units .....................................................................................81
17.8 Compare Match Output Unit ............................................................................83
17.9 Modes of Operation .........................................................................................84
17.10 Timer/Counter Timing Diagrams ......................................................................91
17.11 Register Description ........................................................................................92
18 8-bit Timer/Counter2 with PWM and Asynchronous Operation .........99
18.1 Features ..........................................................................................................99
18.2 Overview ..........................................................................................................99
18.3 Timer/Counter Clock Sources .......................................................................100
18.4 Counter Unit ..................................................................................................100
18.5 Output Compare Unit .....................................................................................101
18.6 Compare Match Output Unit ..........................................................................103
18.7 Modes of Operation .......................................................................................104
18.8 Timer/Counter Timing Diagrams ....................................................................108
18.9 Asynchronous Operation of the Timer/Counter .............................................109
18.10 Timer/Counter Prescaler ...............................................................................111
18.11 Register Description ......................................................................................112
19 Serial Peripheral Interface – SPI .........................................................116
19.1 Features ........................................................................................................116
19.2 Overview ........................................................................................................116
19.3 SS Pin Functionality ......................................................................................121Enter Title of Manual [DATASHEET] iv
8159E–AVR–02/2013
19.4 Data Modes ...................................................................................................121
19.5 Register Description ......................................................................................123
20 USART ...................................................................................................125
20.1 Features ........................................................................................................125
20.2 Overview ........................................................................................................125
20.3 Clock Generation ...........................................................................................127
20.4 Frame Formats ..............................................................................................129
20.5 USART Initialization .......................................................................................130
20.6 Data Transmission – The USART Transmitter ..............................................131
20.7 Asynchronous Data Reception ......................................................................138
20.8 Multi-processor Communication Mode ..........................................................141
20.9 Accessing UBRRH/UCSRC Registers ...........................................................142
20.10 Register Description ......................................................................................143
20.11 Examples of Baud Rate Setting .....................................................................147
21 Two-wire Serial Interface .....................................................................152
21.1 Features ........................................................................................................152
21.2 Overview ........................................................................................................152
21.3 Two-wire Serial Interface Bus Definition ........................................................154
21.4 Data Transfer and Frame Format ..................................................................155
21.5 Multi-master Bus Systems, Arbitration and Synchronization .........................157
21.6 Using the TWI ................................................................................................159
21.7 Multi-master Systems and Arbitration ............................................................174
21.8 Register Description ......................................................................................176
22 Analog Comparator ..............................................................................179
22.1 Overview ........................................................................................................179
22.2 Analog Comparator Multiplexed Input ...........................................................179
22.3 Register Description ......................................................................................180
23 Analog-to-Digital Converter ................................................................182
23.1 Features ........................................................................................................182
23.2 Overview ........................................................................................................182
23.3 Starting a Conversion ....................................................................................184
23.4 Prescaling and Conversion Timing ................................................................184
23.5 Changing Channel or Reference Selection ...................................................186
23.6 ADC Noise Canceler .....................................................................................187
23.7 ADC Conversion Result .................................................................................190Enter Title of Manual [DATASHEET] v
8159E–AVR–02/2013
23.8 Register Description ......................................................................................190
24 Boot Loader Support – Read-While-Write Self-Programming .........194
24.1 Features ........................................................................................................194
24.2 Overview ........................................................................................................194
24.3 Application and Boot Loader Flash Sections .................................................194
24.4 Read-While-Write and No Read-While-Write Flash Sections ........................194
24.5 Boot Loader Lock Bits ...................................................................................197
24.6 Entering the Boot Loader Program ................................................................198
24.7 Addressing the Flash During Self-Programming ...........................................198
24.8 Self-Programming the Flash ..........................................................................199
24.9 Register Description ......................................................................................205
25 Memory Programming .........................................................................207
25.1 Program And Data Memory Lock Bits ...........................................................207
25.2 Fuse Bits ........................................................................................................208
25.3 Signature Bytes .............................................................................................209
25.4 Calibration Byte .............................................................................................209
25.5 Page Size ......................................................................................................210
25.6 Parallel Programming Parameters, Pin Mapping, and Commands ...............210
25.7 Parallel Programming ....................................................................................212
25.8 Serial Downloading ........................................................................................220
25.9 Serial Programming Pin Mapping ..................................................................220
26 Electrical Characteristics – TA = -40°C to 85°C .................................225
26.1 Absolute Maximum Ratings* .........................................................................225
26.2 DC Characteristics .........................................................................................225
26.3 Speed Grades ...............................................................................................227
26.4 Clock Characteristics .....................................................................................227
26.5 System and Reset Characteristics ................................................................228
26.6 Two-wire Serial Interface Characteristics ......................................................229
26.7 SPI Timing Characteristics ............................................................................230
26.8 ADC Characteristics ......................................................................................232
27 Electrical Characteristics – TA = -40°C to 105°C ...............................233
27.1 DC Characteristics .........................................................................................233
28 Typical Characteristics – TA = -40°C to 85°C ....................................235
28.1 Active Supply Current ....................................................................................235
28.2 Idle Supply Current ........................................................................................239Enter Title of Manual [DATASHEET] vi
8159E–AVR–02/2013
28.3 Power-down Supply Current ..........................................................................242
28.4 Power-save Supply Current ...........................................................................243
28.5 Standby Supply Current ................................................................................244
28.6 Pin Pull-up .....................................................................................................247
28.7 Pin Driver Strength ........................................................................................249
28.8 Pin Thresholds and Hysteresis ......................................................................253
28.9 Bod Thresholds and Analog Comparator Offset ............................................258
28.10 Internal Oscillator Speed ...............................................................................260
28.11 Current Consumption of Peripheral Units ......................................................267
28.12 Current Consumption in Reset and Reset Pulsewidth ...................................270
29 Typical Characteristics – TA = -40°C to 105°C ..................................272
29.1 ATmega8A Typical Characteristics ................................................................272
30 Register Summary ................................................................................301
31 Instruction Set Summary .....................................................................303
32 Ordering Information ...........................................................................306
33 Packaging Information .........................................................................307
33.1 32A ................................................................................................................307
33.2 28P3 ..............................................................................................................308
34 Errata .....................................................................................................309
34.1 ATmega8A, rev. L ..........................................................................................310
35 Datasheet Revision History .................................................................312
35.1 Rev.8159E – 02/2013 ....................................................................................312
35.2 Rev.8159D – 02/11 ........................................................................................312
35.3 Rev.8159C – 07/09 ........................................................................................312
35.4 Rev.8159B – 05/09 ........................................................................................312
35.5 Rev.8159A – 08/08 ........................................................................................313
Table of Contents.......................................................................................iAtmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 8159E–AVR–02/2013
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation or its
subsidiaries. Other terms and product names may be trademarks of others.
Atmel AVR1924: XMEGA-A1 Xplained Hardware
User's Guide
Features
• Atmel® ATxmega128A1 microcontroller
• External memory
- 8MB SDRAM
• Atmel AT32UC3B1256
- Communication gateway
- Programmer for Atmel AVR® XMEGA®
• Analog input (to ADC)
- Temperature sensor
- Light sensor
• Analog output (from DAC)
- Mono speaker via audio amplifier
• Digital I/O
- UART communication through USB gateway
- Eight mechanical button switches
- Eight LEDs
- Eight spare analog pins
- 24 spare digital pins
1 Introduction
The Atmel XMEGA-A1 Xplained evaluation kit is a hardware platform to evaluate
the Atmel ATxmega128A1 microcontroller.
The kit offers a larger range of features that enables the Atmel AVR XMEGA user
to get started using XMEGA peripherals right away and understand how to
integrate the XMEGA device in their own design.
Figure 1-1. XMEGA-A1 Xplained evaluation kit.
8-bit Atmel
Microcontrollers
Application Note
Preliminary
Rev. 8370C-AVR-12/11 2 Atmel AVR1924
8370C-AVR-12/11
2 Related items
Atmel FLIP (Flexible In-system Programmer)
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=3886
Atmel AVR Studio® 4 (free Atmel IDE)
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725
Atmel AVR JTAGICE mkII (on-chip programming and debugging tool)
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=3353
Atmel AVR ONE! (on-chip programming and debugging tool)
http://www.atmel.com/dyn/products/tools_card.asp?tool_id=4279
3 General information
This document targets the Atmel XMEGA-A1 Xplained evaluation kit, revision 9. The
schematic, layout, and bill of materials can be found online in the zip files associated
with this application note at:
http://www.atmel.com/products/AVR/xplain.asp?family_id=607&source=redirect.
The XMEGA-A1 Xplained kit is intended to demonstrate the Atmel ATxmega128A1
microcontroller, and the hardware that relates to the Atmel AT32UC3B1256 is,
therefore, not covered in this document.
Figure 3-1. Overview of the XMEGA-A1 Xplained kit.
SDRAM
ATxmega128A1 JTAG and PDI
DataFlash footprint
XMEGA PORT A
USB (COM and PSU)
ATxmega128A1
Speaker
XMEGA PORT C
Audio amp.
XMEGA PORT F Power jumper XMEGA PORT D/R
Light sensor
Temp. sensor
AT32UC3B1256
3.1 Preprogrammed firmware
The Atmel ATxmega128A1 and AT32UC3B1256 that come with the Atmel XMEGAA1
Xplained kit are both preprogrammed.
The preprogrammed firmware in the XMEGA plays different sounds when the
mechanical button switches are pushed. Atmel AVR1924
3
8370C-AVR-12/11
The preprogrammed Atmel AT32UC3B1256 firmware offers features such as a boot
loader for self-programming and a UART-to-USB gateway.
3.2 Power supply
The kit is powered via the USB connector, which leaves two options to power it:
Connect the kit either to a PC through a USB cable, or to a 5V USB power supply
(AC/DC adapter).
3.3 Measuring the XMEGA power consumption
As part of an evaluation of the Atmel ATxmega128A1, it can be of interest to measure
its power consumption. The power jumper (J300) is connected between the 3.3V
regulated voltage from the regulator and the ATxmega128A1 supply. By replacing the
jumper with an ammeter, it is possible to measure the current consumption of the
ATxmega128A1. No other components are connected to the same supply as the
ATxmega128A1, and other components, therefore, do not affect the measurement of
the ATxmega128A1 current consumption (except the DC leakage in the decoupling
capacitors).
3.4 Programming the XMEGA through the UART-to-USB gateway
The ATxmega128A1 has a pre-programmed UART boot loader. How to program the
device through the UART-to-USB gateway is described in the Atmel application note
“AVR1927: XMEGA-A1 Xplained Getting started guide”.
3.5 Communication through the UART-to-USB gateway
The XMEGA UARTC0 is connected to a UART on the AT32UC3B1256. The
AT32UC3B1256 UART is communicating at 115200 baud, using one start bit, eight
data bits, one stop bit, and no parity.
When the AT32UC3B1256 device is enumerated (connected to a PC), the data
transmitted from the XMEGA is passed on to a (virtual) COM port. This means that it
is possible to use a terminal program to receive the transmitted data on a PC.
Similarly, data transmitted from the PC COM port is passed on to the XMEGA UART
through the gateway.
NOTE The AT32UC3B1256 is also connected to the shared SPI and TWI lines, and so it is
also possible to add TWI and SPI gateway functionality for these serial interfaces, if
desired. This gateway functionality is not available in the default firmware for the
AT32UC3B1256. Please refer to the schematics for more information about these
connections. 4 Atmel AVR1924
8370C-AVR-12/11
4 Connectors
The Atmel XMEGA-A1 Xplained kit has five 10-pin, 100mil headers. One header is
used for programming the Atmel ATxmega128A1, and the others are used to access
spare analog and digital pins on the XMEGA (expansion headers).
4.1 Programming headers
The XMEGA can be programmed and debugged by connecting an external
programming/debugging tool to the JTAG and PDI header (J201). The header has a
standard JTAG programmer pin-out (refer to online help in the Atmel AVR Studio),
and tools like the JTAGICE mkII or AVR ONE! can thus be connected directly to the
header. If it is desired to use PDI programming/debugging, an adapter must be used.
Due to physical differences of the JTAGICE mkII and AVR ONE! probes, the PCB has
an opening below the JTAG and PDI header. This is to make room for the orientation
tap on the JTAGICE mkII probe.
Because JTAG TDO and PDI DATA are connected on the PCB for this kit, JTAG
must be disabled on the device in order to use PDI. The reason for this is that when
JTAG is enabled it will enable a pull-up internally on TDO which interferes with the
PDI initialization sequence.
The connection of JTAG_TDO with PDI_DATA is also an issue when the application
on the device uses the JTAG_TDO pin e.g. by driving this pin actively or by using a
pull-up. This will interfere with ongoing PDI communication. Additionally, when JTAG
is disabled and the application is driving the JTAG_TDO pin it might even be not
possible to establish a PDI connection. A workaround for this is to add a ~1k resistor
from PDI_CLK/RESET to GND. This will keep the device in reset while PDI is
enabled. When a PDI connection is established the flash can be erased or JTAG can
be enabled in order to "unlock" the kit.
Table 4-1. XMEGA programming and debugging interface – JTAG and PDI.
J201 pin JTAG (1) PDI (2)
1 TCK -
2 GND GND (3)
3 TDO DATA
4 VCC VCC (3)
5 TMS -
6 nSRST CLK
7 - -
8 - -
9 TDI -
10 GND GND (3)
Notes: 1. Standard pin-out for JTAGICE mkII and other Atmel programming tools.
2. Requires adapter to connect a JTAGICE mkII (refer to AVR Studio help).
3. It is only required to connect on VCC/GND pin.
The Atmel AT32UC3B1256 can be programmed through its boot loader. The boot
loader is evoked by shorting the J600 jumper before applying power to the board. The Atmel AVR1924
5
8370C-AVR-12/11
programming is performed through the FLIP plug-in in AVR Studio (which can also be
started as a standalone application).
FLIP (Flexible In-system Programmer) is free Atmel proprietary software that runs on
Windows® 9x/Me/NT/2000/XP and Linux® x86. FLIP supports in-system programming
of flash devices through RS232, USB, or CAN.
Alternatively, the AT32UC3B1256 can be programmed by connecting a programming
tool, such as JTAGICE mkII, to test points TP600-607.
NOTE It is not recommended to program the AT32UC3B1256 using a programming tool, as
this will erase the boot loader.
4.2 I/O expansion headers
The XMEGA analog PORTA is available on the J2 header. This allows the user to
connect external signals to the analog-to-digital converter (ADC), digital-to-analog
converter (DAC), and analog comparators on PORTA.
The XMEGA digital PORTF and PORTC are available on the J1 and J4 headers,
respectively. These ports feature general-purpose I/O and various communication
modules (USART, SPI, and TWI). PORTD and PORTF are mixed on the J3 header.
NOTE The communication modules on PORTC and PORTF can be interconnected to test
various functions and features: The USART can loop back communication with a
jumper, or communicate between the two USARTs on the port. The native SPI and
the USART in SPI master mode can be connected, and the TWI module can be
enabled in both master and slave modes at the same time to get loop-back behavior.
(Pull-up resistors can be mounted on R101 and R102. These are not mounted from
the factory.) 6 Atmel AVR1924
8370C-AVR-12/11
5 Attached memories
The Atmel XMEGA-A1 Xplained kit demonstrates how to use the external bus
interface (EBI) module to connect a 4-bit SDRAM. An 8MB SDRAM (16Mb x 4) is
attached in three-port EBI mode (PORTH, PORTK, and PORTJ). Atmel AVR1924
7
8370C-AVR-12/11
6 Miscellaneous I/O
6.1 Mechanical button switches
Eight mechanical button switches are connected to XMEGA PORTD(PD0:PD5) and
PORTR(PR0:PR1). Internal pull-ups should be enabled to detect when the buttons
are pushed, as they short the respective line to GND.
NOTE Buttons share the pins with the J3 header: Pushing the buttons potentially affects
communication or other functionality on these pins.
6.2 LEDs
Eight yellow LEDs are connected to XMEGA PORTE. The LEDs are active low, and
thus light up when the respective lines are output low by the XMEGA.
One green and one red LED are inside the same package and therefore the colors
can be mixed to orange when both are activated. The red LED can be activated by
driving the connected I/O line to GND. The green LED is controlled via a FET and is
by default on when the board is powered. However this power indicator LED can also
be turned off by driving the gate of the FET to GND. Both LEDs are controlled by the
Atmel AT32UC3B1256. The default firmware will use the red LED to signal activity on
the UART to USB bridge by toggling the LED.
6.3 Analog I/O
An NTC temperature sensor and a light sensor are connected to PORTB on PB0 and
PB1, respectively. These analog references can be used as input to the ADC.
An audio amplifier (and mono speaker) is connected to PORTB on pin PB2. This pin
is connected to the XMEGA DAC, and thus offers a way to generate sound. 8 Atmel AVR1924
8370C-AVR-12/11
7 Included code example
The example application is based on the Atmel AVR Software Framework found
online at http://asf.atmel.no. For documentation, help, and examples on the drivers
used, please see the website.
For more information about the included code example, see the Atmel application
note “AVR1927: XMEGA-A1 Xplained Getting Started Guide”.
7.1 Compiling and running
The code examples to be found in ASF can be compiled by running make on the
makefile included in the project, or by opening the project in IAR™, and compiling the
project within IAR. Atmel AVR1924
9
8370C-AVR-12/11
8 Further code examples and drivers
Several Getting-Started trainings for the Atmel XMEGA-A1 Xplained kit can be
downloaded from the Atmel website. These trainings offer general introduction to
XMEGA peripherals. Please refer to AVR1500 through AVR1510.
Further information and drivers for XMEGA can be downloaded as application notes,
also distributed from the Atmel website. 10 Atmel AVR1924
8370C-AVR-12/11
9 Known issues
9.1 Light sensor
The output range of the light sensor is 0V – 3.3V. The ADC reference must therefore
be high enough to match the output range of the light sensor when performing
measurements.
9.2 USB test points
Touching the test points of the USB data lines on the reverse side of the board while
there is an ongoing communication, might interrupt the device and cause the device
to stop responding. The kit must be reconnected to start working properly again.
9.3 PDI initialization
Because JTAG_TDO and PDI_DATA are connected on the PCB for this kit, JTAG
must be disabled on the device in order to use PDI. The reason for this is that when
JTAG is enabled it will enable a pull-up internally on TDO which interferes with the
PDI initialization sequence.
The connection of JTAG_TDO with PDI_DATA is also an issue when the application
on the device uses the JTAG_TDO pin e.g. by driving this pin actively or by using a
pull-up. This will interfere with ongoing PDI communication. Additionally, when JTAG
is disabled and the application is driving the JTAG_TDO pin it might even not be
possible to establish a PDI connection. A workaround for this is to add a ~1k resistor
from PDI_CLK/RESET to GND. This will keep the device in reset while PDI is
enabled. When a PDI connection is established the flash can be erased or JTAG can
be enabled in order to "unlock" the kit. Atmel AVR1924
11
8370C-AVR-12/11
10 Revision history
The revision of the evaluation kit can be found on the sticker on the reverse side of
the PCB.
10.1 Revision 7
The Atmel XMEGA-A1 Xplained kit, revision 7, is the first released revision of the
XMEGA-A1 Xplained kit.
This kit replaces the Atmel Xplain evaluation kit. Information about the original Xplain
evaluation kit can be found in the Atmel application note AVR1907: Xplain Hardware
User’s Guide.
10.2 Revisions 1 to 6
Not released. 12 Atmel AVR1924
8370C-AVR-12/11
11 Table of contents
Features............................................................................................... 1
1 Introduction...................................................................................... 1
2 Related items.................................................................................... 2
3 General information......................................................................... 2
3.1 Preprogrammed firmware.................................................................................... 2
3.2 Power supply....................................................................................................... 3
3.3 Measuring the XMEGA power consumption ....................................................... 3
3.4 Programming the XMEGA through the UART-to-USB gateway ......................... 3
3.5 Communication through the UART-to-USB gateway.......................................... 3
4 Connectors....................................................................................... 4
4.1 Programming headers......................................................................................... 4
4.2 I/O expansion headers ........................................................................................ 5
5 Attached memories.......................................................................... 6
6 Miscellaneous I/O............................................................................. 7
6.1 Mechanical button switches ................................................................................ 7
6.2 LEDs.................................................................................................................... 7
6.3 Analog I/O............................................................................................................ 7
7 Included code example ................................................................... 8
7.1 Compiling and running ........................................................................................ 8
8 Further code examples and drivers ............................................... 9
9 Known issues................................................................................. 10
9.1 Light sensor....................................................................................................... 10
9.2 USB test points.................................................................................................. 10
9.3 PDI initialization................................................................................................. 10
10 Revision history ........................................................................... 11
10.1 Revision 7........................................................................................................ 11
10.2 Revisions 1 to 6............................................................................................... 11
11 Table of contents ......................................................................... 128370C-AVR-12/11
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: (+1)(408) 441-0311
Fax: (+1)(408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Milennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan
16F, Shin Osaki Kangyo Bldg.
1-6-4 Osaki Shinagawa-ku
Tokyo 104-0032
JAPAN
Tel: (+81) 3-6417-0300
Fax: (+81) 3-6417-0370
© 2011 Atmel Corporation. All rights reserved.
Atmel®
, Atmel logo and combinations thereof, AVR®
, AVR Logo®
, AVR Studio®
, XMEGA®
and others are registered trademarks or
trademarks of Atmel Corporation or its subsidiaries. Windows®
and others are registered trademarks of Microsoft Corporation in U.S.
and or other countries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to
any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL
TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS
ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE
LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION,
DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO
USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or
warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and
product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically
provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or
warranted for use as components in applications intended to support or sustain life.
Features
• High-performance, Low-power Atmel®AVR® 8-bit Microcontroller
• Advanced RISC Architecture
– 130 Powerful Instructions – Most Single-clock Cycle Execution
– 32 × 8 General Purpose Working Registers
– Fully Static Operation
– Up to 16MIPS Throughput at 16MHz
– On-chip 2-cycle Multiplier
• High Endurance Non-volatile Memory segments
– 8Kbytes of In-System Self-programmable Flash program memory
– 512Bytes EEPROM
– 1Kbyte Internal SRAM
– Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
– Data retention: 20 years at 85°C/100 years at 25°C(1)
– Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program
True Read-While-Write Operation
– Programming Lock for Software Security
• Peripheral Features
– Two 8-bit Timer/Counters with Separate Prescaler, one Compare Mode
– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture
Mode
– Real Time Counter with Separate Oscillator
– Three PWM Channels
– 8-channel ADC in TQFP and QFN/MLF package
Eight Channels 10-bit Accuracy
– 6-channel ADC in PDIP package
Six Channels 10-bit Accuracy
– Byte-oriented Two-wire Serial Interface
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
• Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated RC Oscillator
– External and Internal Interrupt Sources
– Five Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, and
Standby
• I/O and Packages
– 23 Programmable I/O Lines
– 28-lead PDIP, 32-lead TQFP, and 32-pad QFN/MLF
• Operating Voltages
– 2.7V - 5.5V (ATmega8L)
– 4.5V - 5.5V (ATmega8)
• Speed Grades
– 0 - 8MHz (ATmega8L)
– 0 - 16MHz (ATmega8)
• Power Consumption at 4Mhz, 3V, 25C
– Active: 3.6mA
– Idle Mode: 1.0mA
– Power-down Mode: 0.5µA
8-bit Atmel with
8KBytes InSystem
Programmable
Flash
ATmega8
ATmega8L
Rev.2486AA–AVR–02/20132
2486AA–AVR–02/2013
ATmega8(L)
Pin
Configurations
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
(INT1) PD3
(XCK/T0) PD4
GND
VCC
GND
VCC
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
PC1 (ADC1)
PC0 (ADC0)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK)
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
(OC1A) PB1
(SS/OC1B) PB2
(MOSI/OC2) PB3
(MISO) PB4
PD2 (INT0)
PD1 (TXD)
PD0 (RXD)
PC6 (RESET)
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
TQFP Top View
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
(RESET) PC6
(RXD) PD0
(TXD) PD1
(INT0) PD2
(INT1) PD3
(XCK/T0) PD4
VCC
GND
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
PC1 (ADC1)
PC0 (ADC0)
GND
AREF
AVCC
PB5 (SCK)
PB4 (MISO)
PB3 (MOSI/OC2)
PB2 (SS/OC1B)
PB1 (OC1A)
PDIP
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
MLF Top View
(INT1) PD3
(XCK/T0) PD4
GND
VCC
GND
VCC
(XTAL1/TOSC1) PB6
(XTAL2/TOSC2) PB7
PC1 (ADC1)
PC0 (ADC0)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK)
(T1) PD5
(AIN0) PD6
(AIN1) PD7
(ICP1) PB0
(OC1A) PB1
(SS/OC1B) PB2
(MOSI/OC2) PB3
(MISO) PB4
PD2 (INT0)
PD1 (TXD)
PD0 (RXD)
PC6 (RESET)
PC5 (ADC5/SCL)
PC4 (ADC4/SDA)
PC3 (ADC3)
PC2 (ADC2)
NOTE:
The large center pad underneath the MLF
packages is made of metal and internally
connected to GND. It should be soldered
or glued to the PCB to ensure good
mechanical stability. If the center pad is
left unconneted, the package might
loosen from the PCB.3
2486AA–AVR–02/2013
ATmega8(L)
Overview The Atmel®AVR® ATmega8 is a low-power CMOS 8-bit microcontroller based on the AVR RISC
architecture. By executing powerful instructions in a single clock cycle, the ATmega8 achieves
throughputs approaching 1MIPS per MHz, allowing the system designer to optimize power consumption
versus processing speed.
Block Diagram Figure 1. Block Diagram
INTERNAL
OSCILLATOR
OSCILLATOR
WATCHDOG
TIMER
MCU CTRL.
& TIMING
OSCILLATOR
TIMERS/
COUNTERS
INTERRUPT
UNIT
STACK
POINTER
EEPROM
SRAM
STATUS
REGISTER
USART
PROGRAM
COUNTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
PROGRAMMING
LOGIC SPI
ADC
INTERFACE
COMP.
INTERFACE
PORTC DRIVERS/BUFFERS
PORTC DIGITAL INTERFACE
GENERAL
PURPOSE
REGISTERS
X
Y
Z
ALU
+
-
PORTB DRIVERS/BUFFERS
PORTB DIGITAL INTERFACE
PORTD DIGITAL INTERFACE
PORTD DRIVERS/BUFFERS
XTAL1
XTAL2
CONTROL
LINES
VCC
GND
MUX &
ADC
AGND
AREF
PC0 - PC6 PB0 - PB7
PD0 - PD7
AVR CPU
TWI
RESET4
2486AA–AVR–02/2013
ATmega8(L)
The Atmel®AVR® core combines a rich instruction set with 32 general purpose working registers.
All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The
resulting architecture is more code efficient while achieving throughputs up to ten times faster
than conventional CISC microcontrollers.
The ATmega8 provides the following features: 8 Kbytes of In-System Programmable Flash with
Read-While-Write capabilities, 512 bytes of EEPROM, 1 Kbyte of SRAM, 23 general purpose
I/O lines, 32 general purpose working registers, three flexible Timer/Counters with compare
modes, internal and external interrupts, a serial programmable USART, a byte oriented Twowire
Serial Interface, a 6-channel ADC (eight channels in TQFP and QFN/MLF packages) with
10-bit accuracy, a programmable Watchdog Timer with Internal Oscillator, an SPI serial port,
and five software selectable power saving modes. The Idle mode stops the CPU while allowing
the SRAM, Timer/Counters, SPI port, and interrupt system to continue functioning. The Powerdown
mode saves the register contents but freezes the Oscillator, disabling all other chip functions
until the next Interrupt or Hardware Reset. In Power-save mode, the asynchronous timer
continues to run, allowing the user to maintain a timer base while the rest of the device is sleeping.
The ADC Noise Reduction mode stops the CPU and all I/O modules except asynchronous
timer and ADC, to minimize switching noise during ADC conversions. In Standby mode, the
crystal/resonator Oscillator is running while the rest of the device is sleeping. This allows very
fast start-up combined with low-power consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The
Flash Program memory can be reprogrammed In-System through an SPI serial interface, by a
conventional non-volatile memory programmer, or by an On-chip boot program running on the
AVR core. The boot program can use any interface to download the application program in the
Application Flash memory. Software in the Boot Flash Section will continue to run while the
Application Flash Section is updated, providing true Read-While-Write operation. By combining
an 8-bit RISC CPU with In-System Self-Programmable Flash on a monolithic chip, the Atmel
ATmega8 is a powerful microcontroller that provides a highly-flexible and cost-effective solution
to many embedded control applications.
The ATmega8 is supported with a full suite of program and system development tools, including
C compilers, macro assemblers, program simulators, and evaluation kits.
Disclaimer Typical values contained in this datasheet are based on simulations and characterization of
other AVR microcontrollers manufactured on the same process technology. Minimum and Maximum
values will be available after the device is characterized.5
2486AA–AVR–02/2013
ATmega8(L)
Pin Descriptions
VCC Digital supply voltage.
GND Ground.
Port B (PB7..PB0)
XTAL1/XTAL2/TOSC1/
TOSC2
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Depending on the clock selection fuse settings, PB6 can be used as input to the inverting Oscillator
amplifier and input to the internal clock operating circuit.
Depending on the clock selection fuse settings, PB7 can be used as output from the inverting
Oscillator amplifier.
If the Internal Calibrated RC Oscillator is used as chip clock source, PB7..6 is used as TOSC2..1
input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.
The various special features of Port B are elaborated in “Alternate Functions of Port B” on page
58 and “System Clock and Clock Options” on page 25.
Port C (PC5..PC0) Port C is an 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port C output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
PC6/RESET If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical characteristics
of PC6 differ from those of the other pins of Port C.
If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low level on this pin
for longer than the minimum pulse length will generate a Reset, even if the clock is not running.
The minimum pulse length is given in Table 15 on page 38. Shorter pulses are not guaranteed to
generate a Reset.
The various special features of Port C are elaborated on page 61.
Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port D also serves the functions of various special features of the ATmega8 as listed on page
63.
RESET Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running. The minimum pulse length is given in Table 15 on page
38. Shorter pulses are not guaranteed to generate a reset.6
2486AA–AVR–02/2013
ATmega8(L)
AVCC AVCC is the supply voltage pin for the A/D Converter, Port C (3..0), and ADC (7..6). It should be
externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected
to VCC through a low-pass filter. Note that Port C (5..4) use digital supply voltage, VCC.
AREF AREF is the analog reference pin for the A/D Converter.
ADC7..6 (TQFP and
QFN/MLF Package
Only)
In the TQFP and QFN/MLF package, ADC7..6 serve as analog inputs to the A/D converter.
These pins are powered from the analog supply and serve as 10-bit ADC channels.7
2486AA–AVR–02/2013
ATmega8(L)
Resources A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
Note: 1.
Data Retention Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.8
2486AA–AVR–02/2013
ATmega8(L)
About Code
Examples
This datasheet contains simple code examples that briefly show how to use various parts of the
device. These code examples assume that the part specific header file is included before compilation.
Be aware that not all C compiler vendors include bit definitions in the header files and
interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.9
2486AA–AVR–02/2013
ATmega8(L)
Atmel AVR CPU
Core
Introduction This section discusses the Atmel®AVR® core architecture in general. The main function of the
CPU core is to ensure correct program execution. The CPU must therefore be able to access
memories, perform calculations, control peripherals, and handle interrupts.
Architectural
Overview
Figure 2. Block Diagram of the AVR MCU Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the Program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the Program memory. This concept enables instructions to be executed
in every clock cycle. The Program memory is In-System Reprogrammable Flash memory.
The fast-access Register File contains 32 × 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
32 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
EEPROM
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
i/O Module 2
i/O Module1
i/O Module n10
2486AA–AVR–02/2013
ATmega8(L)
can also be used as an address pointer for look up tables in Flash Program memory. These
added function registers are the 16-bit X-register, Y-register, and Z-register, described later in
this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
The Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format.
Every Program memory address contains a 16-bit or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot program section and the
Application program section. Both sections have dedicated Lock Bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the reset routine (before subroutines or interrupts are executed). The Stack
Pointer SP is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional global
interrupt enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F.11
2486AA–AVR–02/2013
ATmega8(L)
Arithmetic Logic
Unit – ALU
The high-performance Atmel®AVR® ALU operates in direct connection with all the 32 general
purpose working registers. Within a single clock cycle, arithmetic operations between general
purpose registers or between a register and an immediate are executed. The ALU operations
are divided into three main categories – arithmetic, logical, and bit-functions. Some implementations
of the architecture also provide a powerful multiplier supporting both signed/unsigned
multiplication and fractional format. For a detailed description, see “Instruction Set Summary” on
page 311.
Status Register The Status Register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.
The AVR Status Register – SREG – is defined as:
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the Instruction Set Reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination
for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
Bit 7 6 5 4 3 2 1 0
I T H S V N Z C SREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 012
2486AA–AVR–02/2013
ATmega8(L)
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a Carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
General Purpose
Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve
the required performance and flexibility, the following input/output schemes are supported by the
Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 3 shows the structure of the 32 general purpose working registers in the CPU.
Figure 3. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 3, each register is also assigned a Data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-pointer, Y-pointer, and Z-pointer Registers can be set to index any register in
the file.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
Purpose R15 0x0F
Working R16 0x10
Registers R17 0x11
…
R26 0x1A X-register Low Byte
R27 0x1B X-register High Byte
R28 0x1C Y-register Low Byte
R29 0x1D Y-register High Byte
R30 0x1E Z-register Low Byte
R31 0x1F Z-register High Byte13
2486AA–AVR–02/2013
ATmega8(L)
The X-register, Yregister
and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the Data Space. The three indirect
address registers X, Y and Z are defined as described in Figure 4.
Figure 4. The X-register, Y-register and Z-Register
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the Instruction Set Reference for details).
Stack Pointer The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x60. The Stack Pointer is decremented by one when data is pushed onto the Stack
with the PUSH instruction, and it is decremented by two when the return address is pushed onto
the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is
popped from the Stack with the POP instruction, and it is incremented by two when address is
popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations
of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
Instruction
Execution Timing
This section describes the general access timing concepts for instruction execution. The
Atmel®AVR® CPU is driven by the CPU clock clkCPU, directly generated from the selected clock
source for the chip. No internal clock division is used.
15 XH XL 0
X-register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 7 0 7 0
R31 (0x1F) R30 (0x1E)
Bit 15 14 13 12 11 10 9 8
SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
0000000014
2486AA–AVR–02/2013
ATmega8(L)
Figure 5 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access Register File concept. This is the basic pipelining concept
to obtain up to 1MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 5. The Parallel Instruction Fetches and Instruction Executions
Figure 6 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Figure 6. Single Cycle ALU Operation
Reset and
Interrupt Handling
The Atmel®AVR® provides several different interrupt sources. These interrupts and the separate
Reset Vector each have a separate Program Vector in the Program memory space. All interrupts
are assigned individual enable bits which must be written logic one together with the
Global Interrupt Enable bit in the Status Register in order to enable the interrupt. Depending on
the Program Counter value, interrupts may be automatically disabled when Boot Lock Bits
BLB02 or BLB12 are programmed. This feature improves software security. See the section
“Memory Programming” on page 215 for details.
The lowest addresses in the Program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of Vectors is shown in “Interrupts” on page 46. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request
0. The Interrupt Vectors can be moved to the start of the boot Flash section by setting the Interrupt
Vector Select (IVSEL) bit in the General Interrupt Control Register (GICR). Refer to
“Interrupts” on page 46 for more information. The Reset Vector can also be moved to the start of
the boot Flash section by programming the BOOTRST Fuse, see “Boot Loader Support – ReadWhile-Write
Self-Programming” on page 202.
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPU15
2486AA–AVR–02/2013
ATmega8(L)
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s)
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the global interrupt
enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
global interrupt enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMWE ; start EEPROM write
sbi EECR, EEWE
out SREG, r16 ; restore SREG value (I-bit)
C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1< xxx
... ... ...
Table 19. Reset and Interrupt Vectors Placement
BOOTRST(1) IVSEL Reset Address Interrupt Vectors Start Address
1 0 0x000 0x001
1 1 0x000 Boot Reset Address + 0x001
0 0 Boot Reset Address 0x001
0 1 Boot Reset Address Boot Reset Address + 0x00148
2486AA–AVR–02/2013
ATmega8(L)
When the BOOTRST Fuse is unprogrammed, the boot section size set to 2Kbytes and the
IVSEL bit in the GICR Register is set before any interrupts are enabled, the most typical and
general program setup for the Reset and Interrupt Vector Addresses is:
AddressLabels Code Comments
$000 rjmp RESET ; Reset handler
;
$001 RESET:ldi r16,high(RAMEND); Main program start
$002 out SPH,r16 ; Set Stack Pointer to top of RAM
$003 ldi r16,low(RAMEND)
$004 out SPL,r16
$005 sei ; Enable interrupts
$006 xxx
;
.org $c01
$c01 rjmp EXT_INT0 ; IRQ0 Handler
$c02 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
$c12 rjmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST Fuse is programmed and the boot section size set to 2Kbytes, the most
typical and general program setup for the Reset and Interrupt Vector Addresses is:
AddressLabels Code Comments
.org $001
$001 rjmp EXT_INT0 ; IRQ0 Handler
$002 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
$012 rjmp SPM_RDY ; Store Program Memory Ready Handler
;
.org $c00
$c00 rjmp RESET ; Reset handler
;
$c01 RESET:ldi r16,high(RAMEND); Main program start
$c02 out SPH,r16 ; Set Stack Pointer to top of RAM
$c03 ldi r16,low(RAMEND)
$c04 out SPL,r16
$c05 sei ; Enable interrupts
$c06 xxx49
2486AA–AVR–02/2013
ATmega8(L)
When the BOOTRST Fuse is programmed, the boot section size set to 2Kbytes, and the IVSEL
bit in the GICR Register is set before any interrupts are enabled, the most typical and general
program setup for the Reset and Interrupt Vector Addresses is:
AddressLabels Code Comments
;
.org $c00
$c00 rjmp RESET ; Reset handler
$c01 rjmp EXT_INT0 ; IRQ0 Handler
$c02 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
$c12 rjmp SPM_RDY ; Store Program Memory Ready Handler
$c13 RESET: ldi r16,high(RAMEND); Main program start
$c14 out SPH,r16 ; Set Stack Pointer to top of RAM
$c15 ldi r16,low(RAMEND)
$c16 out SPL,r16
$c17 sei ; Enable interrupts
$c18 xxx
Moving Interrupts
Between Application
and Boot Space
The General Interrupt Control Register controls the placement of the Interrupt Vector table.
General Interrupt
Control Register –
GICR
• Bit 1 – IVSEL: Interrupt Vector Select
When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash
memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot
Loader section of the Flash. The actual address of the start of the boot Flash section is determined
by the BOOTSZ Fuses. Refer to the section “Boot Loader Support – Read-While-Write
Self-Programming” on page 202 for details. To avoid unintentional changes of Interrupt Vector
tables, a special write procedure must be followed to change the IVSEL bit:
1. Write the Interrupt Vector Change Enable (IVCE) bit to one
2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled
in the cycle IVCE is set, and they remain disabled until after the instruction following the write to
IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status
Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed,
interrupts are disabled while executing from the Application section. If Interrupt
Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts
are disabled while executing from the Boot Loader section. Refer to the section “Boot Loader
Support – Read-While-Write Self-Programming” on page 202 for details on Boot Lock Bits.
Bit 7 6 5 4 3 2 1 0
INT1 INT0 – – – – IVSEL IVCE GICR
Read/Write R/W R/W R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 050
2486AA–AVR–02/2013
ATmega8(L)
• Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by
hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable
interrupts, as explained in the IVSEL description above. See Code Example below.
Assembly Code Example
Move_interrupts:
; Enable change of Interrupt Vectors
ldi r16, (1< CSn2:0 > 1). The number of system clock
cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution.
However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
External Clock Source An external clock source applied to the T1/T0 pin can be used as Timer/Counter clock
(clkT1/clkT0). The T1/T0 pin is sampled once every system clock cycle by the pin synchronization
logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 30
shows a functional equivalent block diagram of the T1/T0 synchronization and edge detector
logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch
is transparent in the high period of the internal system clock.
The edge detector generates one clkT1/clkT0 pulse for each positive (CSn2:0 = 7) or negative
(CSn2:0 = 6) edge it detects.
Figure 30. T1/T0 Pin Sampling
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T1/T0 pin to the counter is updated.
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least
one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system
clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
Tn_sync
(To Clock
Select Logic)
Synchronization Edge Detector
D Q D Q
LE
Tn D Q
clkI/O74
2486AA–AVR–02/2013
ATmega8(L)
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency
(Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 31. Prescaler for Timer/Counter0 and Timer/Counter1(1)
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 30 on page 73
Special Function IO
Register – SFIOR
• Bit 0 – PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0
When this bit is written to one, the Timer/Counter1 and Timer/Counter0 prescaler will be reset.
The bit will be cleared by hardware after the operation is performed. Writing a zero to this bit will
have no effect. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a
reset of this prescaler will affect both timers. This bit will always be read as zero.
PSR10
Clear
clkT1 clkT0
T1
T0
clkI/O
Synchronization
Synchronization
Bit 7 6 5 4 3 2 1 0
– – – – ACME PUD PSR2 PSR10 SFIOR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 075
2486AA–AVR–02/2013
ATmega8(L)
16-bit
Timer/Counter1
The 16-bit Timer/Counter unit allows accurate program execution timing (event management),
wave generation, and signal timing measurement. The main features are:
• True 16-bit Design (that is, allows 16-bit PWM)
• Two Independent Output Compare Units
• Double Buffered Output Compare Registers
• One Input Capture Unit
• Input Capture Noise Canceler
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• External Event Counter
• Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)
Overview Most register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit
channel. However, when using the register or bit defines in a program, the precise form must be
used, that is, TCNT1 for accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 32 on page 76. For the
actual placement of I/O pins, refer to “Pin Configurations” on page 2. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit
locations are listed in the “16-bit Timer/Counter Register Description” on page 96.76
2486AA–AVR–02/2013
ATmega8(L)
Figure 32. 16-bit Timer/Counter Block Diagram(1)
Note: 1. Refer to “Pin Configurations” on page 2, Table 22 on page 58, and Table 28 on page 63 for
Timer/Counter1 pin placement and description
Registers The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Register
(ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16-
bit registers. These procedures are described in the section “Accessing 16-bit Registers” on
page 77. The Timer/Counter Control Registers (TCCR1A/B) are 8-bit registers and have no CPU
access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all visible
in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer
Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these registers
are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the T1 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the clock select logic is referred to as the timer clock (clkT1).
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Counter
value at all time. The result of the compare can be used by the waveform generator to
generate a PWM or variable frequency output on the Output Compare Pin (OC1A/B). See “Output
Compare Units” on page 83. The Compare Match event will also set the Compare Match
Flag (OCF1A/B) which can be used to generate an Output Compare interrupt request.
Clock Select
Timer/Counter
DATA BUS
OCRnA
OCRnB
ICRn
=
=
TCNTn
Waveform
Generation
Waveform
Generation
OCnA
OCnB
Noise
Canceler
ICPn
=
Fixed
TOP
Values
Edge
Detector
Control Logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(Int. Req.)
OCFnA
(Int. Req.)
OCFnB
(Int.Req.)
ICFn (Int.Req.)
TCCRnA TCCRnB
( From Analog
Comparator Ouput )
Tn Edge
Detector
( From Prescaler )
clkTn77
2486AA–AVR–02/2013
ATmega8(L)
The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered)
event on either the Input Capture Pin (ICP1) or on the Analog Comparator pins (see
“Analog Comparator” on page 186). The Input Capture unit includes a digital filtering unit (Noise
Canceler) for reducing the chance of capturing noise spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined
by either the OCR1A Register, the ICR1 Register, or by a set of fixed values. When using
OCR1A as TOP value in a PWM mode, the OCR1A Register can not be used for generating a
PWM output. However, the TOP value will in this case be double buffered allowing the TOP
value to be changed in run time. If a fixed TOP value is required, the ICR1 Register can be used
as an alternative, freeing the OCR1A to be used as PWM output.
Definitions The following definitions are used extensively throughout the document:
Compatibility The 16-bit Timer/Counter has been updated and improved from previous versions of the 16-bit
AVR Timer/Counter. This 16-bit Timer/Counter is fully compatible with the earlier version
regarding:
• All 16-bit Timer/Counter related I/O Register address locations, including Timer Interrupt
Registers
• Bit locations inside all 16-bit Timer/Counter Registers, including Timer Interrupt Registers
• Interrupt Vectors
The following control bits have changed name, but have same functionality and register location:
• PWM10 is changed to WGM10
• PWM11 is changed to WGM11
• CTC1 is changed to WGM12
The following bits are added to the 16-bit Timer/Counter Control Registers:
• FOC1A and FOC1B are added to TCCR1A
• WGM13 is added to TCCR1B
The 16-bit Timer/Counter has improvements that will affect the compatibility in some special
cases.
Accessing 16-bit
Registers
The TCNT1, OCR1A/B, and ICR1 are 16-bit registers that can be accessed by the AVR CPU via
the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations.
The 16-bit timer has a single 8-bit register for temporary storing of the High byte of the 16-bit
access. The same temporary register is shared between all 16-bit registers within the 16-bit
timer. Accessing the Low byte triggers the 16-bit read or write operation. When the Low byte of a
16-bit register is written by the CPU, the High byte stored in the temporary register, and the Low
byte written are both copied into the 16-bit register in the same clock cycle. When the Low byte
Table 35. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal
65535).
TOP The counter reaches the TOP when it becomes equal to the highest
value in the count sequence. The TOP value can be assigned to be one
of the fixed values: 0x00FF, 0x01FF, or 0x03FF, or to the value stored in
the OCR1A or ICR1 Register. The assignment is dependent of the mode
of operation.78
2486AA–AVR–02/2013
ATmega8(L)
of a 16-bit register is read by the CPU, the High byte of the 16-bit register is copied into the temporary
register in the same clock cycle as the Low byte is read.
Not all 16-bit accesses uses the temporary register for the High byte. Reading the OCR1A/B 16-
bit registers does not involve using the temporary register.
To do a 16-bit write, the High byte must be written before the Low byte. For a 16-bit read, the
Low byte must be read before the High byte.
The following code examples show how to access the 16-bit Timer Registers assuming that no
interrupts updates the temporary register. The same principle can be used directly for accessing
the OCR1A/B and ICR1 Registers. Note that when using “C”, the compiler handles the 16-bit
access.
Note: 1. See “About Code Examples” on page 8
The assembly code example returns the TCNT1 value in the r17:r16 Register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt
occurs between the two instructions accessing the 16-bit register, and the interrupt code
updates the temporary register by accessing the same or any other of the 16-bit Timer Registers,
then the result of the access outside the interrupt will be corrupted. Therefore, when both
the main code and the interrupt code update the temporary register, the main code must disable
the interrupts during the 16-bit access.
The following code examples show how to do an atomic read of the TCNT1 Register contents.
Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
Assembly Code Example(1)
...
; Set TCNT1 to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNT1H,r17
out TCNT1L,r16
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
...
C Code Example(1)
unsigned int i;
...
/* Set TCNT1 to 0x01FF */
TCNT1 = 0x1FF;
/* Read TCNT1 into i */
i = TCNT1;
...79
2486AA–AVR–02/2013
ATmega8(L)
Note: 1. See “About Code Examples” on page 8
The assembly code example returns the TCNT1 value in the r17:r16 Register pair.
Assembly Code Example(1)
TIM16_ReadTCNT1:
; Save Global Interrupt Flag
in r18,SREG
; Disable interrupts
cli
; Read TCNT1 into r17:r16
in r16,TCNT1L
in r17,TCNT1H
; Restore Global Interrupt Flag
out SREG,r18
ret
C Code Example(1)
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save Global Interrupt Flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Read TCNT1 into i */
i = TCNT1;
/* Restore Global Interrupt Flag */
SREG = sreg;
return i;
}80
2486AA–AVR–02/2013
ATmega8(L)
The following code examples show how to do an atomic write of the TCNT1 Register contents.
Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
Note: 1. See “About Code Examples” on page 8
The assembly code example requires that the r17:r16 Register pair contains the value to be written
to TCNT1.
Reusing the
Temporary High Byte
Register
If writing to more than one 16-bit register where the High byte is the same for all registers written,
then the High byte only needs to be written once. However, note that the same rule of
atomic operation described previously also applies in this case.
Timer/Counter
Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source
is selected by the clock select logic which is controlled by the clock select (CS12:0) bits located
in the Timer/Counter Control Register B (TCCR1B). For details on clock sources and prescaler,
see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 73.
Counter Unit The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit.
Figure 33 on page 81 shows a block diagram of the counter and its surroundings.
Assembly Code Example(1)
TIM16_WriteTCNT1:
; Save Global Interrupt Flag
in r18,SREG
; Disable interrupts
cli
; Set TCNT1 to r17:r16
out TCNT1H,r17
out TCNT1L,r16
; Restore Global Interrupt Flag
out SREG,r18
ret
C Code Example(1)
void TIM16_WriteTCNT1( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save Global Interrupt Flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore Global Interrupt Flag */
SREG = sreg;
}81
2486AA–AVR–02/2013
ATmega8(L)
Figure 33. Counter Unit Block Diagram
Signal description (internal signals):
count Increment or decrement TCNT1 by 1
direction Select between increment and decrement
clear Clear TCNT1 (set all bits to zero)
clkT1 Timer/Counter clock
TOP Signalize that TCNT1 has reached maximum value
BOTTOM Signalize that TCNT1 has reached minimum value (zero)
The 16-bit counter is mapped into two 8-bit I/O memory locations: counter high (TCNT1H) containing
the upper eight bits of the counter, and Counter Low (TCNT1L) containing the lower eight
bits. The TCNT1H Register can only be indirectly accessed by the CPU. When the CPU does an
access to the TCNT1H I/O location, the CPU accesses the High byte temporary register
(TEMP). The temporary register is updated with the TCNT1H value when the TCNT1L is read,
and TCNT1H is updated with the temporary register value when TCNT1L is written. This allows
the CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data
bus. It is important to notice that there are special cases of writing to the TCNT1 Register when
the counter is counting that will give unpredictable results. The special cases are described in
the sections where they are of importance.
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT1). The clkT1 can be generated from an external or internal clock source,
selected by the clock select bits (CS12:0). When no clock source is selected (CS12:0 = 0) the
timer is stopped. However, the TCNT1 value can be accessed by the CPU, independent of
whether clkT1 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the Waveform Generation mode bits
(WGM13:0) located in the Timer/Counter Control Registers A and B (TCCR1A and TCCR1B).
There are close connections between how the counter behaves (counts) and how waveforms
are generated on the Output Compare Outputs OC1x. For more details about advanced counting
sequences and waveform generation, see “Modes of Operation” on page 87.
The Timer/Counter Overflow (TOV1) fLag is set according to the mode of operation selected by
the WGM13:0 bits. TOV1 can be used for generating a CPU interrupt.
Input Capture Unit The Timer/Counter incorporates an Input Capture unit that can capture external events and give
them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple
events, can be applied via the ICP1 pin or alternatively, via the Analog Comparator unit.
TEMP (8-bit)
DATA BUS (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit) Control Logic
count
clear
direction
TOVn
(Int. Req.)
Clock Select
TOP BOTTOM
Tn Edge
Detector
( From Prescaler )
clkTn82
2486AA–AVR–02/2013
ATmega8(L)
The time-stamps can then be used to calculate frequency, duty-cycle, and other features of the
signal applied. Alternatively the time-stamps can be used for creating a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 34. The elements of
the block diagram that are not directly a part of the Input Capture unit are gray shaded. The
small “n” in register and bit names indicates the Timer/Counter number.
Figure 34. Input Capture Unit Block Diagram
When a change of the logic level (an event) occurs on the Input Capture Pin (ICP1), alternatively
on the Analog Comparator Output (ACO), and this change confirms to the setting of the edge
detector, a capture will be triggered. When a capture is triggered, the 16-bit value of the counter
(TCNT1) is written to the Input Capture Register (ICR1). The Input Capture Flag (ICF1) is set at
the same system clock as the TCNT1 value is copied into ICR1 Register. If enabled (TICIE1 =
1), the Input Capture Flag generates an Input Capture interrupt. The ICF1 Flag is automatically
cleared when the interrupt is executed. Alternatively the ICF1 Flag can be cleared by software
by writing a logical one to its I/O bit location.
Reading the 16-bit value in the Input Capture Register (ICR1) is done by first reading the Low
byte (ICR1L) and then the High byte (ICR1H). When the Low byte is read the High byte is copied
into the High byte temporary register (TEMP). When the CPU reads the ICR1H I/O location it will
access the TEMP Register.
The ICR1 Register can only be written when using a Waveform Generation mode that utilizes
the ICR1 Register for defining the counter’s TOP value. In these cases the Waveform Generation
mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1
Register. When writing the ICR1 Register the High byte must be written to the ICR1H I/O location
before the Low byte is written to ICR1L.
For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 77.
Input Capture Pin
Source
The main trigger source for the Input Capture unit is the Input Capture Pin (ICP1). Timer/Counter
1 can alternatively use the Analog Comparator Output as trigger source for the Input Capture
ICFn (Int. Req.)
Analog
Comparator
WRITE ICRn (16-bit Register)
ICRnH (8-bit)
Noise
Canceler
ICPn
Edge
Detector
TEMP (8-bit)
DATA BUS (8-bit)
ICRnL (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
ACO* ACIC* ICNC ICES83
2486AA–AVR–02/2013
ATmega8(L)
unit. The Analog Comparator is selected as trigger source by setting the Analog Comparator
Input Capture (ACIC) bit in the Analog Comparator Control and Status Register (ACSR). Be
aware that changing trigger source can trigger a capture. The Input Capture Flag must therefore
be cleared after the change.
Both the Input Capture Pin (ICP1) and the Analog Comparator Output (ACO) inputs are sampled
using the same technique as for the T1 pin (Figure 30 on page 73). The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four system clock cycles. Note that the input of the
noise canceler and edge detector is always enabled unless the Timer/Counter is set in a Waveform
Generation mode that uses ICR1 to define TOP.
An Input Capture can be triggered by software by controlling the port of the ICP1 pin.
Noise Canceler The noise canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC1) bit in
Timer/Counter Control Register B (TCCR1B). When enabled the noise canceler introduces additional
four system clock cycles of delay from a change applied to the input, to the update of the
ICR1 Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
Using the Input
Capture Unit
The main challenge when using the Input Capture unit is to assign enough processor capacity
for handling the incoming events. The time between two events is critical. If the processor has
not read the captured value in the ICR1 Register before the next event occurs, the ICR1 will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture interrupt, the ICR1 Register should be read as early in the interrupt
handler routine as possible. Even though the Input Capture interrupt has relatively high
priority, the maximum interrupt response time is dependent on the maximum number of clock
cycles it takes to handle any of the other interrupt requests.
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is
actively changed during operation, is not recommended.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensing must be done as early as possible after the ICR1
Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the clearing of the ICF1 Flag is not required (if an interrupt handler is used).
Output Compare
Units
The 16-bit comparator continuously compares TCNT1 with the Output Compare Register
(OCR1x). If TCNT equals OCR1x the comparator signals a match. A match will set the Output
Compare Flag (OCF1x) at the next timer clock cycle. If enabled (OCIE1x = 1), the Output Compare
Flag generates an Output Compare interrupt. The OCF1x Flag is automatically cleared
when the interrupt is executed. Alternatively the OCF1x Flag can be cleared by software by writing
a logical one to its I/O bit location. The waveform generator uses the match signal to
generate an output according to operating mode set by the Waveform Generation mode
(WGM13:0) bits and Compare Output mode (COM1x1:0) bits. The TOP and BOTTOM signals
are used by the waveform generator for handling the special cases of the extreme values in
some modes of operation (see “Modes of Operation” on page 87).
A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (that
is counter resolution). In addition to the counter resolution, the TOP value defines the period
time for waveforms generated by the waveform generator.84
2486AA–AVR–02/2013
ATmega8(L)
Figure 35 shows a block diagram of the Output Compare unit. The small “n” in the register and
bit names indicates the device number (n = 1 for Timer/Counter 1), and the “x” indicates Output
Compare unit (A/B). The elements of the block diagram that are not directly a part of the Output
Compare unit are gray shaded.
Figure 35. Output Compare Unit, Block Diagram
The OCR1x Register is double buffered when using any of the twelve Pulse Width Modulation
(PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double
buffering is disabled. The double buffering synchronizes the update of the OCR1x Compare
Register to either TOP or BOTTOM of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR1x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR1x Buffer Register, and if double buffering is disabled
the CPU will access the OCR1x directly. The content of the OCR1x (Buffer or Compare)
Register is only changed by a write operation (the Timer/Counter does not update this register
automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the High byte
temporary register (TEMP). However, it is a good practice to read the Low byte first as when
accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Register
since the compare of all 16-bit is done continuously. The High byte (OCR1xH) has to be
written first. When the High byte I/O location is written by the CPU, the TEMP Register will be
updated by the value written. Then when the Low byte (OCR1xL) is written to the lower eight
bits, the High byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x Compare
Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 77.
OCFnx (Int.Req.)
= (16-bit Comparator )
OCRnx Buffer (16-bit Register)
OCRnxH Buf. (8-bit)
OCnx
TEMP (8-bit)
DATA BUS (8-bit)
OCRnxL Buf. (8-bit)
TCNTn (16-bit Counter)
TCNTnH (8-bit) TCNTnL (8-bit)
WGMn3:0 COMnx1:0
OCRnx (16-bit Register)
OCRnxH (8-bit) OCRnxL (8-bit)
Waveform Generator
TOP
BOTTOM85
2486AA–AVR–02/2013
ATmega8(L)
Force Output
Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC1x) bit. Forcing Compare Match will not set the
OCF1x Flag or reload/clear the timer, but the OC1x pin will be updated as if a real Compare
Match had occurred (the COM1x1:0 bits settings define whether the OC1x pin is set, cleared or
toggled).
Compare Match
Blocking by TCNT1
Write
All CPU writes to the TCNT1 Register will block any Compare Match that occurs in the next timer
clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the
same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled.
Using the Output
Compare Unit
Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT1 when using any of the Output Compare
channels, independent of whether the Timer/Counter is running or not. If the value written to
TCNT1 equals the OCR1x value, the Compare Match will be missed, resulting in incorrect waveform
generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP
values. The Compare Match for the TOP will be ignored and the counter will continue to
0xFFFF. Similarly, do not write the TCNT1 value equal to BOTTOM when the counter is
downcounting.
The setup of the OC1x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC1x value is to use the Force Output Compare
(FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COM1x1:0 bits are not double buffered together with the compare value.
Changing the COM1x1:0 bits will take effect immediately.
Compare Match
Output Unit
The Compare Output mode (COM1x1:0) bits have two functions. The waveform generator uses
the COM1x1:0 bits for defining the Output Compare (OC1x) state at the next Compare Match.
Secondly the COM1x1:0 bits control the OC1x pin output source. Figure 36 on page 86 shows a
simplified schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers, I/O
bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control
Registers (DDR and PORT) that are affected by the COM1x1:0 bits are shown. When referring
to the OC1x state, the reference is for the internal OC1x Register, not the OC1x pin. If a System
Reset occur, the OC1x Register is reset to “0”.86
2486AA–AVR–02/2013
ATmega8(L)
Figure 36. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC1x) from the waveform
generator if either of the COM1x1:0 bits are set. However, the OC1x pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC1x pin (DDR_OC1x) must be set as output before the OC1x value is visible
on the pin. The port override function is generally independent of the Waveform Generation
mode, but there are some exceptions. Refer to Table 36 on page 96, Table 37 on page 96 and
Table 38 on page 97 for details.
The design of the Output Compare Pin logic allows initialization of the OC1x state before the
output is enabled. Note that some COM1x1:0 bit settings are reserved for certain modes of operation.
See “16-bit Timer/Counter Register Description” on page 96.
The COM1x1:0 bits have no effect on the Input Capture unit.
PORT
DDR
D Q
D Q
OCnx
OCnx Pin
D Q Waveform
Generator
COMnx1
COMnx0
0
1
DATABUS
FOCnx
clkI/O87
2486AA–AVR–02/2013
ATmega8(L)
Compare Output Mode
and Waveform
Generation
The waveform generator uses the COM1x1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM1x1:0 = 0 tells the waveform generator that no action on the
OC1x Register is to be performed on the next Compare Match. For compare output actions in
the non-PWM modes refer to Table 36 on page 96. For fast PWM mode refer to Table 37 on
page 96, and for phase correct and phase and frequency correct PWM refer to Table 38 on page
97.
A change of the COM1x1:0 bits state will have effect at the first Compare Match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC1x strobe bits.
Modes of
Operation
The mode of operation (that is, the behavior of the Timer/Counter and the Output Compare pins)
is defined by the combination of the Waveform Generation mode (WGM13:0) and Compare Output
mode (COM1x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM1x1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM1x1:0 bits control whether the output should be set, cleared or toggle at a Compare
Match. See “Compare Match Output Unit” on page 85.
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 94.
Normal Mode The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the
BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOV1) will be set in
the same timer clock cycle as the TCNT1 becomes zero. The TOV1 Flag in this case behaves
like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow
interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be
written anytime.
The Input Capture unit is easy to use in Normal mode. However, observe that the maximum
interval between the external events must not exceed the resolution of the counter. If the interval
between events are too long, the timer overflow interrupt or the prescaler must be used to
extend the resolution for the capture unit.
The Output Compare units can be used to generate interrupts at some given time. Using the
Output Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
Clear Timer on
Compare Match (CTC)
Mode
In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register
are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when
the counter value (TCNT1) matches either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 =
12). The OCR1A or ICR1 define the top value for the counter, hence also its resolution. This
mode allows greater control of the Compare Match output frequency. It also simplifies the operation
of counting external events.
The timing diagram for the CTC mode is shown in Figure 37 on page 88. The counter value
(TCNT1) increases until a Compare Match occurs with either OCR1A or ICR1, and then counter
(TCNT1) is cleared.88
2486AA–AVR–02/2013
ATmega8(L)
Figure 37. CTC Mode, Timing Diagram
An interrupt can be generated at each time the counter value reaches the TOP value by either
using the OCF1A or ICF1 Flag according to the register used to define the TOP value. If the
interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However,
changing the TOP to a value close to BOTTOM when the counter is running with none or a
low prescaler value must be done with care since the CTC mode does not have the double buffering
feature. If the new value written to OCR1A or ICR1 is lower than the current value of
TCNT1, the counter will miss the Compare Match. The counter will then have to count to its maximum
value (0xFFFF) and wrap around starting at 0x0000 before the Compare Match can occur.
In many cases this feature is not desirable. An alternative will then be to use the fast PWM mode
using OCR1A for defining TOP (WGM13:0 = 15) since the OCR1A then will be double buffered.
For generating a waveform output in CTC mode, the OC1A output can be set to toggle its logical
level on each Compare Match by setting the Compare Output mode bits to toggle mode
(COM1A1:0 = 1). The OC1A value will not be visible on the port pin unless the data direction for
the pin is set to output (DDR_OC1A = 1). The waveform generated will have a maximum frequency
of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). The waveform frequency is
defined by the following equation:
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x0000.
Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5, 6, 7, 14, or 15) provides a
high frequency PWM waveform generation option. The fast PWM differs from the other PWM
options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts
from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared
on the Compare Match between TCNT1 and OCR1x, and set at BOTTOM. In inverting Compare
Output mode output is set on Compare Match and cleared at BOTTOM. Due to the single-slope
operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct
and phase and frequency correct PWM modes that use dual-slope operation. This high
frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC
applications. High frequency allows physically small sized external components (coils, capacitors),
hence reduces total system cost.
The PWM resolution for fast PWM can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either ICR1
or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the
TCNTn
OCnA
(Toggle)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4
(COMnA1:0 = 1)
f
OCnA
f
clk_I/O
2 N 1 + OCRnA = --------------------------------------------------89
2486AA–AVR–02/2013
ATmega8(L)
maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be
calculated by using the following equation:
In fast PWM mode the counter is incremented until the counter value matches either one of the
fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 =
14), or the value in OCR1A (WGM13:0 = 15). The counter is then cleared at the following timer
clock cycle. The timing diagram for the fast PWM mode is shown in Figure 38. The figure shows
fast PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing
diagram shown as a histogram for illustrating the single-slope operation. The diagram includes
non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes
represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set
when a Compare Match occurs.
Figure 38. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. In addition
the OCF1A or ICF1 Flag is set at the same timer clock cycle as TOV1 is set when either OCR1A
or ICR1 is used for defining the TOP value. If one of the interrupts are enabled, the interrupt handler
routine can be used for updating the TOP and compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a Compare Match will never occur between the TCNT1 and the OCR1x.
Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCR1x Registers are written.
The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP
value. The ICR1 Register is not double buffered. This means that if ICR1 is changed to a low
value when the counter is running with none or a low prescaler value, there is a risk that the new
ICR1 value written is lower than the current value of TCNT1. The result will then be that the
counter will miss the Compare Match at the TOP value. The counter will then have to count to
the MAX value (0xFFFF) and wrap around starting at 0x0000 before the Compare Match can
occur. The OCR1A Register, however, is double buffered. This feature allows the OCR1A I/O
location to be written anytime. When the OCR1A I/O location is written the value written will be
put into the OCR1A Buffer Register. The OCR1A Compare Register will then be updated with
the value in the Buffer Register at the next timer clock cycle the TCNT1 matches TOP. The
update is done at the same timer clock cycle as the TCNT1 is cleared and the TOV1 Flag is set.
RFPWM
log TOP + 1
log 2 = -----------------------------------
TCNTn
OCRnx / TOP Update
and TOVn Interrupt Flag
Set and OCnA Interrupt
Flag Set or ICFn
Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4 5 6 7 8
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)90
2486AA–AVR–02/2013
ATmega8(L)
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using
ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However,
if the base PWM frequency is actively changed (by changing the TOP value), using the OCR1A
as TOP is clearly a better choice due to its double buffer feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins.
Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM1x1:0 to 3. See Table 37 on page 96. The actual OC1x
value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at
the Compare Match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register at
the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the output
will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCR1x equal to TOP
will result in a constant high or low output (depending on the polarity of the output set by the
COM1x1:0 bits).
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC1A to toggle its logical level on each Compare Match (COM1A1:0 = 1). This applies only
if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have
a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). This feature is
similar to the OC1A toggle in CTC mode, except the double buffer feature of the Output Compare
unit is enabled in the fast PWM mode.
Phase Correct PWM
Mode
The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1, 2, 3,
10, or 11) provides a high resolution phase correct PWM waveform generation option. The
phase correct PWM mode is, like the phase and frequency correct PWM mode, based on a dualslope
operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from
TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is
cleared on the Compare Match between TCNT1 and OCR1x while upcounting, and set on the
Compare Match while downcounting. In inverting Output Compare mode, the operation is
inverted. The dual-slope operation has lower maximum operation frequency than single slope
operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes
are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode can be fixed to 8-bit, 9-bit, or 10-bit, or
defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set
to 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution
in bits can be calculated by using the following equation:
In phase correct PWM mode the counter is incremented until the counter value matches either
one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1
(WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counter has then reached the
TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock
cycle. The timing diagram for the phase correct PWM mode is shown on Figure 39 on page 91.
The figure shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The
TCNT1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operaf
OCnxPWM
f
clk_I/O
N 1 + TOP = -----------------------------------
RPCPWM
log TOP + 1
log 2 = -----------------------------------91
2486AA–AVR–02/2013
ATmega8(L)
tion. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line
marks on the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The
OC1x Interrupt Flag will be set when a Compare Match occurs.
Figure 39. Phase Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM. When
either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set accordingly
at the same timer clock cycle as the OCR1x Registers are updated with the double buffer
value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter
reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a Compare Match will never occur between the TCNT1 and the OCR1x.
Note that when using fixed TOP values, the unused bits are masked to zero when any of the
OCR1x Registers are written. As the third period shown in Figure 39 illustrates, changing the
TOP actively while the Timer/Counter is running in the Phase Correct mode can result in an
unsymmetrical output. The reason for this can be found in the time of update of the OCR1x Register.
Since the OCR1x update occurs at TOP, the PWM period starts and ends at TOP. This
implies that the length of the falling slope is determined by the previous TOP value, while the
length of the rising slope is determined by the new TOP value. When these two values differ the
two slopes of the period will differ in length. The difference in length gives the unsymmetrical
result on the output.
It is recommended to use the Phase and Frequency Correct mode instead of the Phase Correct
mode when changing the TOP value while the Timer/Counter is running. When using a static
TOP value there are practically no differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the
OC1x pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COM1x1:0 to 3. See Table 38 on page 97. The
actual OC1x value will only be visible on the port pin if the data direction for the port pin is set as
output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register
at the Compare Match between OCR1x and TCNT1 when the counter increments, and
clearing (or setting) the OC1x Register at Compare Match between OCR1x and TCNT1 when
OCRnx / TOP Update and
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TOVn Interrupt Flag Set
(Interrupt on Bottom)
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)92
2486AA–AVR–02/2013
ATmega8(L)
the counter decrements. The PWM frequency for the output when using phase correct PWM can
be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
If OCR1A is used to define the TOP value (WMG13:0 = 11) and COM1A1:0 = 1, the OC1A output
will toggle with a 50% duty cycle.
Phase and Frequency
Correct PWM Mode
The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM
mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform
generation option. The phase and frequency correct PWM mode is, like the phase correct
PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM
(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the
Output Compare (OC1x) is cleared on the Compare Match between TCNT1 and OCR1x while
upcounting, and set on the Compare Match while downcounting. In inverting Compare Output
mode, the operation is inverted. The dual-slope operation gives a lower maximum operation frequency
compared to the single-slope operation. However, due to the symmetric feature of the
dual-slope PWM modes, these modes are preferred for motor control applications.
The main difference between the phase correct, and the phase and frequency correct PWM
mode is the time the OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 39
on page 91 and Figure 40 on page 93).
The PWM resolution for the phase and frequency correct PWM mode can be defined by either
ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and
the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can
be calculated using the following equation:
In phase and frequency correct PWM mode the counter is incremented until the counter value
matches either the value in ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The
counter has then reached the TOP and changes the count direction. The TCNT1 value will be
equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency
correct PWM mode is shown on Figure 40 on page 93. The figure shows phase and frequency
correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the
timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1
slopes represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will
be set when a Compare Match occurs.
f
OCnxPCPWM
f
clk_I/O
2 N TOP = ----------------------------
RPFCPWM
log TOP + 1
log 2 = -----------------------------------93
2486AA–AVR–02/2013
ATmega8(L)
Figure 40. Phase and Frequency Correct PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV1) is set at the same timer clock cycle as the OCR1x
Registers are updated with the double buffer value (at BOTTOM). When either OCR1A or ICR1
is used for defining the TOP value, the OC1A or ICF1 Flag set when TCNT1 has reached TOP.
The Interrupt Flags can then be used to generate an interrupt each time the counter reaches the
TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a Compare Match will never occur between the TCNT1 and the OCR1x.
As Figure 40 shows the output generated is, in contrast to the Phase Correct mode, symmetrical
in all periods. Since the OCR1x Registers are updated at BOTTOM, the length of the rising and
the falling slopes will always be equal. This gives symmetrical output pulses and is therefore frequency
correct.
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using
ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However,
if the base PWM frequency is actively changed by changing the TOP value, using the OCR1A as
TOP is clearly a better choice due to its double buffer feature.
In phase and frequency correct PWM mode, the compare units allow generation of PWM waveforms
on the OC1x pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and
an inverted PWM output can be generated by setting the COM1x1:0 to 3. See Table 38 on page
97. The actual OC1x value will only be visible on the port pin if the data direction for the port pin
is set as output (DDR_OC1x). The PWM waveform is generated by setting (or clearing) the
OC1x Register at the Compare Match between OCR1x and TCNT1 when the counter increments,
and clearing (or setting) the OC1x Register at Compare Match between OCR1x and
TCNT1 when the counter decrements. The PWM frequency for the output when using phase
and frequency correct PWM can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the
OCRnx / TOP Update and
TOVn Interrupt Flag Set
(Interrupt on Bottom)
OCnA Interrupt Flag Set or
ICFn Interrupt Flag Set
(Interrupt on TOP)
1 2 3 4
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
f
OCnxPFCPWM
f
clk_I/O
2 N TOP = ----------------------------94
2486AA–AVR–02/2013
ATmega8(L)
output will be continuously low and if set equal to TOP the output will be set to high for noninverted
PWM mode. For inverted PWM the output will have the opposite logic values.
If OCR1A is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output
will toggle with a 50% duty cycle.
Timer/Counter
Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT1) is therefore shown as a
clock enable signal in the following figures. The figures include information on when Interrupt
Flags are set, and when the OCR1x Register is updated with the OCR1x buffer value (only for
modes utilizing double buffering). Figure 41 shows a timing diagram for the setting of OCF1x.
Figure 41. Timer/Counter Timing Diagram, Setting of OCF1x, no Prescaling
Figure 42 shows the same timing data, but with the prescaler enabled.
Figure 42. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)
Figure 43 on page 95 shows the count sequence close to TOP in various modes. When using
phase and frequency correct PWM mode the OCR1x Register is updated at BOTTOM. The timclkTn
(clkI/O/1)
OCFnx
clkI/O
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)95
2486AA–AVR–02/2013
ATmega8(L)
ing diagrams will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1
and so on. The same renaming applies for modes that set the TOV1 Flag at BOTTOM.
Figure 43. Timer/Counter Timing Diagram, no Prescaling
Figure 44 shows the same timing data, but with the prescaler enabled.
Figure 44. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkTn
(clkI/O/1)
clkI/O
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(Update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx Value New OCRnx Value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)96
2486AA–AVR–02/2013
ATmega8(L)
16-bit
Timer/Counter
Register
Description
Timer/Counter 1
Control Register A –
TCCR1A
• Bit 7:6 – COM1A1:0: Compare Output Mode for channel A
• Bit 5:4 – COM1B1:0: Compare Output Mode for channel B
The COM1A1:0 and COM1B1:0 control the Output Compare Pins (OC1A and OC1B respectively)
behavior. If one or both of the COM1A1:0 bits are written to one, the OC1A output
overrides the normal port functionality of the I/O pin it is connected to. If one or both of the
COM1B1:0 bit are written to one, the OC1B output overrides the normal port functionality of the
I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding
to the OC1A or OC1B pin must be set in order to enable the output driver.
When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is dependent
of the WGM13:0 bits setting. Table 36 shows the COM1x1:0 bit functionality when the
WGM13:0 bits are set to a normal or a CTC mode (non-PWM).
Table 37 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the fast PWM
mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. In
this case the Compare Match is ignored, but the set or clear is done at BOTTOM. See “Fast
PWM Mode” on page 88 for more details
Bit 7 6 5 4 3 2 1 0
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 TCCR1A
Read/Write R/W R/W R/W R/W W W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 36. Compare Output Mode, Non-PWM
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 Toggle OC1A/OC1B on Compare Match
1 0 Clear OC1A/OC1B on Compare Match (Set output to low level)
1 1 Set OC1A/OC1B on Compare Match (Set output to high level)
Table 37. Compare Output Mode, Fast PWM(1)
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 WGM13:0 = 15: Toggle OC1A on Compare Match, OC1B
disconnected (normal port operation). For all other WGM1
settings, normal port operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at
BOTTOM, (non-inverting mode)
1 1 Set OC1A/OC1B on Compare Match, clear OC1A/OC1B at
BOTTOM, (inverting mode)97
2486AA–AVR–02/2013
ATmega8(L)
Table 38 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to the phase correct
or the phase and frequency correct, PWM mode.
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. See
“Phase Correct PWM Mode” on page 90 for more details
• Bit 3 – FOC1A: Force Output Compare for channel A
• Bit 2 – FOC1B: Force Output Compare for channel B
The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM mode.
However, for ensuring compatibility with future devices, these bits must be set to zero when
TCCR1A is written when operating in a PWM mode. When writing a logical one to the
FOC1A/FOC1B bit, an immediate Compare Match is forced on the waveform generation unit.
The OC1A/OC1B output is changed according to its COM1x1:0 bits setting. Note that the
FOC1A/FOC1B bits are implemented as strobes. Therefore it is the value present in the
COM1x1:0 bits that determine the effect of the forced compare.
A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear Timer
on Compare Match (CTC) mode using OCR1A as TOP.
The FOC1A/FOC1B bits are always read as zero.
• Bit 1:0 – WGM11:0: Waveform Generation Mode
Combined with the WGM13:2 bits found in the TCCR1B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 39. Modes of operation supported by the Timer/Counter
unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and three types
of Pulse Width Modulation (PWM) modes (see “Modes of Operation” on page 87).
Table 38. Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM(1)
COM1A1/
COM1B1
COM1A0/
COM1B0 Description
0 0 Normal port operation, OC1A/OC1B disconnected.
0 1 WGM13:0 = 9 or 14: Toggle OC1A on Compare Match, OC1B
disconnected (normal port operation). For all other WGM1
settings, normal port operation, OC1A/OC1B disconnected.
1 0 Clear OC1A/OC1B on Compare Match when up-counting. Set
OC1A/OC1B on Compare Match when downcounting.
1 1 Set OC1A/OC1B on Compare Match when up-counting. Clear
OC1A/OC1B on Compare Match when downcounting.
Table 39. Waveform Generation Mode Bit Description
Mode WGM13
WGM12
(CTC1)
WGM11
(PWM11)
WGM10
(PWM10)
Timer/Counter Mode of
Operation(1) TOP
Update of
OCR1x
TOV1 Flag
Set on
0 0 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM
3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCR1A Immediate MAX
5 0 1 0 1 Fast PWM, 8-bit 0x00FF BOTTOM TOP
6 0 1 1 0 Fast PWM, 9-bit 0x01FF BOTTOM TOP98
2486AA–AVR–02/2013
ATmega8(L)
Note: 1. The CTC1 and PWM11:0 bit definition names are obsolete. Use the WGM12:0 definitions. However, the functionality and
location of these bits are compatible with previous versions of the timer
Timer/Counter 1
Control Register B –
TCCR1B
• Bit 7 – ICNC1: Input Capture Noise Canceler
Setting this bit (to one) activates the Input Capture Noise Canceler. When the noise canceler is
activated, the input from the Input Capture Pin (ICP1) is filtered. The filter function requires four
successive equal valued samples of the ICP1 pin for changing its output. The Input Capture is
therefore delayed by four Oscillator cycles when the noise canceler is enabled.
• Bit 6 – ICES1: Input Capture Edge Select
This bit selects which edge on the Input Capture Pin (ICP1) that is used to trigger a capture
event. When the ICES1 bit is written to zero, a falling (negative) edge is used as trigger, and
when the ICES1 bit is written to one, a rising (positive) edge will trigger the capture.
When a capture is triggered according to the ICES1 setting, the counter value is copied into the
Input Capture Register (ICR1). The event will also set the Input Capture Flag (ICF1), and this
can be used to cause an Input Capture Interrupt, if this interrupt is enabled.
When the ICR1 is used as TOP value (see description of the WGM13:0 bits located in the
TCCR1A and the TCCR1B Register), the ICP1 is disconnected and consequently the Input Capture
function is disabled.
• Bit 5 – Reserved Bit
This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be
written to zero when TCCR1B is written.
• Bit 4:3 – WGM13:2: Waveform Generation Mode
See TCCR1A Register description.
• Bit 2:0 – CS12:0: Clock Select
The three clock select bits select the clock source to be used by the Timer/Counter, see Figure
41 on page 94 and Figure 42 on page 94.
7 0 1 1 1 Fast PWM, 10-bit 0x03FF BOTTOM TOP
8 1 0 0 0 PWM, Phase and Frequency Correct ICR1 BOTTOM BOTTOM
9 1 0 0 1 PWM, Phase and Frequency Correct OCR1A BOTTOM BOTTOM
10 1 0 1 0 PWM, Phase Correct ICR1 TOP BOTTOM
11 1 0 1 1 PWM, Phase Correct OCR1A TOP BOTTOM
12 1 1 0 0 CTC ICR1 Immediate MAX
13 1 1 0 1 (Reserved) – – –
14 1 1 1 0 Fast PWM ICR1 BOTTOM TOP
15 1 1 1 1 Fast PWM OCR1A BOTTOM TOP
Table 39. Waveform Generation Mode Bit Description (Continued)
Mode WGM13
WGM12
(CTC1)
WGM11
(PWM11)
WGM10
(PWM10)
Timer/Counter Mode of
Operation(1) TOP
Update of
OCR1x
TOV1 Flag
Set on
Bit 7 6 5 4 3 2 1 0
ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 TCCR1B
Read/Write R/W R/W R R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 099
2486AA–AVR–02/2013
ATmega8(L)
If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
Timer/Counter 1 –
TCNT1H and TCNT1L
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct
access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To
ensure that both the high and Low bytes are read and written simultaneously when the CPU
accesses these registers, the access is performed using an 8-bit temporary High byte Register
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit
Registers” on page 77.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing a Compare
Match between TCNT1 and one of the OCR1x Registers.
Writing to the TCNT1 Register blocks (removes) the Compare Match on the following timer clock
for all compare units.
Output Compare
Register 1 A –
OCR1AH and OCR1AL
Output Compare
Register 1 B –
OCR1BH and OCR1BL
Table 40. Clock Select Bit Description
CS12 CS11 CS10 Description
0 0 0 No clock source. (Timer/Counter stopped)
0 0 1 clkI/O/1 (No prescaling)
0 1 0 clkI/O/8 (From prescaler)
0 1 1 clkI/O/64 (From prescaler)
1 0 0 clkI/O/256 (From prescaler)
1 0 1 clkI/O/1024 (From prescaler)
1 1 0 External clock source on T1 pin. Clock on falling edge
1 1 1 External clock source on T1 pin. Clock on rising edge
Bit 7 6 5 4 3 2 1 0
TCNT1[15:8] TCNT1H
TCNT1[7:0] TCNT1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1A[15:8] OCR1AH
OCR1A[7:0] OCR1AL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1B[15:8] OCR1BH
OCR1B[7:0] OCR1BL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0100
2486AA–AVR–02/2013
ATmega8(L)
The Output Compare Registers contain a 16-bit value that is continuously compared with the
counter value (TCNT1). A match can be used to generate an Output Compare Interrupt, or to
generate a waveform output on the OC1x pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and Low bytes
are written simultaneously when the CPU writes to these registers, the access is performed
using an 8-bit temporary High byte Register (TEMP). This temporary register is shared by all the
other 16-bit registers. See “Accessing 16-bit Registers” on page 77.
Input Capture Register
1 – ICR1H and ICR1L
The Input Capture is updated with the counter (TCNT1) value each time an event occurs on the
ICP1 pin (or optionally on the Analog Comparator Output for Timer/Counter1). The Input Capture
can be used for defining the counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and Low bytes are read
simultaneously when the CPU accesses these registers, the access is performed using an 8-bit
temporary High byte Register (TEMP). This temporary register is shared by all the other 16-bit
registers. See “Accessing 16-bit Registers” on page 77.
Timer/Counter
Interrupt Mask
Register – TIMSK(1)
Note: 1. This register contains interrupt control bits for several Timer/Counters, but only Timer1 bits are
described in this section. The remaining bits are described in their respective timer sections
• Bit 5 – TICIE1: Timer/Counter1, Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Input Capture Interrupt is enabled. The corresponding Interrupt
Vector (see “Interrupts” on page 46) is executed when the ICF1 Flag, located in TIFR, is set.
• Bit 4 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Output Compare A match interrupt is enabled. The corresponding
Interrupt Vector (see “Interrupts” on page 46) is executed when the OCF1A Flag, located in
TIFR, is set.
• Bit 3 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Output Compare B match interrupt is enabled. The corresponding
Interrupt Vector (see “Interrupts” on page 46) is executed when the OCF1B Flag, located in
TIFR, is set.
• Bit 2 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Counter1 Overflow Interrupt is enabled. The corresponding Interrupt Vector
(see “Interrupts” on page 46) is executed when the TOV1 Flag, located in TIFR, is set.
Bit 7 6 5 4 3 2 1 0
ICR1[15:8] ICR1H
ICR1[7:0] ICR1L
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0101
2486AA–AVR–02/2013
ATmega8(L)
Timer/Counter
Interrupt Flag Register
– TIFR(1)
Note: 1. This register contains flag bits for several Timer/Counters, but only Timer1 bits are described
in this section. The remaining bits are described in their respective timer sections
• Bit 5 – ICF1: Timer/Counter1, Input Capture Flag
This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register
(ICR1) is set by the WGM13:0 to be used as the TOP value, the ICF1 Flag is set when the counter
reaches the TOP value.
ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively,
ICF1 can be cleared by writing a logic one to its bit location.
• Bit 4 – OCF1A: Timer/Counter1, Output Compare A Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output
Compare Register A (OCR1A).
Note that a Forced Output Compare (FOC1A) strobe will not set the OCF1A Flag.
OCF1A is automatically cleared when the Output Compare Match A Interrupt Vector is executed.
Alternatively, OCF1A can be cleared by writing a logic one to its bit location.
• Bit 3 – OCF1B: Timer/Counter1, Output Compare B Match Flag
This flag is set in the timer clock cycle after the counter (TCNT1) value matches the Output
Compare Register B (OCR1B).
Note that a Forced Output Compare (FOC1B) strobe will not set the OCF1B Flag.
OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed.
Alternatively, OCF1B can be cleared by writing a logic one to its bit location.
• Bit 2 – TOV1: Timer/Counter1, Overflow Flag
The setting of this flag is dependent of the WGM13:0 bits setting. In normal and CTC modes, the
TOV1 Flag is set when the timer overflows. Refer to Table 39 on page 97 for the TOV1 Flag
behavior when using another WGM13:0 bit setting.
TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed.
Alternatively, TOV1 can be cleared by writing a logic one to its bit location.
Bit 7 6 5 4 3 2 1 0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0102
2486AA–AVR–02/2013
ATmega8(L)
8-bit
Timer/Counter2
with PWM and
Asynchronous
Operation
Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. The main
features are:
• Single Channel Counter
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, phase Correct Pulse Width Modulator (PWM)
• Frequency Generator
• 10-bit Clock Prescaler
• Overflow and Compare Match Interrupt Sources (TOV2 and OCF2)
• Allows Clocking from External 32kHz Watch Crystal Independent of the I/O Clock
Overview A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 45. For the actual placement
of I/O pins, refer to “Pin Configurations” on page 2. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations
are listed in the “8-bit Timer/Counter Register Description” on page 114.
Figure 45. 8-bit Timer/Counter Block Diagram
Timer/Counter
DATA BUS
=
TCNTn
Waveform
Generation OCn
= 0
Control Logic
= 0xFF
BOTTOM TOP
count
clear
direction
TOVn
(Int. Req.)
OCn
(Int. Req.)
Synchronization Unit
OCRn
TCCRn
ASSRn
Status Flags
clkI/O
clkASY
Synchronized Status Flags
asynchronous Mode
Select (ASn)
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkTn
clkI/O103
2486AA–AVR–02/2013
ATmega8(L)
Registers The Timer/Counter (TCNT2) and Output Compare Register (OCR2) are 8-bit registers. Interrupt
request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag Register (TIFR).
All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and
TIMSK are not shown in the figure since these registers are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from
the TOSC1/2 pins, as detailed later in this section. The asynchronous operation is controlled by
the Asynchronous Status Register (ASSR). The Clock Select logic block controls which clock
source the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive
when no clock source is selected. The output from the clock select logic is referred to as the
timer clock (clkT2).
The double buffered Output Compare Register (OCR2) is compared with the Timer/Counter
value at all times. The result of the compare can be used by the waveform generator to generate
a PWM or variable frequency output on the Output Compare Pin (OC2). For details, see “Output
Compare Unit” on page 105. The Compare Match event will also set the Compare Flag (OCF2)
which can be used to generate an Output Compare interrupt request.
Definitions Many register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 2. However, when using the register or bit
defines in a program, the precise form must be used (that is, TCNT2 for accessing
Timer/Counter2 counter value and so on).
The definitions in Table 41 are also used extensively throughout the document.
Timer/Counter
Clock Sources
The Timer/Counter can be clocked by an internal synchronous or an external asynchronous
clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2
bit in the ASSR Register is written to logic one, the clock source is taken from the Timer/Counter
Oscillator connected to TOSC1 and TOSC2. For details on asynchronous operation, see “Asynchronous
Status Register – ASSR” on page 117. For details on clock sources and prescaler, see
“Timer/Counter Prescaler” on page 120.
Table 41. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00).
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR2 Register. The assignment is dependent
on the mode of operation.104
2486AA–AVR–02/2013
ATmega8(L)
Counter Unit The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
46 shows a block diagram of the counter and its surrounding environment.
Figure 46. Counter Unit Block Diagram
Signal description (internal signals):
count Increment or decrement TCNT2 by 1
direction Selects between increment and decrement
clear Clear TCNT2 (set all bits to zero)
clkT2 Timer/Counter clock
TOP Signalizes that TCNT2 has reached maximum value
BOTTOM Signalizes that TCNT2 has reached minimum value (zero)
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source,
selected by the clock select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the
timer is stopped. However, the TCNT2 value can be accessed by the CPU, regardless of
whether clkT2 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in
the Timer/Counter Control Register (TCCR2). There are close connections between how the
counter behaves (counts) and how waveforms are generated on the Output Compare Output
OC2. For more details about advanced counting sequences and waveform generation, see
“Modes of Operation” on page 108.
The Timer/Counter Overflow (TOV2) Flag is set according to the mode of operation selected by
the WGM21:0 bits. TOV2 can be used for generating a CPU interrupt.
DATA BUS
TCNTn Control Logic
count
TOVn
(Int. Req.)
BOTTOM TOP
direction
clear
TOSC1
T/C
Oscillator
TOSC2
Prescaler
clkI/O
clk Tn105
2486AA–AVR–02/2013
ATmega8(L)
Output Compare
Unit
The 8-bit comparator continuously compares TCNT2 with the Output Compare Register
(OCR2). Whenever TCNT2 equals OCR2, the comparator signals a match. A match will set the
Output Compare Flag (OCF2) at the next timer clock cycle. If enabled (OCIE2 = 1), the Output
Compare Flag generates an Output Compare interrupt. The OCF2 Flag is automatically cleared
when the interrupt is executed. Alternatively, the OCF2 Flag can be cleared by software by writing
a logical one to its I/O bit location. The waveform generator uses the match signal to
generate an output according to operating mode set by the WGM21:0 bits and Compare Output
mode (COM21:0) bits. The max and bottom signals are used by the waveform generator for handling
the special cases of the extreme values in some modes of operation (see “Modes of
Operation” on page 108).
Figure 47 shows a block diagram of the Output Compare unit.
Figure 47. Output Compare Unit, Block Diagram
The OCR2 Register is double buffered when using any of the Pulse Width Modulation (PWM)
modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double buffering
is disabled. The double buffering synchronizes the update of the OCR2 Compare Register
to either top or bottom of the counting sequence. The synchronization prevents the occurrence
of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR2 Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR2 Buffer Register, and if double buffering is disabled
the CPU will access the OCR2 directly.
OCFn (Int. Req.)
= (8-bit Comparator )
OCRn
OCxy
DATA BUS
TCNTn
WGMn1:0
Waveform Generator
TOP
FOCn
COMn1:0
BOTTOM106
2486AA–AVR–02/2013
ATmega8(L)
Force Output
Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC2) bit. Forcing Compare Match will not set the
OCF2 Flag or reload/clear the timer, but the OC2 pin will be updated as if a real Compare Match
had occurred (the COM21:0 bits settings define whether the OC2 pin is set, cleared or toggled).
Compare Match
Blocking by TCNT2
Write
All CPU write operations to the TCNT2 Register will block any Compare Match that occurs in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR2 to be initialized
to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is
enabled.
Using the Output
Compare Unit
Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT2 when using the Output Compare channel,
independently of whether the Timer/Counter is running or not. If the value written to TCNT2
equals the OCR2 value, the Compare Match will be missed, resulting in incorrect waveform generation.
Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is
downcounting.
The setup of the OC2 should be performed before setting the Data Direction Register for the port
pin to output. The easiest way of setting the OC2 value is to use the Force Output Compare
(FOC2) strobe bit in Normal mode. The OC2 Register keeps its value even when changing
between waveform generation modes.
Be aware that the COM21:0 bits are not double buffered together with the compare value.
Changing the COM21:0 bits will take effect immediately.107
2486AA–AVR–02/2013
ATmega8(L)
Compare Match
Output Unit
The Compare Output mode (COM21:0) bits have two functions. The waveform generator uses
the COM21:0 bits for defining the Output Compare (OC2) state at the next Compare Match.
Also, the COM21:0 bits control the OC2 pin output source. Figure 48 shows a simplified schematic
of the logic affected by the COM21:0 bit setting. The I/O Registers, I/O bits, and I/O pins in
the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and
PORT) that are affected by the COM21:0 bits are shown. When referring to the OC2 state, the
reference is for the internal OC2 Register, not the OC2 pin.
Figure 48. Compare Match Output Unit, Schematic
The general I/O port function is overridden by the Output Compare (OC2) from the waveform
generator if either of the COM21:0 bits are set. However, the OC2 pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register
bit for the OC2 pin (DDR_OC2) must be set as output before the OC2 value is visible on the
pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare Pin logic allows initialization of the OC2 state before the output
is enabled. Note that some COM21:0 bit settings are reserved for certain modes of
operation. See “8-bit Timer/Counter Register Description” on page 114.
PORT
DDR
D Q
D Q
OCn
OCn Pin
D Q Waveform
Generator
COMn1
COMn0
0
1
DATABUS
FOCn
clkI/O108
2486AA–AVR–02/2013
ATmega8(L)
Compare Output Mode
and Waveform
Generation
The Waveform Generator uses the COM21:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM21:0 = 0 tells the waveform generator that no action on the OC2
Register is to be performed on the next Compare Match. For compare output actions in the nonPWM
modes refer to Table 43 on page 115. For fast PWM mode, refer to Table 44 on page 115,
and for phase correct PWM refer to Table 45 on page 116.
A change of the COM21:0 bits state will have effect at the first Compare Match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC2 strobe bits.
Modes of
Operation
The mode of operation (that is, the behavior of the Timer/Counter and the Output Compare pins)
is defined by the combination of the Waveform Generation mode (WGM21:0) and Compare Output
mode (COM21:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM21:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM21:0 bits control whether the output should be set, cleared, or toggled at a Compare
Match (see “Compare Match Output Unit” on page 107).
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 112.
Normal Mode The simplest mode of operation is the Normal mode (WGM21:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same
timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV2 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare unit can be used to generate interrupts at some given time. Using the Output
Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.109
2486AA–AVR–02/2013
ATmega8(L)
Clear Timer on
Compare Match (CTC)
Mode
In Clear Timer on Compare or CTC mode (WGM21:0 = 2), the OCR2 Register is used to manipulate
the counter resolution. In CTC mode the counter is cleared to zero when the counter value
(TCNT2) matches the OCR2. The OCR2 defines the top value for the counter, hence also its
resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies
the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 49. The counter value (TCNT2)
increases until a Compare Match occurs between TCNT2 and OCR2, and then counter (TCNT2)
is cleared.
Figure 49. CTC Mode, Timing Diagram
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF2 Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the
TOP value. However, changing the TOP to a value close to BOTTOM when the counter is running
with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR2 is lower than the current
value of TCNT2, the counter will miss the Compare Match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can
occur.
For generating a waveform output in CTC mode, the OC2 output can be set to toggle its logical
level on each Compare Match by setting the Compare Output mode bits to toggle mode
(COM21:0 = 1). The OC2 value will not be visible on the port pin unless the data direction for the
pin is set to output. The waveform generated will have a maximum frequency of fOC2 = fclk_I/O/2
when OCR2 is set to zero (0x00). The waveform frequency is defined by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
As for the Normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
TCNTn
OCn
(Toggle)
OCn Interrupt Flag Set
Period 1 2 3 4
(COMn1:0 = 1)
f
OCn
f
clk_I/O
2 N 1 + OCRn = ----------------------------------------------110
2486AA–AVR–02/2013
ATmega8(L)
Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM21:0 = 3) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope
operation. The counter counts from BOTTOM to MAX then restarts from BOTTOM. In
non-inverting Compare Output mode, the Output Compare (OC2) is cleared on the Compare
Match between TCNT2 and OCR2, and set at BOTTOM. In inverting Compare Output mode, the
output is set on Compare Match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that uses dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the MAX value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
PWM mode is shown in Figure 50. The TCNT2 value is in the timing diagram shown as a histogram
for illustrating the single-slope operation. The diagram includes non-inverted and inverted
PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare
matches between OCR2 and TCNT2.
Figure 50. Fast PWM Mode, Timing Diagram
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches MAX. If the interrupt
is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2 pin. Setting
the COM21:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output can
be generated by setting the COM21:0 to 3 (see Table 44 on page 115). The actual OC2 value
will only be visible on the port pin if the data direction for the port pin is set as output. The PWM
waveform is generated by setting (or clearing) the OC2 Register at the Compare Match between
OCR2 and TCNT2, and clearing (or setting) the OC2 Register at the timer clock cycle the counter
is cleared (changes from MAX to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
TCNTn
OCRn Update
and
TOVn Interrupt Flag Set
Period 1 2 3
OCn
OCn
(COMn1:0 = 2)
(COMn1:0 = 3)
OCRn Interrupt Flag Set
4 5 6 7
f
OCnPWM
f
clk_I/O
N 256 = ------------------111
2486AA–AVR–02/2013
ATmega8(L)
The extreme values for the OCR2 Register represent special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR2 is set equal to BOTTOM, the output will be
a narrow spike for each MAX+1 timer clock cycle. Setting the OCR2 equal to MAX will result in a
constantly high or low output (depending on the polarity of the output set by the COM21:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC2 to toggle its logical level on each Compare Match (COM21:0 = 1). The waveform
generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2 is set to zero. This feature
is similar to the OC2 toggle in CTC mode, except the double buffer feature of the Output
Compare unit is enabled in the fast PWM mode.
Phase Correct PWM
Mode
The phase correct PWM mode (WGM21:0 = 1) provides a high resolution phase correct PWM
waveform generation option. The phase correct PWM mode is based on a dual-slope operation.
The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In noninverting
Compare Output mode, the Output Compare (OC2) is cleared on the Compare Match
between TCNT2 and OCR2 while upcounting, and set on the Compare Match while downcounting.
In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct
PWM mode the counter is incremented until the counter value matches MAX. When the counter
reaches MAX, it changes the count direction. The TCNT2 value will be equal to MAX for one
timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 51.
The TCNT2 value is in the timing diagram shown as a histogram for illustrating the dual-slope
operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal
line marks on the TCNT2 slopes represent compare matches between OCR2 and TCNT2.
Figure 51. Phase Correct PWM Mode, Timing Diagram
TOVn Interrupt Flag Set
OCn Interrupt Flag Set
1 2 3
TCNTn
Period
OCn
OCn
(COMn1:0 = 2)
(COMn1:0 = 3)
OCRn Update112
2486AA–AVR–02/2013
ATmega8(L)
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC2 pin. Setting the COM21:0 bits to 2 will produce a non-inverted PWM. An inverted PWM output
can be generated by setting the COM21:0 to 3 (see Table 45 on page 116). The actual OC2
value will only be visible on the port pin if the data direction for the port pin is set as output. The
PWM waveform is generated by clearing (or setting) the OC2 Register at the Compare Match
between OCR2 and TCNT2 when the counter increments, and setting (or clearing) the OC2
Register at Compare Match between OCR2 and TCNT2 when the counter decrements. The
PWM frequency for the output when using phase correct PWM can be calculated by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2 Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR2 is set equal to BOTTOM, the output
will be continuously low and if set equal to MAX the output will be continuously high for noninverted
PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 51 on page 111 OCn has a transition from high to low even
though there is no Compare Match. The point of this transition is to guarantee symmetry around
BOTTOM. There are two cases that give a transition without Compare Match:
• OCR2A changes its value from MAX, like in Figure 51 on page 111. When the OCR2A value
is MAX the OCn pin value is the same as the result of a down-counting Compare Match. To
ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result of
an up-counting Compare Match
• The timer starts counting from a value higher than the one in OCR2A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up
Timer/Counter
Timing Diagrams
The following figures show the Timer/Counter in Synchronous mode, and the timer clock (clkT2)
is therefore shown as a clock enable signal. In Asynchronous mode, clkI/O should be replaced by
the Timer/Counter Oscillator clock. The figures include information on when Interrupt Flags are
set. Figure 52 contains timing data for basic Timer/Counter operation. The figure shows the
count sequence close to the MAX value in all modes other than phase correct PWM mode.
Figure 52. Timer/Counter Timing Diagram, no Prescaling
f
OCnPCPWM
f
clk_I/O
N 510 = ------------------
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1113
2486AA–AVR–02/2013
ATmega8(L)
Figure 53 shows the same timing data, but with the prescaler enabled.
Figure 53. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
Figure 54 shows the setting of OCF2 in all modes except CTC mode.
Figure 54. Timer/Counter Timing Diagram, Setting of OCF2, with Prescaler (fclk_I/O/8)
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
OCFn
OCRn
TCNTn
OCRn Value
OCRn - 1 OCRn OCRn + 1 OCRn + 2
clkI/O
clkTn
(clkI/O/8)114
2486AA–AVR–02/2013
ATmega8(L)
Figure 55 shows the setting of OCF2 and the clearing of TCNT2 in CTC mode.
Figure 55. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Prescaler
(fclk_I/O/8)
8-bit
Timer/Counter
Register
Description
Timer/Counter Control
Register – TCCR2
• Bit 7 – FOC2: Force Output Compare
The FOC2 bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring
compatibility with future devices, this bit must be set to zero when TCCR2 is written when
operating in PWM mode. When writing a logical one to the FOC2 bit, an immediate Compare
Match is forced on the waveform generation unit. The OC2 output is changed according to its
COM21:0 bits setting. Note that the FOC2 bit is implemented as a strobe. Therefore it is the
value present in the COM21:0 bits that determines the effect of the forced compare.
A FOC2 strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2 as TOP.
The FOC2 bit is always read as zero.
• Bit 6:3 – WGM21:0: Waveform Generation Mode
These bits control the counting sequence of the counter, the source for the maximum (TOP)
counter value, and what type of waveform generation to be used. Modes of operation supported
by the Timer/Counter unit are: Normal mode, Clear Timer on Compare Match (CTC) mode, and
two types of Pulse Width Modulation (PWM) modes. See Table 42 on page 115 and “Modes of
Operation” on page 108.
OCFn
OCRn
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
Bit 7 6 5 4 3 2 1 0
FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20 TCCR2
Read/Write W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0115
2486AA–AVR–02/2013
ATmega8(L)
Note: 1. The CTC2 and PWM2 bit definition names are now obsolete. Use the WGM21:0 definitions.
However, the functionality and location of these bits are compatible with previous versions of
the timer
• Bit 5:4 – COM21:0: Compare Match Output Mode
These bits control the Output Compare Pin (OC2) behavior. If one or both of the COM21:0 bits
are set, the OC2 output overrides the normal port functionality of the I/O pin it is connected to.
However, note that the Data Direction Register (DDR) bit corresponding to OC2 pin must be set
in order to enable the output driver.
When OC2 is connected to the pin, the function of the COM21:0 bits depends on the WGM21:0
bit setting.
Table 43 shows the COM21:0 bit functionality when the WGM21:0 bits are set to a normal or
CTC mode (non-PWM).
Table 44 shows the COM21:0 bit functionality when the WGM21:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, the Compare
Match is ignored, but the set or clear is done at BOTTOM. See “Fast PWM Mode” on page 110
for more details
Table 42. Waveform Generation Mode Bit Description
Mode
WGM21
(CTC2)
WGM20
(PWM2)
Timer/Counter Mode
of Operation(1) TOP
Update of
OCR2
TOV2 Flag
Set
0 0 0 Normal 0xFF Immediate MAX
1 0 1 PWM, Phase Correct 0xFF TOP BOTTOM
2 1 0 CTC OCR2 Immediate MAX
3 1 1 Fast PWM 0xFF BOTTOM MAX
Table 43. Compare Output Mode, Non-PWM Mode
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected
0 1 Toggle OC2 on Compare Match
1 0 Clear OC2 on Compare Match
1 1 Set OC2 on Compare Match
Table 44. Compare Output Mode, Fast PWM Mode(1)
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected
0 1 Reserved
1 0 Clear OC2 on Compare Match, set OC2 at BOTTOM,
(non-inverting mode)
1 1 Set OC2 on Compare Match, clear OC2 at BOTTOM,
(inverting mode)116
2486AA–AVR–02/2013
ATmega8(L)
Table 45 shows the COM21:0 bit functionality when the WGM21:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2 equals TOP and COM21 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on page
111 for more details
• Bit 2:0 – CS22:0: Clock Select
The three clock select bits select the clock source to be used by the Timer/Counter, see Table
46.
Timer/Counter
Register – TCNT2
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes) the Compare
Match on the following timer clock. Modifying the counter (TCNT2) while the counter is running,
introduces a risk of missing a Compare Match between TCNT2 and the OCR2 Register.
Output Compare
Register – OCR2
The Output Compare Register contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2 pin.
Table 45. Compare Output Mode, Phase Correct PWM Mode(1)
COM21 COM20 Description
0 0 Normal port operation, OC2 disconnected
0 1 Reserved
1 0 Clear OC2 on Compare Match when up-counting. Set OC2 on Compare
Match when downcounting
1 1 Set OC2 on Compare Match when up-counting. Clear OC2 on Compare
Match when downcounting
Table 46. Clock Select Bit Description
CS22 CS21 CS20 Description
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clkT2S/(No prescaling)
0 1 0 clkT2S/8 (From prescaler)
0 1 1 clkT2S/32 (From prescaler)
1 0 0 clkT2S/64 (From prescaler)
1 0 1 clkT2S/128 (From prescaler)
1 1 0 clkT2S/256 (From prescaler)
1 1 1 clkT2S/1024 (From prescaler)
Bit 7 6 5 4 3 2 1 0
TCNT2[7:0] TCNT2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR2[7:0] OCR2
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0117
2486AA–AVR–02/2013
ATmega8(L)
Asynchronous
Operation of the
Timer/Counter
Asynchronous Status
Register – ASSR
• Bit 3 – AS2: Asynchronous Timer/Counter2
When AS2 is written to zero, Timer/Counter 2 is clocked from the I/O clock, clkI/O. When AS2 is
written to one, Timer/Counter 2 is clocked from a crystal Oscillator connected to the Timer Oscillator
1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2, and
TCCR2 might be corrupted.
• Bit 2 – TCN2UB: Timer/Counter2 Update Busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set.
When TCNT2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value.
• Bit 1 – OCR2UB: Output Compare Register2 Update Busy
When Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomes set.
When OCR2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2 is ready to be updated with a new value.
• Bit 0 – TCR2UB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomes set.
When TCCR2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that TCCR2 is ready to be updated with a new value.
If a write is performed to any of the three Timer/Counter2 Registers while its update busy flag is
set, the updated value might get corrupted and cause an unintentional interrupt to occur.
The mechanisms for reading TCNT2, OCR2, and TCCR2 are different. When reading TCNT2,
the actual timer value is read. When reading OCR2 or TCCR2, the value in the temporary storage
register is read.
Asynchronous
Operation of
Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken.
• Warning: When switching between asynchronous and synchronous clocking of
Timer/Counter2, the Timer Registers TCNT2, OCR2, and TCCR2 might be corrupted. A
safe procedure for switching clock source is:
1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2
2. Select clock source by setting AS2 as appropriate
3. Write new values to TCNT2, OCR2, and TCCR2
4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, and TCR2UB
5. Clear the Timer/Counter2 Interrupt Flags
6. Enable interrupts, if needed
• The Oscillator is optimized for use with a 32.768kHz watch crystal. Applying an external
clock to the TOSC1 pin may result in incorrect Timer/Counter2 operation. The CPU main
clock frequency must be more than four times the Oscillator frequency
• When writing to one of the registers TCNT2, OCR2, or TCCR2, the value is transferred to a
temporary register, and latched after two positive edges on TOSC1. The user should not
Bit 7 6 5 4 3 2 1 0
– – – – AS2 TCN2UB OCR2UB TCR2UB ASSR
Read/Write R R R R R/W R R R
Initial Value 0 0 0 0 0 0 0 0118
2486AA–AVR–02/2013
ATmega8(L)
write a new value before the contents of the temporary register have been transferred to its
destination. Each of the three mentioned registers have their individual temporary register,
which means that, for example, writing to TCNT2 does not disturb an OCR2 write in
progress. To detect that a transfer to the destination register has taken place, the
Asynchronous Status Register – ASSR has been implemented
• When entering Power-save mode after having written to TCNT2, OCR2, or TCCR2, the user
must wait until the written register has been updated if Timer/Counter2 is used to wake up
the device. Otherwise, the MCU will enter sleep mode before the changes are effective. This
is particularly important if the Output Compare2 interrupt is used to wake up the device,
since the Output Compare function is disabled during writing to OCR2 or TCNT2. If the write
cycle is not finished, and the MCU enters sleep mode before the OCR2UB bit returns to
zero, the device will never receive a Compare Match interrupt, and the MCU will not wake up
• If Timer/Counter2 is used to wake the device up from Power-save mode, precautions must
be taken if the user wants to re-enter one of these modes: The interrupt logic needs one
TOSC1 cycle to be reset. If the time between wake-up and re-entering sleep mode is less
than one TOSC1 cycle, the interrupt will not occur, and the device will fail to wake up. If the
user is in doubt whether the time before re-entering Power-save or Extended Standby mode
is sufficient, the following algorithm can be used to ensure that one TOSC1 cycle has
elapsed:
1. Write a value to TCCR2, TCNT2, or OCR2
2. Wait until the corresponding Update Busy Flag in ASSR returns to zero
3. Enter Power-save or Extended Standby mode
• When the asynchronous operation is selected, the 32.768kHZ Oscillator for Timer/Counter2
is always running, except in Power-down and Standby modes. After a Power-up Reset or
Wake-up from Power-down or Standby mode, the user should be aware of the fact that this
Oscillator might take as long as one second to stabilize. The user is advised to wait for at
least one second before using Timer/Counter2 after Power-up or Wake-up from Power-down
or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost
after a wake-up from Power-down or Standby mode due to unstable clock signal upon startup,
no matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin
• Description of wake up from Power-save or Extended Standby mode when the timer is
clocked asynchronously: When the interrupt condition is met, the wake up process is started
on the following cycle of the timer clock, that is, the timer is always advanced by at least one
before the processor can read the counter value. After wake-up, the MCU is halted for four
cycles, it executes the interrupt routine, and resumes execution from the instruction
following SLEEP
• Reading of the TCNT2 Register shortly after wake-up from Power-save may give an
incorrect result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2
must be done through a register synchronized to the internal I/O clock domain.
Synchronization takes place for every rising TOSC1 edge. When waking up from Powersave
mode, and the I/O clock (clkI/O) again becomes active, TCNT2 will read as the previous
value (before entering sleep) until the next rising TOSC1 edge. The phase of the TOSC
clock after waking up from Power-save mode is essentially unpredictable, as it depends on
the wake-up time. The recommended procedure for reading TCNT2 is thus as follows:
1. Write any value to either of the registers OCR2 or TCCR2
2. Wait for the corresponding Update Busy Flag to be cleared
3. Read TCNT2119
2486AA–AVR–02/2013
ATmega8(L)
• During asynchronous operation, the synchronization of the Interrupt Flags for the
asynchronous timer takes three processor cycles plus one timer cycle. The timer is therefore
advanced by at least one before the processor can read the timer value causing the setting
of the Interrupt Flag. The Output Compare Pin is changed on the timer clock and is not
synchronized to the processor clock
Timer/Counter
Interrupt Mask
Register – TIMSK
• Bit 7 – OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable
When the OCIE2 bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match interrupt is enabled. The corresponding interrupt is executed if
a Compare Match in Timer/Counter2 occurs (that is, when the OCF2 bit is set in the
Timer/Counter Interrupt Flag Register – TIFR).
• Bit 6 – TOIE2: Timer/Counter2 Overflow Interrupt Enable
When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter2 occurs (that is, when the TOV2 bit is set in the Timer/Counter Interrupt
Flag Register – TIFR).
Timer/Counter
Interrupt Flag Register
– TIFR
• Bit 7 – OCF2: Output Compare Flag 2
The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2 and the
data in OCR2 – Output Compare Register2. OCF2 is cleared by hardware when executing the
corresponding interrupt Handling Vector. Alternatively, OCF2 is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIE2 (Timer/Counter2 Compare Match Interrupt Enable), and
OCF2 are set (one), the Timer/Counter2 Compare Match Interrupt is executed.
• Bit 6 – TOV2: Timer/Counter2 Overflow Flag
The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware
when executing the corresponding interrupt Handling Vector. Alternatively, TOV2 is
cleared by writing a logic one to the flag. When the SREG I-bit, TOIE2 (Timer/Counter2 Overflow
Interrupt Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In
PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00.
Bit 7 6 5 4 3 2 1 0
OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 TIMSK
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 TIFR
Read/Write R/W R/W R/W R/W R/W R/W R R/W
Initial Value 0 0 0 0 0 0 0 0120
2486AA–AVR–02/2013
ATmega8(L)
Timer/Counter
Prescaler
Figure 56. Prescaler for Timer/Counter2
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main
system I/O clock clkI/O. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously
clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter
(RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port B. A crystal can
then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock
source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal. Applying
an external clock source to TOSC1 is not recommended.
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64,
clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected.
Setting the PSR2 bit in SFIOR resets the prescaler. This allows the user to operate with a predictable
prescaler.
Special Function IO
Register – SFIOR
• Bit 1 – PSR2: Prescaler Reset Timer/Counter2
When this bit is written to one, the Timer/Counter2 prescaler will be reset. The bit will be cleared
by hardware after the operation is performed. Writing a zero to this bit will have no effect. This bit
will always be read as zero if Timer/Counter2 is clocked by the internal CPU clock. If this bit is
written when Timer/Counter2 is operating in Asynchronous mode, the bit will remain one until
the prescaler has been reset.
10-BIT T/C PRESCALER
TIMER/COUNTER2 CLOCK SOURCE
clkI/O clkT2S
TOSC1
AS2
CS20
CS21
CS22
clkT2S/8
clkT2S/64
clkT2S/128
clkT2S/1024
clkT2S/256
clkT2S/32
0 PSR2
Clear
clkT2
Bit 7 6 5 4 3 2 1 0
– – – – ACME PUD PSR2 PSR10 SFIOR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0121
2486AA–AVR–02/2013
ATmega8(L)
Serial
Peripheral
Interface – SPI
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
ATmega8 and peripheral devices or between several AVR devices. The ATmega8 SPI includes
the following features:
• Full-duplex, Three-wire Synchronous Data Transfer
• Master or Slave Operation
• LSB First or MSB First Data Transfer
• Seven Programmable Bit Rates
• End of Transmission Interrupt Flag
• Write Collision Flag Protection
• Wake-up from Idle Mode
• Double Speed (CK/2) Master SPI Mode
Figure 57. SPI Block Diagram(1)
Note: 1. Refer to “Pin Configurations” on page 2, and Table 22 on page 58 for SPI pin placement
The interconnection between Master and Slave CPUs with SPI is shown in Figure 58 on page
122. The system consists of two Shift Registers, and a Master clock generator. The SPI Master
initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave.
Master and Slave prepare the data to be sent in their respective Shift Registers, and the Master
generates the required clock pulses on the SCK line to interchange data. Data is always shifted
from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the
Master In – Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave
by pulling high the Slave Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This
must be handled by user software before communication can start. When this is done, writing a SPI2X SPI2X
DIVIDER
/2/4/8/16/32/64/128122
2486AA–AVR–02/2013
ATmega8(L)
byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight
bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of
Transmission Flag (SPIF). If the SPI interrupt enable bit (SPIE) in the SPCR Register is set, an
interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be
kept in the Buffer Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin
until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission
Flag, SPIF is set. If the SPI interrupt enable bit, SPIE, in the SPCR Register is set, an interrupt is
requested. The Slave may continue to place new data to be sent into SPDR before reading the
incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 58. SPI Master-Slave Interconnection
The system is single buffered in the transmit direction and double buffered in the receive direction.
This means that bytes to be transmitted cannot be written to the SPI Data Register before
the entire shift cycle is completed. When receiving data, however, a received character must be
read from the SPI Data Register before the next character has been completely shifted in. Otherwise,
the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure
correct sampling of the clock signal, the minimum low and high periods should be:
Low period: longer than 2 CPU clock cycles
High period: longer than 2 CPU clock cycles
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 47. For more details on automatic port overrides, refer to “Alternate Port
Functions” on page 56.
Note: 1. See “Port B Pins Alternate Functions” on page 58 for a detailed description of how to define
the direction of the user defined SPI pins
Table 47. SPI Pin Overrides(1)
Pin Direction, Master SPI Direction, Slave SPI
MOSI User Defined Input
MISO Input User Defined
SCK User Defined Input
SS User Defined Input
MSB MASTER LSB
8 BIT SHIFT REGISTER
MSB SLAVE LSB
8 BIT SHIFT REGISTER
MISO
MOSI
SPI
CLOCK GENERATOR
SCK
SS
MISO
MOSI
SCK
SS
VCC
SHIFT
ENABLE123
2486AA–AVR–02/2013
ATmega8(L)
The following code examples show how to initialize the SPI as a Master and how to perform a
simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction
Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the
actual data direction bits for these pins. For example if MOSI is placed on pin PB5, replace
DD_MOSI with DDB5 and DDR_SPI with DDRB.
Note: 1. See “About Code Examples” on page 8
Assembly Code Example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi r17,(1<>8);
UBRRL = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSRB = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}141
2486AA–AVR–02/2013
ATmega8(L)
Receive Compete Flag
and Interrupt
The USART Receiver has one flag that indicates the Receiver state.
The Receive Complete (RXC) Flag indicates if there are unread data present in the receive buffer.
This flag is one when unread data exist in the receive buffer, and zero when the receive
buffer is empty (that is, does not contain any unread data). If the Receiver is disabled (RXEN =
0), the receive buffer will be flushed and consequently the RXC bit will become zero.
When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive
Complete Interrupt will be executed as long as the RXC Flag is set (provided that global interrupts
are enabled). When interrupt-driven data reception is used, the receive complete routine
must read the received data from UDR in order to clear the RXC Flag, otherwise a new interrupt
will occur once the interrupt routine terminates.
Receiver Error Flags The USART Receiver has three error flags: Frame Error (FE), Data OverRun (DOR) and Parity
Error (PE). All can be accessed by reading UCSRA. Common for the error flags is that they are
located in the receive buffer together with the frame for which they indicate the error status. Due
to the buffering of the error flags, the UCSRA must be read before the receive buffer (UDR),
since reading the UDR I/O location changes the buffer read location. Another equality for the
error flags is that they can not be altered by software doing a write to the flag location. However,
all flags must be set to zero when the UCSRA is written for upward compatibility of future
USART implementations. None of the error flags can generate interrupts.
The Frame Error (FE) Flag indicates the state of the first stop bit of the next readable frame
stored in the receive buffer. The FE Flag is zero when the stop bit was correctly read (as one),
and the FE Flag will be one when the stop bit was incorrect (zero). This flag can be used for
detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE Flag
is not affected by the setting of the USBS bit in UCSRC since the Receiver ignores all, except for
the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to
UCSRA.
The Data OverRun (DOR) Flag indicates data loss due to a Receiver buffer full condition. A Data
OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in
the Receive Shift Register, and a new start bit is detected. If the DOR Flag is set there was one
or more serial frame lost between the frame last read from UDR, and the next frame read from
UDR. For compatibility with future devices, always write this bit to zero when writing to UCSRA.
The DOR Flag is cleared when the frame received was successfully moved from the Shift Register
to the receive buffer.
The Parity Error (PE) Flag indicates that the next frame in the receive buffer had a parity error
when received. If parity check is not enabled the PE bit will always be read zero. For compatibility
with future devices, always set this bit to zero when writing to UCSRA. For more details see
“Parity Bit Calculation” on page 134 and “Parity Checker” .
Parity Checker The Parity Checker is active when the high USART Parity mode (UPM1) bit is set. Type of parity
check to be performed (odd or even) is selected by the UPM0 bit. When enabled, the Parity
Checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. The result of the check is stored in the receive buffer together
with the received data and stop bits. The Parity Error (PE) Flag can then be read by software to
check if the frame had a parity error.
The PE bit is set if the next character that can be read from the receive buffer had a parity error
when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid
until the receive buffer (UDR) is read.142
2486AA–AVR–02/2013
ATmega8(L)
Disabling the Receiver In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing
receptions will therefore be lost. When disabled (that is, the RXEN is set to zero) the Receiver
will no longer override the normal function of the RxD port pin. The Receiver buffer FIFO will be
flushed when the Receiver is disabled. Remaining data in the buffer will be lost
Flushing the Receive
Buffer
The Receiver buffer FIFO will be flushed when the Receiver is disabled (that is, the buffer will be
emptied of its contents). Unread data will be lost. If the buffer has to be flushed during normal
operation, due to for instance an error condition, read the UDR I/O location until the RXC Flag is
cleared. The following code example shows how to flush the receive buffer.
Note: 1. See “About Code Examples” on page 8
Asynchronous
Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data
reception. The clock recovery logic is used for synchronizing the internally generated baud rate
clock to the incoming asynchronous serial frames at the RxD pin. The data recovery logic samples
and low pass filters each incoming bit, thereby improving the noise immunity of the
Receiver. The asynchronous reception operational range depends on the accuracy of the internal
baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
Asynchronous Clock
Recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 65
illustrates the sampling process of the start bit of an incoming frame. The sample rate is 16 times
the baud rate for Normal mode, and eight times the baud rate for Double Speed mode. The horizontal
arrows illustrate the synchronization variation due to the sampling process. Note the
larger time variation when using the Double Speed mode (U2X = 1) of operation. Samples
denoted zero are samples done when the RxD line is idle (that is, no communication activity).
Figure 65. Start Bit Sampling
When the clock recovery logic detects a high (idle) to low (start) transition on the RxD line, the
start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in
Assembly Code Example(1)
USART_Flush:
sbis UCSRA, RXC
ret
in r16, UDR
rjmp USART_Flush
C Code Example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRA & (1< 2 CPU clock cycles for fck <12MHz, 3 CPU clock cycles for fck >=12MHz
High:> 2 CPU clock cycles for fck <12MHz, 3 CPU clock cycles for fck >=12MHz
Table 96. Pin Mapping Serial Programming
Symbol Pins I/O Description
MOSI PB3 I Serial data in
MISO PB4 O Serial data out
SCK PB5 I Serial clock
VCC
GND
XTAL1
SCK
MISO
MOSI
RESET
PB3
PB4
PB5
+2.7V - 5.5V
AVCC
+2.7V - 5.5V (2)231
2486AA–AVR–02/2013
ATmega8(L)
Serial Programming
Algorithm
When writing serial data to the ATmega8, data is clocked on the rising edge of SCK.
When reading data from the ATmega8, data is clocked on the falling edge of SCK. See Figure
113 on page 232 for timing details.
To program and verify the ATmega8 in the Serial Programming mode, the following sequence is
recommended (see four byte instruction formats in Table 98 on page 233):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
the programmer can not guarantee that SCK is held low during Power-up. In this
case, RESET must be given a positive pulse of at least two CPU clock cycles duration
after SCK has been set to “0”
2. Wait for at least 20ms and enable Serial Programming by sending the Programming
Enable serial instruction to pin MOSI
3. The Serial Programming instructions will not work if the communication is out of synchronization.
When in sync. the second byte (0x53), will echo back when issuing the third
byte of the Programming Enable instruction. Whether the echo is correct or not, all four
bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a
positive pulse and issue a new Programming Enable command
4. The Flash is programmed one page at a time. The page size is found in Table 89 on
page 218. The memory page is loaded one byte at a time by supplying the 5 LSB of the
address and data together with the Load Program memory Page instruction. To ensure
correct loading of the page, the data Low byte must be loaded before data High byte is
applied for a given address. The Program memory Page is stored by loading the Write
Program memory Page instruction with the 7MSB of the address. If polling is not used,
the user must wait at least tWD_FLASH before issuing the next page (see Table 97 on page
232).
Note: If other commands than polling (read) are applied before any write operation (FLASH,
EEPROM, Lock Bits, Fuses) is completed, it may result in incorrect programming
5. The EEPROM array is programmed one byte at a time by supplying the address and data
together with the appropriate Write instruction. An EEPROM memory location is first
automatically erased before new data is written. If polling is not used, the user must wait
at least tWD_EEPROM before issuing the next byte (see Table 97 on page 232). In a chip
erased device, no 0xFFs in the data file(s) need to be programmed
6. Any memory location can be verified by using the Read instruction which returns the content
at the selected address at serial output MISO
7. At the end of the programming session, RESET can be set high to commence normal
operation
8. Power-off sequence (if needed):
Set RESET to “1”
Turn VCC power off
Data Polling Flash When a page is being programmed into the Flash, reading an address location within the page
being programmed will give the value 0xFF. At the time the device is ready for a new page, the
programmed value will read correctly. This is used to determine when the next page can be written.
Note that the entire page is written simultaneously and any address within the page can be
used for polling. Data polling of the Flash will not work for the value 0xFF, so when programming
this value, the user will have to wait for at least tWD_FLASH before programming the next page. As
a chip-erased device contains 0xFF in all locations, programming of addresses that are meant to
contain 0xFF, can be skipped. See Table 97 on page 232 for tWD_FLASH value.232
2486AA–AVR–02/2013
ATmega8(L)
Data Polling EEPROM When a new byte has been written and is being programmed into EEPROM, reading the
address location being programmed will give the value 0xFF. At the time the device is ready for
a new byte, the programmed value will read correctly. This is used to determine when the next
byte can be written. This will not work for the value 0xFF, but the user should have the following
in mind: As a chip-erased device contains 0xFF in all locations, programming of addresses that
are meant to contain 0xFF, can be skipped. This does not apply if the EEPROM is Re-programmed
without chip-erasing the device. In this case, data polling cannot be used for the value
0xFF, and the user will have to wait at least tWD_EEPROM before programming the next byte. See
Table 97 for tWD_EEPROM value.
Figure 113. Serial Programming Waveforms
Table 97. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol Minimum Wait Delay
tWD_FUSE 4.5ms
tWD_FLASH 4.5ms
tWD_EEPROM 9.0ms
tWD_ERASE 9.0ms
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT233
2486AA–AVR–02/2013
ATmega8(L)
Note: a = address high bits
b = address low bits
H = 0 – Low byte, 1 – High byte
o = data out
i = data in
x = don’t care
Table 98. Serial Programming Instruction Set
Instruction
Instruction Format
Byte 1 Byte 2 Byte 3 Byte 4 Operation
Programming Enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable Serial Programming after
RESET goes low
Chip Erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip Erase EEPROM and Flash
Read Program Memory 0010 H000 0000 aaaa bbbb bbbb oooo oooo Read H (high or low) data o from
Program memory at word address
a:b
Load Program Memory
Page
0100 H000 0000 xxxx xxxb bbbb iiii iiii Write H (high or low) data i to
Program memory page at word
address b. Data Low byte must be
loaded before Data High byte is
applied within the same address
Write Program Memory
Page
0100 1100 0000 aaaa bbbx xxxx xxxx xxxx Write Program memory Page at
address a:b
Read EEPROM Memory 1010 0000 00xx xxxa bbbb bbbb oooo oooo Read data o from EEPROM
memory at address a:b
Write EEPROM Memory 1100 0000 00xx xxxa bbbb bbbb iiii iiii Write data i to EEPROM memory
at address a:b
Read Lock Bits 0101 1000 0000 0000 xxxx xxxx xxoo oooo Read Lock Bits. “0” = programmed,
“1” = unprogrammed. See Table
85 on page 215 for details
Write Lock Bits 1010 1100 111x xxxx xxxx xxxx 11ii iiii Write Lock Bits. Set bits = “0” to
program Lock Bits. See Table 85
on page 215 for details
Read Signature Byte 0011 0000 00xx xxxx xxxx xxbb oooo oooo Read Signature Byte o at address
b
Write Fuse Bits 1010 1100 1010 0000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram. See Table 88 on
page 217 for details
Write Fuse High Bits 1010 1100 1010 1000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram. See Table 87 on
page 216 for details
Read Fuse Bits 0101 0000 0000 0000 xxxx xxxx oooo oooo Read Fuse Bits. “0” = programmed,
“1” = unprogrammed. See Table
88 on page 217 for details
Read Fuse High Bits 0101 1000 0000 1000 xxxx xxxx oooo oooo Read Fuse high bits. “0” = programmed,
“1” = unprogrammed.
See Table 87 on page 216 for
details
Read Calibration Byte 0011 1000 00xx xxxx 0000 00bb oooo oooo Read Calibration Byte234
2486AA–AVR–02/2013
ATmega8(L)
SPI Serial
Programming
Characteristics
For characteristics of the SPI module, see “SPI Timing Characteristics” on page 239.235
2486AA–AVR–02/2013
ATmega8(L)
Electrical Characteristics – TA = -40°C to 85°C
Note: Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured
on the same process technology. Min and Max values will be available after the device is characterized.
DC Characteristics
Absolute Maximum Ratings*
Operating Temperature.................................. -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ................................................ 40.0mA
DC Current VCC and GND Pins................................. 300.0mA
TA = -40C to +85C, VCC = 2.7V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min Typ Max Units
VIL
Input Low Voltage except
XTAL1 and RESET pins VCC = 2.7V - 5.5V -0.5 0.2 VCC(1)
V
VIH
Input High Voltage except
XTAL1 and RESET pins VCC = 2.7V - 5.5V 0.6VCC(2) VCC + 0.5
VIL1
Input Low Voltage
XTAL1 pin
VCC = 2.7V - 5.5V -0.5 0.1VCC(1)
VIH1
Input High Voltage
XTAL 1 pin
VCC = 2.7V - 5.5V 0.8VCC(2) VCC + 0.5
VIL2
Input Low Voltage
RESET pin
VCC = 2.7V - 5.5V -0.5 0.2 VCC
VIH2
Input High Voltage
RESET pin
VCC = 2.7V - 5.5V 0.9VCC(2) VCC + 0.5
VIL3
Input Low Voltage
RESET pin as I/O VCC = 2.7V - 5.5V -0.5 0.2VCC
VIH3
Input High Voltage
RESET pin as I/O VCC = 2.7V - 5.5V 0.6VCC(2)
0.7VCC(2) VCC + 0.5
VOL
Output Low Voltage(3)
(Ports B,C,D)
I
OL = 20mA, VCC = 5V
IOL = 10mA, VCC = 3V
0.9
0.6
VOH
Output High Voltage(4)
(Ports B,C,D)
I
OH = -20mA, VCC = 5V
IOH = -10mA, VCC = 3V
4.2
2.2
IIL
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin low
(absolute value) 1
µA
I
IH
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin high
(absolute value) 1
RRST Reset Pull-up Resistor 30 80 k236
2486AA–AVR–02/2013
ATmega8(L)
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOL, for all ports, should not exceed 300mA.
2] The sum of all IOL, for ports C0 - C5 should not exceed 100mA.
3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition
4. Although each I/O port can source more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP, TQFP, and QFN/MLF Package:
1] The sum of all IOH, for all ports, should not exceed 300mA.
2] The sum of all IOH, for port C0 - C5, should not exceed 100mA.
3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 200mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition
5. Minimum VCC for Power-down is 2.5V
Rpu I/O Pin Pull-up Resistor 20 50 k
ICC
Power Supply Current
Active 4MHz, VCC = 3V
(ATmega8L) 3 5
mA
Active 8MHz, VCC = 5V
(ATmega8) 11 15
Idle 4MHz, VCC = 3V
(ATmega8L) 1 2
Idle 8MHz, VCC = 5V
(ATmega8) 4.5 7
Power-down mode(5) WDT enabled, VCC = 3V < 22 28
µA
WDT disabled, VCC = 3V < 1 3
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 40 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nA
tACPD
Analog Comparator
Propagation Delay
VCC = 2.7V
VCC = 5.0V
750
500 ns
TA = -40C to +85C, VCC = 2.7V to 5.5V (unless otherwise noted) (Continued)
Symbol Parameter Condition Min Typ Max Units237
2486AA–AVR–02/2013
ATmega8(L)
External Clock
Drive Waveforms
Figure 114. External Clock Drive Waveforms
External Clock
Drive
Notes: 1. R should be in the range 3k - 100k, and C should be at least 20pF. The C values given in
the table includes pin capacitance. This will vary with package type
2. The frequency will vary with package type and board layout
VIL1
VIH1
Table 99. External Clock Drive
Symbol Parameter
VCC = 2.7V to 5.5V VCC = 4.5V to 5.5V
Min Max Min Max Units
1/tCLCL Oscillator Frequency 0 8 0 16 MHz
tCLCL Clock Period 125 62.5
tCHCX High Time 50 25 ns
tCLCX Low Time 50 25
tCLCH Rise Time 1.6 0.5
s
tCHCL Fall Time 1.6 0.5
tCLCL
Change in period from one
clock cycle to the next 2 2%
Table 100. External RC Oscillator, Typical Frequencies
R [k]
(1) C [pF] f(2)
33 22 650kHz
10 22 2.0MHz238
2486AA–AVR–02/2013
ATmega8(L)
Two-wire Serial Interface Characteristics
Table 101 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega8 Two-wire Serial
Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 115 on page 239.
Notes: 1. In ATmega8, this parameter is characterized and not 100% tested
2. Required only for fSCL > 100kHz
3. Cb = capacitance of one bus line in pF
4. fCK = CPU clock frequency
Table 101. Two-wire Serial Bus Requirements
Symbol Parameter Condition Min Max Units
VIL Input Low-voltage -0.5 0.3VCC
V
VIH Input High-voltage 0.7VCC VCC + 0.5
Vhys(1) Hysteresis of Schmitt Trigger Inputs 0.05VCC(2) –
VOL(1) Output Low-voltage 3mA sink Current 0 0.4
tr
(1) Rise Time for both SDA and SCL 20 + 0.1Cb
(3)(2) 300
tof ns (1) Output Fall Time from VIHmin to VILmax 10pF < Cb < 400pF(3) 20 + 0.1Cb
(3)(2) 250
tSP(1) Spikes Suppressed by Input Filter 0 50(2)
Ii Input Current each I/O Pin 0.1VCC < Vi
< 0.9VCC -10 10 µA
Ci
(1) Capacitance for each I/O Pin – 10 pF
fSCL SCL Clock Frequency fCK(4) > max(16fSCL, 250kHz)(5) 0 400 kHz
Rp Value of Pull-up resistor
fSCL 100kHz
fSCL > 100kHz
tHD;STA Hold Time (repeated) START Condition
fSCL 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tLOW Low Period of the SCL Clock
fSCL 100kHz(6) 4.7 –
fSCL > 100kHz(7) 1.3 –
tHIGH High period of the SCL clock
fSCL 100kHz 4.0 –
fSCL > 100kHz 0.6 –
tSU;STA Set-up time for a repeated START condition
fSCL 100kHz 4.7 –
fSCL > 100kHz 0.6 –
tHD;DAT Data hold time
fSCL 100kHz 0 3.45
fSCL > 100kHz 0 0.9
tSU;DAT Data setup time
fSCL 100kHz 250 –
ns
fSCL > 100kHz 100 –
tSU;STO Setup time for STOP condition
fSCL 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tBUF
Bus free time between a STOP and START
condition
fSCL 100kHz 4.7 –
fSCL > 100kHz 1.3 –
VCC – 0.4V
3mA ---------------------------- 1000ns
Cb
-------------------
VCC – 0.4V
3mA ---------------------------- 300ns
Cb
----------------239
2486AA–AVR–02/2013
ATmega8(L)
5. This requirement applies to all ATmega8 Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial
Bus need only obey the general fSCL requirement
6. The actual low period generated by the ATmega8 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus fCK must be greater than
6MHz for the low time requirement to be strictly met at fSCL = 100kHz
7. The actual low period generated by the ATmega8 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement
will not be strictly met for fSCL > 308kHz when fCK = 8MHz. Still, ATmega8 devices connected to the bus may communicate at
full speed (400kHz) with other ATmega8 devices, as well as any other device with a proper tLOW acceptance margin
Figure 115. Two-wire Serial Bus Timing
SPI Timing
Characteristics
See Figure 116 on page 240 and Figure 117 on page 240 for details.
Note: 1. In SPI Programming mode the minimum SCK high/low period is:
- 2tCLCL for fCK < 12MHz
- 3tCLCL for fCK > 12MHz
t
SU;STA
t
LOW
t
HIGH
t
LOW
t
of
t
HD;STA t
HD;DAT t
SU;DAT t
SU;STO
t
BUF
SCL
SDA
t
r
Table 102. SPI Timing Parameters
Description Mode Min Typ Max
1 SCK period Master See Table 50 on
page 126
ns
2 SCK high/low Master 50% duty cycle
3 Rise/Fall time Master 3.6
4 Setup Master 10
5 Hold Master 10
6 Out to SCK Master 0.5 • tSCK
7 SCK to out Master 10
8 SCK to out high Master 10
9 SS low to out Slave 15
10 SCK period Slave 4 • tck
11 SCK high/low(1) Slave 2 • tck
12 Rise/Fall time Slave 1600
13 Setup Slave 10
14 Hold Slave 10
15 SCK to out Slave 15
16 SCK to SS high Slave 20
17 SS high to tri-state Slave 10
18 SS low to SCK Salve 2 • tck240
2486AA–AVR–02/2013
ATmega8(L)
Figure 116. SPI interface timing requirements (Master Mode)
Figure 117. SPI interface timing requirements (Slave Mode)
MOSI
(Data Output)
SCK
(CPOL = 1)
MISO
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
6 1
2 2
4 5 3
7 8
MISO
(Data Output)
SCK
(CPOL = 1)
MOSI
(Data Input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
10
11 11
13 14 12
15 17
9
X
16
18241
2486AA–AVR–02/2013
ATmega8(L)
ADC Characteristics
Notes: 1. Values are guidelines only
2. Minimum for AVCC is 2.7V
3. Maximum for AVCC is 5.5V
4. Maximum conversion time is 1/50kHz × 25 = 0.5ms
Table 103. ADC Characteristics
Symbol Parameter Condition Min(1) Typ(1) Max(1) Units
Resolution Single Ended Conversion 10 Bits
Absolute accuracy
(including INL, DNL,
Quantization Error, Gain,
and Offset Error)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1.75
LSB
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 1MHz
3
Integral Non-linearity (INL)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz 0.75
Differential Non-linearity
(DNL)
Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz 0.5
Gain Error Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1
Offset Error Single Ended Conversion
VREF = 4V, VCC = 4V
ADC clock = 200kHz
1
Conversion Time(4) Free Running Conversion 13 260 µs
Clock Frequency 50 1000 kHz
AVCC Analog Supply Voltage VCC - 0.3(2) VCC + 0.3(3)
V
VREF Reference Voltage 2.0 AVCC
VIN Input voltage GND VREF
Input bandwidth 38.5 kHz
VINT Internal Voltage Reference 2.3 2.56 2.9 V
RREF Reference Input Resistance 32 k
RAIN Analog Input Resistance 55 100 M242
2486AA–AVR–02/2013
ATmega8(L)
Electrical Characteristics – TA = -40°C to 105°C
Note: Typical values contained in this data sheet are based on simulations and characterization of other AVR microcontrollers manufactured
on the same process technology. Min and Max values will be available after the device is characterized.
Absolute Maximum Ratings*
Operating Temperature.................................. -55C to +125C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage Temperature ..................................... -65°C to +150°C
Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5V
Voltage on RESET with respect to Ground......-0.5V to +13.0V
Maximum Operating Voltage ............................................ 6.0V
DC Current per I/O Pin ............................................... 40.0 mA
DC Current VCC and GND Pins................................ 200.0 mA
DC Characteristics
TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted)
Symbol Parameter Condition Min Typ Max Units
VIL Input Low Voltage Except XTAL1 pin -0.5 0.2 VCC(1) V
VIL1 Input Low Voltage XTAL1 pin, External Clock Selected -0.5 0.1 VCC(1) V
VIH Input High Voltage Except XTAL1 and RESET pins 0.6 VCC(2) VCC + 0.5 V
VIH1 Input High Voltage XTAL1 pin, External Clock Selected 0.8 VCC(2) VCC + 0.5 V
VIH2 Input High Voltage RESET pin 0.9 VCC(2) VCC + 0.5 V
VOL
Output Low Voltage(3)
(Ports A,B,C,D)
I
OL = 20 mA, VCC = 5V
IOL = 10 mA, VCC = 3V
0.8
0.6
V
V
VOH
Output High Voltage(4)
(Ports A,B,C,D)
IOH = -20 mA, VCC = 5V
IOH = -10 mA, VCC = 3V
4.0
2.2
V
V
IIL
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin low
(absolute value) 3 µA
IIH
Input Leakage
Current I/O Pin
Vcc = 5.5V, pin high
(absolute value) 3 µA
RRST Reset Pull-up Resistor 30 80 k
Rpu I/O Pin Pull-up Resistor 20 50 k243
2486AA–AVR–02/2013
ATmega8(L)
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP Package:
1] The sum of all IOL, for all ports, should not exceed 400 mA.
2] The sum of all IOL, for ports C0 - C5 should not exceed 200 mA.
3] The sum of all IOL, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 100 mA.
TQFP and MLF Package:
1] The sum of all IOL, for all ports, should not exceed 400 mA.
2] The sum of all IOL, for ports C0 - C5, should not exceed 200 mA.
3] The sum of all IOL, for ports C6, D0 - D4, should not exceed 300 mA.
4] The sum of all IOL, for ports B0 - B7, D5 - D7, should not exceed 300 mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state
conditions (non-transient), the following must be observed:
PDIP Package:
1] The sum of all IOH, for all ports, should not exceed 400 mA.
2] The sum of all IOH, for port C0 - C5, should not exceed 100 mA.
3] The sum of all IOH, for ports B0 - B7, C6, D0 - D7 and XTAL2, should not exceed 100 mA.
TQFP and MLF Package:
1] The sum of all IOH, for all ports, should not exceed 400 mA.
2] The sum of all IOH, for ports C0 - C5, should not exceed 200 mA.
3] The sum of all IOH, for ports C6, D0 - D4, should not exceed 300 mA.
4] The sum of all IOH, for ports B0 - B7, D5 - D7, should not exceed 300 mA.
If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
5. Minimum VCC for Power-down is 2.5V.
I
CC
Power Supply Current
Active 4 MHz, VCC = 3V
(ATmega8L) 6 mA
Active 8 MHz, VCC = 5V
(ATmega8) 15 mA
Idle 4 MHz, VCC = 3V
(ATmega8L) 3 mA
Idle 8 MHz, VCC = 5V
(ATmega8) 8 mA
Power-down mode(5) WDT enabled, VCC = 3V 35 µA
WDT disabled, VCC = 3V 6 µA
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 20 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nA
tACPD
Analog Comparator
Propagation Delay
VCC = 2.7V
VCC = 5.0V
750
500 ns
DC Characteristics
TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted) (Continued)
Symbol Parameter Condition Min Typ Max Units244
2486AA–AVR–02/2013
ATmega8(L)
ATmega8
Typical
Characteristics
– TA = -40°C to 85°C
The following charts show typical behavior. These figures are not tested during manufacturing.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. A sine wave generator with Rail-to-Rail output is used as clock
source.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating
frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature.
The dominating factors are operating voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as:
CL × VCC × f
where CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O
pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to
function properly at frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer
enabled and Power-down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.
Active Supply Current Figure 118. Active Supply Current vs. Frequency (0.1MHz - 1.0MHz)
0
0.5
1
1.5
2
2.5
3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5V
5.0V
4.5V
3.3V
3.0V
2.7V
4.0V245
2486AA–AVR–02/2013
ATmega8(L)
Figure 119. Active Supply Current vs. Frequency (1MHz - 20MHz)
Figure 120. Active Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
0
5
10
15
20
25
30
0246 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5V
5.0V
4.5V
3.3V
2.7V
3.0V
0
2
4
6
8
10
12
14
16
18
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C246
2486AA–AVR–02/2013
ATmega8(L)
Figure 121. Active Supply Current vs. VCC (Internal RC Oscillator, 4MHz)
Figure 122. Active Supply Current vs. VCC (Internal RC Oscillator, 2MHz)
0
2
4
6
8
10
12
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
0
1
2
3
4
5
6
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C247
2486AA–AVR–02/2013
ATmega8(L)
Figure 123. Active Supply Current vs. VCC (Internal RC Oscillator, 1MHz)
Figure 124. Active Supply Current vs. VCC (32kHz External Oscillator)
0
0.5
1
1.5
2
2.5
3
3.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
25°C 85°C
-40°C
0
20
40
60
80
100
120
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C248
2486AA–AVR–02/2013
ATmega8(L)
Idle Supply Current Figure 125. Idle Supply Current vs. Frequency (0.1MHz - 1.0MHz)
Figure 126. Idle Supply Current vs. Frequency (1MHz - 20MHz)
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5V
4.5V
4.0V
3.3V
3.0V
2.7V
5.0V
0
2
4
6
8
10
12
14
0246 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5V
4.5V
4.0V
3.3V
3.0V
2.7V
5.0V249
2486AA–AVR–02/2013
ATmega8(L)
Figure 127. Idle Supply Current vs. VCC (Internal RC Oscillator, 8MHz)
Figure 128. Idle Supply Current vs. VCC (Internal RC Oscillator, 4MHz)
0
1
2
3
4
5
6
7
8
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
3.5
4
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C250
2486AA–AVR–02/2013
ATmega8(L)
Figure 129. Idle Supply Current vs. VCC (Internal RC Oscillator, 2MHz)
Figure 130. Idle Supply Current vs. VCC (Internal RC Oscillator, 1MHz)
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C251
2486AA–AVR–02/2013
ATmega8(L)
Figure 131. Idle Supply Current vs. VCC (32kHz External Oscillator)
Power-down Supply
Current
Figure 132. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
0
5
10
15
20
25
30
35
40
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C252
2486AA–AVR–02/2013
ATmega8(L)
Figure 133. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
Power-save Supply
Current
Figure 134. Power-save Supply Current vs. VCC (Watchdog Timer Disabled)
0
10
20
30
40
50
60
70
80
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C
0
5
10
15
20
25
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C253
2486AA–AVR–02/2013
ATmega8(L)
Standby Supply
Current
Figure 135. Standby Supply Current vs. VCC (455kHz Resonator, Watchdog Timer Disabled)
Figure 136. Standby Supply Current vs. VCC (1MHz Resonator, Watchdog Timer Disabled)
0
10
20
30
40
50
60
70
80
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
0
10
20
30
40
50
60
70
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)254
2486AA–AVR–02/2013
ATmega8(L)
Figure 137. Standby Supply Current vs. VCC (2MHz Resonator, Watchdog Timer Disabled)
Figure 138. Standby Supply Current vs. VCC (2MHz Xtal, Watchdog Timer Disabled)
0
10
20
30
40
50
60
70
80
90
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
0
10
20
30
40
50
60
70
80
90
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)255
2486AA–AVR–02/2013
ATmega8(L)
Figure 139. Standby Supply Current vs. VCC (4MHz Resonator, Watchdog Timer Disabled)
Figure 140. Standby Supply Current vs. VCC (4MHz Xtal, Watchdog Timer Disabled)
0
20
40
60
80
100
120
140
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
0
20
40
60
80
100
120
140
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)256
2486AA–AVR–02/2013
ATmega8(L)
Figure 141. Standby Supply Current vs. VCC (6MHz Resonator, Watchdog Timer Disabled)
Figure 142. Standby Supply Current vs. VCC (6MHz Xtal, Watchdog Timer Disabled)
0
20
40
60
80
100
120
140
160
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
0
20
40
60
80
100
120
140
160
180
200
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)257
2486AA–AVR–02/2013
ATmega8(L)
Pin Pull-up Figure 143. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
Figure 144. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
0
20
40
60
80
100
120
140
160
012 3 4 56
VOP (V)
IIO (µA)
85°C
25°C
-40°C
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5 3
VOP (V)
IIO (µA)
85°C 25°C
-40°C258
2486AA–AVR–02/2013
ATmega8(L)
Figure 145. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
Figure 146. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
0
20
40
60
80
100
012
VRESET (V)
IRESET (µA)
85°C
25°C
- 40°C
0
5
10
15
20
25
30
35
40
45
0 0.5 1 1.5 2 2.5
VRESET (V)
IRESET (µA)
85°C
25°C
-40°C259
2486AA–AVR–02/2013
ATmega8(L)
Pin Driver Strength Figure 147. I/O Pin Source Current vs. Output Voltage (VCC = 5V)
Figure 148. I/O Pin Source Current vs. Output Voltage (VCC = 2.7V)
0
10
20
30
40
50
60
70
80
VOH (V)
IOH (mA)
85°C
25°C
-40°C
0
5
10
15
20
25
30
0 0.5 1 1.5 2 2.5 3
VOH (V)
IOH (mA)
85°C
25°C
-40°C260
2486AA–AVR–02/2013
ATmega8(L)
Figure 149. I/O Pin Sink Current vs. Output Voltage (VCC = 5V)
Figure 150. I/O Pin Sink Current vs. Output Voltage (VCC = 2.7V)
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
5
10
15
20
25
30
35
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)
85°C
25°C
-40°C261
2486AA–AVR–02/2013
ATmega8(L)
Figure 151. Reset Pin as I/O – Pin Source Current vs. Output Voltage (VCC = 5V)
Figure 152. Reset Pin as I/O – Pin Source Current vs. Output Voltage (VCC = 2.7V)
0
0.5
1
1.5
2
2.5
3
3.5
4
2 2.5 3 3.5 4 4.5
VOH (V)
Current (mA)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
5
0 0.5 1 1.5 2 2.5
VOH (V)
Current (mA)
85°C
25°C -40°C262
2486AA–AVR–02/2013
ATmega8(L)
Figure 153. Reset Pin as I/O – Pin Sink Current vs. Output Voltage (VCC = 5V)
Figure 154. Reset Pin as I/O – Pin Sink Current vs. Output Voltage (VCC = 2.7V)
0
2
4
6
8
10
12
14
0 0.5 1 1.5 2 2.5
VOL (V)
Current (mA)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
0 0.5 1 1.5 2 2.5
VOL (V)
Current (mA)
85°C
25°C
-40°C263
2486AA–AVR–02/2013
ATmega8(L)
Pin Thresholds and
Hysteresis
Figure 155. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin Read as “1”)
Figure 156. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C264
2486AA–AVR–02/2013
ATmega8(L)
Figure 157. I/O Pin Input Hysteresis vs. VCC
Figure 158. Reset Pin as I/O – Input Threshold Voltage vs. VCC (VIH, I/O Pin Read as “1”)
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
3.5
4
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C265
2486AA–AVR–02/2013
ATmega8(L)
Figure 159. Reset Pin as I/O – Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
Figure 160. Reset Pin as I/O – Pin Hysteresis vs. VCC
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (V)
85°C
25°C
-40°C266
2486AA–AVR–02/2013
ATmega8(L)
Figure 161. Reset Input Threshold Voltage vs. VCC (VIH, Reset Pin Read as “1”)
Figure 162. Reset Input Threshold Voltage vs. VCC (VIL, Reset Pin Read as “0”)
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C267
2486AA–AVR–02/2013
ATmega8(L)
Figure 163. Reset Input Pin Hysteresis vs. VCC
Bod Thresholds and
Analog Comparator
Offset
Figure 164. BOD Thresholds vs. Temperature (BOD Level is 4.0V)
0
0.2
0.4
0.6
0.8
1
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input Hysteresis (V)
85°C
25°C
-40°C
3.7
3.8
3.9
4
4.1
4.2
4.3
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
Threshold (V)
Rising VCC
Falling VCC268
2486AA–AVR–02/2013
ATmega8(L)
Figure 165. BOD Thresholds vs. Temperature (BOD Level is 2.7V)
Figure 166. Bandgap Voltage vs. VCC
2.4
2.5
2.6
2.7
2.8
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
Threshold (V)
Rising VCC
Falling VCC
1.29
1.295
1.3
1.305
1.31
1.315
2.5 3 3.5 4 4.5 5 5.5
Vcc (V)
Bandgap Voltage (V)
-40°C
25°C
85°C269
2486AA–AVR–02/2013
ATmega8(L)
Figure 167. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 5V)
Figure 168. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 2.7V)
-0.006
-0.005
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Common Mode Voltage (V)
Comparator Offset Voltage (V)
85°C
25°C
-40°C
-0.005
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0 0.5 1 1.5 2 2.5 3
Common Mode Voltage (V)
Comparator Offset Voltage (V)
85°C
25°C
-40°C270
2486AA–AVR–02/2013
ATmega8(L)
Internal Oscillator
Speed
Figure 169. Watchdog Oscillator Frequency vs. VCC
Figure 170. Calibrated 8MHz RC Oscillator Frequency vs. Temperature
1100
1120
1140
1160
1180
1200
1220
1240
1260
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (kHz)
85°C
25°C
-40°C
6.5
6.7
6.9
7.1
7.3
7.5
7.7
7.9
8.1
8.3
8.5
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (MHz)
5.5V
2.7V
4.0V271
2486AA–AVR–02/2013
ATmega8(L)
Figure 171. Calibrated 8MHz RC Oscillator Frequency vs. VCC
Figure 172. Calibrated 8MHz RC Oscillator Frequency vs. Osccal Value
6.5
6.7
6.9
7.1
7.3
7.5
7.7
7.9
8.1
8.3
8.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
4
6
8
10
12
14
16
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL VALUE
FRC (MHz)272
2486AA–AVR–02/2013
ATmega8(L)
Figure 173. Calibrated 4MHz RC Oscillator Frequency vs. Temperature
Figure 174. Calibrated 4MHz RC Oscillator Frequency vs. VCC
3.5
3.6
3.7
3.8
3.9
4
4.1
4.2
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (MHz)
5.5V
2.7V
4.0V
3.5
3.6
3.7
3.8
3.9
4
4.1
4.2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C273
2486AA–AVR–02/2013
ATmega8(L)
Figure 175. Calibrated 4MHz RC Oscillator Frequency vs. Osccal Value
Figure 176. Calibrated 2MHz RC Oscillator Frequency vs. Temperature
2
3
4
5
6
7
8
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL VALUE
FRC (MHz)
1.8
1.85
1.9
1.95
2
2.05
2.1
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (MHz)
5.5V
2.7V
4.0V274
2486AA–AVR–02/2013
ATmega8(L)
Figure 177. Calibrated 2MHz RC Oscillator Frequency vs. VCC
Figure 178. Calibrated 2MHz RC Oscillator Frequency vs. Osccal Value
1.7
1.8
1.9
2
2.1
2.2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
0.8
1.3
1.8
2.3
2.8
3.3
3.8
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL VALUE
FRC (MHz)275
2486AA–AVR–02/2013
ATmega8(L)
Figure 179. Calibrated 1MHz RC Oscillator Frequency vs. Temperature
Figure 180. Calibrated 1MHz RC Oscillator Frequency vs. VCC
0.9
0.92
0.94
0.96
0.98
1
1.02
1.04
-60 -40 -20 0 20 40 60 80 100
Temperature (°C)
FRC (MHz)
5.5V
2.7V
4.0V
0.9
0.95
1
1.05
1.1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C276
2486AA–AVR–02/2013
ATmega8(L)
Figure 181. Calibrated 1MHz RC Oscillator Frequency vs. Osccal Value
Current Consumption
of Peripheral Units
Figure 182. Brown-out Detector Current vs. VCC
0.5
0.7
0.9
1.1
1.3
1.5
1.7
1.9
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL VALUE
FRC (MHz)
0
5
10
15
20
25
30
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C
85°C
-40°C277
2486AA–AVR–02/2013
ATmega8(L)
Figure 183. ADC Current vs. VCC (AREF = AVCC)
Figure 184. AREF External Reference Current vs. VCC
0
50
100
150
200
250
300
350
400
450
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C
0
50
100
150
200
250
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C278
2486AA–AVR–02/2013
ATmega8(L)
Figure 185. 32kHz TOSC Current vs. VCC (Watchdog Timer Disabled)
Figure 186. Watchdog Timer Current vs. VCC
0
5
10
15
20
25
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C
0
10
20
30
40
50
60
70
80
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C279
2486AA–AVR–02/2013
ATmega8(L)
Figure 187. Analog Comparator Current vs. VCC
Figure 188. Programming Current vs. VCC
0
10
20
30
40
50
60
70
80
90
100
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
25°C
85°C
-40°C
0
1
2
3
4
5
6
7
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
25°C
85°C
-40°C280
2486AA–AVR–02/2013
ATmega8(L)
Current Consumption
in Reset and Reset
Pulsewidth
Figure 189. Reset Supply Current vs. VCC (0.1MHz - 1.0MHz, Excluding Current Through The
Reset Pull-up)
Figure 190. Reset Supply Current vs. VCC (1MHz - 20MHz, Excluding Current Through The
Reset Pull-up)
0
0.5
1
1.5
2
2.5
3
3.5
4
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
5.5V
5.0V
4.5V
3.3V
3.0V
2.7V
4.0V
0
5
10
15
20
25
0246 8 10 12 14 16 18 20
Frequency (MHz)
ICC (mA)
5.5V
5.0V
4.5V
3.3V
3.0V
2.7V281
2486AA–AVR–02/2013
ATmega8(L)
Figure 191. Reset Pulse Width vs. VCC
0
200
400
600
800
1000
1200
1400
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Pulsewidth (ns)
85°C
25°C
-40°C282
2486AA–AVR–02/2013
ATmega8(L)
ATmega8
Typical
Characteristics
– TA = -40°C to 105°C
The following charts show typical behavior. These figures are not tested during manufacturing.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. A sine wave generator with Rail-to-Rail output is used as clock
source.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating
frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature.
The dominating factors are operating voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where
CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to
function properly at frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer
enabled and Power-down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.
Active Supply Current
Figure 0-1. Active Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
ACTIVE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 8 MHz
0
2
4
6
8
10
12
14
16
18
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C283
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-2. Active Supply Current vs. VCC (Internal RC Oscillator, 4 MHz)
Figure 0-3. Active Supply Current vs. VCC (Internal RC Oscillator, 2 MHz)
ACTIVE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 4 MHz
0
2
4
6
8
10
12
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C
ACTIVE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 2 MHz
0
1
2
3
4
5
6
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C284
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-4. Active Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
Idle Supply Current
Figure 0-5. Idle Supply Current vs. VCC (Internal RC Oscillator, 8 MHz)
ACTIVE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 1 MHz
0
0.5
1
1.5
2
2.5
3
3.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C
IDLE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 8 MHz
0
1
2
3
4
5
6
7
8
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C285
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-6. Idle Supply Current vs. VCC (Internal RC Oscillator, 4 MHz)
Figure 0-7. Idle Supply Current vs. VCC (Internal RC Oscillator, 2 MHz)
IDLE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 4 MHz
0
0.5
1
1.5
2
2.5
3
3.5
4
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C
IDLE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 2 MHz
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C286
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-8. Idle Supply Current vs. VCC (Internal RC Oscillator, 1 MHz)
Power-down Supply Current
Figure 0-9. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
IDLE SUPPLY CURRENT vs. VCC
INTERNAL RC OSCILLATOR, 1 MHz
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
105°C
POWER-DOWN SUPPLY CURRENT vs. VCC
WATCHDOG TIMER DISABLED
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
105°C
25°C
-40°C
85°C287
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-10. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
Pin Pull-up
Figure 0-11. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
POWER-DOWN SUPPLY CURRENT vs. VCC
WATCHDOG TIMER ENABLED
0
10
20
30
40
50
60
70
80
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
-40°C
105°C
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
Vcc = 5V
0
20
40
60
80
100
120
140
160
0123
VOP (V)
IOP (uA)
85°C
25°C
-40°C
105°C288
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-12. I/O Pin Pull-up Resistor Current vs. Input Voltage (VCC = 2.7V)
Figure 0-13. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
I/O PIN PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
Vcc = 2.7V
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5 3
VOP (V)
IOP (uA)
85°C 25°C
-40°C
105°C
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE
Vcc = 5V
0
20
40
60
80
100
012
VRESET (V)
IRESET (uA)
85°C
25°C
105°C
-40°C289
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-14. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
Pin Driver Strength
Figure 0-15. I/O Pin Source Current vs. Output Voltage (VCC = 5V)
RESET PULL-UP RESISTOR CURRENT vs. RESET PIN VOLTAGE
Vcc = 2.7V
0
5
10
15
20
25
30
35
40
45
0 0.5 1 1.5 2 2.5
VRESET (V)
IRESET (uA)
85°C 25°C
-40°C
105°C
I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V
0
10
20
30
40
50
60
70
80
01234
VOH (V)
IOH (mA)
85°C
25°C
-40°C
105°C290
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-16. I/O Pin Source Current vs. Output Voltage (VCC = 2.7V)
Figure 0-17. I/O Pin Sink Current vs. Output Voltage (VCC = 5V)
I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V
0
5
10
15
20
25
30
0 0.5 1 1.5 2 2.5 3
VOH (V)
IOH (mA)
85°C
25°C
-40°C
105°C
I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)
85°C
25°C
-40°C
105°C291
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-18. I/O Pin Sink Current vs. Output Voltage (VCC = 2.7V)
Figure 0-19. Reset Pin as I/O – Pin Source Current vs. Output Voltage (VCC = 5V)
I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V
0
5
10
15
20
25
30
35
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)
85°C
25°C
-40°C
105°C
RESET PIN AS I/O - SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V
0
0.5
1
1.5
2
2.5
3
3.5
4
2 2.5 3 3.5 4 4.5
VOH (V)
Current (mA)
85°C
25°C
-40°C
105°C292
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-20. Reset Pin as I/O – Pin Source Current vs. Output Voltage (VCC = 2.7V)
Figure 0-21. Reset Pin as I/O – Pin Sink Current vs. Output Voltage (VCC = 5V)
RESET PIN AS I/O - SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
5
0 0.5 1 1.5 2 2.5
VOH (V)
Current (mA)
85°C
25°C -40°C
105 °C
RESET PIN AS I/O - SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V
0
2
4
6
8
10
12
14
0 0.5 1 1.5 2 2.5
VOL (V)
Current (mA)
85°C
25°C
-40°C
105°C293
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-22. Reset Pin as I/O – Pin Sink Current vs. Output Voltage (VCC = 2.7V)
Pin Thresholds and Hysteresis
Figure 0-23. I/O Pin Input Threshold Voltage vs. VCC (VIH, I/O Pin Read as “1”)
RESET PIN AS I/O - SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
0 0.5 1 1.5 2 2.5
VOL (V)
Current (mA)
85°C
25°C
-40°C
105°C
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC
VIH, IO PIN READ AS '1'
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
105°C
-40°C
25°C294
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-24. I/O Pin Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
Figure 0-25. I/O Pin Input Hysteresis vs. VCC
I/O PIN INPUT THRESHOLD VOLTAGE vs. VCC
VIL, IO PIN READ AS '0'
0
0.5
1
1.5
2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C
I/O PIN INPUT HYSTERESIS vs. VCC
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C295
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-26. Reset Pin as I/O – Input Threshold Voltage vs. VCC (VIH,I/O Pin Read as “1”)
Figure 0-27. Reset Pin as I/O – Input Threshold Voltage vs. VCC (VIL, I/O Pin Read as “0”)
RESET PIN AS I/O - INPUT THRESHOLD VOLTAGE vs. VCC
VIH, RESET PIN READ AS '1'
0
0.5
1
1.5
2
2.5
3
3.5
4
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C
RESET PIN AS I/O - INPUT THRESHOLD VOLTAGE vs. VCC
VIL, RESET PIN READ AS '0'
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C296
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-28. Reset Pin as I/O – Pin Hysteresis vs. VCC
Figure 0-29. Reset Input Threshold Voltage vs. VCC (VIH, Reset Pin Read as “1”)
RESET PIN AS I/O - PIN HYSTERESIS vs. VCC
0
0.5
1
1.5
2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C
RESET INPUT THRESHOLD VOLTAGE vs. VCC
VIH, RESET PIN READ AS '1'
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C297
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-30. Reset Input Threshold Voltage vs. VCC (VIL, Reset Pin Read as “0”)
Figure 0-31. Reset Input Pin Hysteresis vs. VCC
RESET INPUT THRESHOLD VOLTAGE vs. VCC
VIL, RESET PIN READ AS '0'
0
0.5
1
1.5
2
2.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C
RESET INPUT PIN HYSTERESIS vs. VCC
0
0.2
0.4
0.6
0.8
1
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
105°C298
2486AA–AVR–02/2013
ATmega8(L)
Bod Thresholds and Analog Comparator Offset
Figure 0-32. BOD Thresholds vs. Temperature (BOD Level is 4.0V)
Figure 0-33. BOD Thresholds vs. Temperature (BOD Level is 2.7V)
BOD THRESHOLDS vs. TEMPERATURE
BODLEVEL IS 4.0V
3.8
3.9
4
4.1
4.2
4.3
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120
Temperature (˚C)
Threshold (V)
Rising VCC
Falling VCC
BOD THRESHOLDS vs. TEMPERATURE
BODLEVEL IS 2.7V
2.4
2.5
2.6
2.7
2.8
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120
Temperature (˚C)
Threshold (V)
Rising VCC
Falling VCC299
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-34. Bandgap Voltage vs. VCC
Figure 0-35. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 5V)
BANDGAP VOLTAGE vs. VCC
1.29
1.295
1.3
1.305
1.31
1.315
2.5 3 3.5 4 4.5 5 5.5
Vcc (V)
Bandgap Voltage (V)
85°C
25°C
-40°C
105°C
ANALOG COMPARATOR OFFSET VOLTAGE vs. COMMON MODE VOLTAGE
VCC = 5V
-0.006
-0.005
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Common Mode Voltage (V)
Comparator Offset Voltage (V)
85°C
25°C
-40°C
105°C300
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-36. Analog Comparator Offset Voltage vs. Common Mode Voltage (VCC = 2.7V)
Internal Oscillator Speed
Figure 0-37. Watchdog Oscillator Frequency vs. VCC
ANALOG COMPARATOR OFFSET VOLTAGE vs. COMMON MODE VOLTAGE
VCC = 2.7V
-0.005
-0.004
-0.003
-0.002
-0.001
0
0.001
0.002
0.003
0 0.5 1 1.5 2 2.5 3
Common Mode Voltage (V)
Comparator Offset Voltage (V)
85°C
25°C
-40°C
105°C
WATCHDOG OSCILLATOR FREQUENCY vs. VCC
1080
1100
1120
1140
1160
1180
1200
1220
1240
1260
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (kHz)
85°C
25°C
-40°C
105°C301
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-38. Calibrated 8 MHz RC Oscillator Frequency vs. Temperature
Figure 0-39. Calibrated 8 MHz RC Oscillator Frequency vs. VCC
CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
6.5
6.7
6.9
7.1
7.3
7.5
7.7
7.9
8.1
8.3
8.5
-60 -40 -20 0 20 40 60 80 100 120
Temperature (˚C)
FRC (MHz)
5.5V
2.7V
4.0V
CALIBRATED 8MHz RC OSCILLATOR FREQUENCY vs. VCC
6.5
6.7
6.9
7.1
7.3
7.5
7.7
7.9
8.1
8.3
8.5
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
105°C302
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-40. Calibrated 4 MHz RC Oscillator Frequency vs. Temperature
Figure 0-41. Calibrated 4 MHz RC Oscillator Frequency vs. VCC
CALIBRATED 4MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
3.5
3.6
3.7
3.8
3.9
4
4.1
4.2
-60 -40 -20 0 20 40 60 80 100 120
Temperature (˚C)
FRC (MHz)
5.5V
2.7V
4.0V
CALIBRATED 4MHz RC OSCILLATOR FREQUENCY vs. VCC
3.5
3.6
3.7
3.8
3.9
4
4.1
4.2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
105°C303
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-42. Calibrated 2 MHz RC Oscillator Frequency vs. Temperature
Figure 0-43. Calibrated 2 MHz RC Oscillator Frequency vs. VCC
CALIBRATED 2MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
1.75
1.8
1.85
1.9
1.95
2
2.05
2.1
-60 -40 -20 0 20 40 60 80 100 120
Temperature (˚C)
FRC (MHz)
5.5V
2.7V
4.0V
CALIBRATED 2MHz RC OSCILLATOR FREQUENCY vs. VCC
1.7
1.8
1.9
2
2.1
2.2
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
105°C304
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-44. Calibrated 1 MHz RC Oscillator Frequency vs. Temperature
Figure 0-45. Calibrated 1 MHz RC Oscillator Frequency vs. VCC
CALIBRATED 1MHz RC OSCILLATOR FREQUENCY vs. TEMPERATURE
0.9
0.92
0.94
0.96
0.98
1
1.02
1.04
-60 -40 -20 0 20 40 60 80 100 120
Temperature (˚C)
FRC (MHz)
5.5V
2.7V
4.0V
CALIBRATED 1MHz RC OSCILLATOR FREQUENCY vs. VCC
0.9
0.95
1
1.05
1.1
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)
85°C
25°C
-40°C
105°C305
2486AA–AVR–02/2013
ATmega8(L)
Current Consumption of Peripheral Units
Figure 0-46. Brown-out Detector Current vs. VCC
Figure 0-47. ADC Current vs. VCC (AREF = AVCC)
BROWNOUT DETECTOR CURRENT vs. VCC
0
5
10
15
20
25
30
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25°C
85°C
-40°C
105°C
ADC CURRENT vs. VCC
AREF = AVCC
0
50
100
150
200
250
300
350
400
450
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C
-40°C
105°C306
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-48. AREF External Reference Current vs. VCC
Figure 0-49. Watchdog Timer Current vs. VCC
AREF EXTERNAL REFERENCE CURRENT vs. VCC
0
50
100
150
200
250
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
85°C
25°C -40°C
105°C
WATCHDOG TIMER CURRENT vs. VCC
0
0.01
0.02
0.03
0.04
0.05
0.06
0.07
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
105°C
25°C
-40°C
85°C307
2486AA–AVR–02/2013
ATmega8(L)
Figure 0-50. Analog Comparator Current vs. VCC
Figure 0-51. Programming Current vs. VCC
ANALOG COMPARATOR CURRENT vs. VCC
0
20
40
60
80
100
120
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25°C
105°C
-40°C
85°C
PROGRAMMING CURRENT vs. VCC
0
1
2
3
4
5
6
7
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (uA)
25°C
85°C
-40°C
105°C308
2486AA–AVR–02/2013
ATmega8(L)
Current Consumption in Reset and Reset Pulsewidth
Figure 0-52. Reset Pulse Width vs. VCC
RESET PULSE WIDTH vs. VCC
0
200
400
600
800
1000
1200
1400
2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Pulsewidth (ns)
85°C
25°C
-40°C
105°C309
2486AA–AVR–02/2013
ATmega8(L)
Register Summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
0x3F (0x5F) SREG I T H S V N Z C 11
0x3E (0x5E) SPH – – – – – SP10 SP9 SP8 13
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 13
0x3C (0x5C) Reserved
0x3B (0x5B) GICR INT1 INT0 – – – – IVSEL IVCE 49, 67
0x3A (0x5A) GIFR INTF1 INTF0 – – – – – – 67
0x39 (0x59) TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 – TOIE0 72, 100, 119
0x38 (0x58) TIFR OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 – TOV0 72, 101, 119
0x37 (0x57) SPMCR SPMIE RWWSB – RWWSRE BLBSET PGWRT PGERS SPMEN 206
0x36 (0x56) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 165
0x35 (0x55) MCUCR SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00 33, 66
0x34 (0x54) MCUCSR – – – – WDRF BORF EXTRF PORF 41
0x33 (0x53) TCCR0 – – – – – CS02 CS01 CS00 71
0x32 (0x52) TCNT0 Timer/Counter0 (8 Bits) 72
0x31 (0x51) OSCCAL Oscillator Calibration Register 31
0x30 (0x50) SFIOR – – – – ACME PUD PSR2 PSR10 58, 74, 120, 186
0x2F (0x4F) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 96
0x2E (0x4E) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 98
0x2D (0x4D) TCNT1H Timer/Counter1 – Counter Register High byte 99
0x2C (0x4C) TCNT1L Timer/Counter1 – Counter Register Low byte 99
0x2B (0x4B) OCR1AH Timer/Counter1 – Output Compare Register A High byte 99
0x2A (0x4A) OCR1AL Timer/Counter1 – Output Compare Register A Low byte 99
0x29 (0x49) OCR1BH Timer/Counter1 – Output Compare Register B High byte 99
0x28 (0x48) OCR1BL Timer/Counter1 – Output Compare Register B Low byte 99
0x27 (0x47) ICR1H Timer/Counter1 – Input Capture Register High byte 100
0x26 (0x46) ICR1L Timer/Counter1 – Input Capture Register Low byte 100
0x25 (0x45) TCCR2 FOC2 WGM20 COM21 COM20 WGM21 CS22 CS21 CS20 114
0x24 (0x44) TCNT2 Timer/Counter2 (8 Bits) 116
0x23 (0x43) OCR2 Timer/Counter2 Output Compare Register 116
0x22 (0x42) ASSR – – – – AS2 TCN2UB OCR2UB TCR2UB 117
0x21 (0x41) WDTCR – – – WDCE WDE WDP2 WDP1 WDP0 43
0x20(1) (0x40)(1) UBRRH URSEL – – – UBRR[11:8] 152
UCSRC URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL 150
0x1F (0x3F) EEARH – – – – – – – EEAR8 20
0x1E (0x3E) EEARL EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 20
0x1D (0x3D) EEDR EEPROM Data Register 20
0x1C (0x3C) EECR – – – – EERIE EEMWE EEWE EERE 20
0x1B (0x3B) Reserved
0x1A (0x3A) Reserved
0x19 (0x39) Reserved
0x18 (0x38) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 65
0x17 (0x37) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 65
0x16 (0x36) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 65
0x15 (0x35) PORTC – PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 65
0x14 (0x34) DDRC – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 65
0x13 (0x33) PINC – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 65
0x12 (0x32) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 65
0x11 (0x31) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 65
0x10 (0x30) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 65
0x0F (0x2F) SPDR SPI Data Register 127
0x0E (0x2E) SPSR SPIF WCOL – – – – – SPI2X 126
0x0D (0x2D) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 125
0x0C (0x2C) UDR USART I/O Data Register 148
0x0B (0x2B) UCSRA RXC TXC UDRE FE DOR PE U2X MPCM 148
0x0A (0x2A) UCSRB RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 149
0x09 (0x29) UBRRL USART Baud Rate Register Low byte 152
0x08 (0x28) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 186
0x07 (0x27) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 199
0x06 (0x26) ADCSRA ADEN ADSC ADFR ADIF ADIE ADPS2 ADPS1 ADPS0 200
0x05 (0x25) ADCH ADC Data Register High byte 201
0x04 (0x24) ADCL ADC Data Register Low byte 201
0x03 (0x23) TWDR Two-wire Serial Interface Data Register 167
0x02 (0x22) TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE 167310
2486AA–AVR–02/2013
ATmega8(L)
Notes: 1. Refer to the USART description (“USART” on page 129) for details on how to access UBRRH and UCSRC (“Accessing
UBRRH/UCSRC Registers” on page 146)
2. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written
3. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on
all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions
work with registers 0x00 to 0x1F only
0x01 (0x21) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 166
0x00 (0x20) TWBR Two-wire Serial Interface Bit Rate Register 165
Register Summary (Continued)
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page311
2486AA–AVR–02/2013
ATmega8(L)
Instruction Set Summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd Rd + Rr Z, C, N, V, H 1
ADC Rd, Rr Add with Carry two Registers Rd Rd + Rr + C Z, C, N, V, H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl Rdh:Rdl + K Z, C, N, V, S 2
SUB Rd, Rr Subtract two Registers Rd Rd - Rr Z, C, N, V, H 1
SUBI Rd, K Subtract Constant from Register Rd Rd - K Z, C, N, V, H 1
SBC Rd, Rr Subtract with Carry two Registers Rd Rd - Rr - C Z, C, N, V, H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd Rd - K - C Z, C, N ,V, H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl Rdh:Rdl - K Z, C, N, V, S 2
AND Rd, Rr Logical AND Registers Rd Rd Rr Z, N, V 1
ANDI Rd, K Logical AND Register and Constant Rd Rd K Z, N, V 1
OR Rd, Rr Logical OR Registers Rd Rd v Rr Z, N, V 1
ORI Rd, K Logical OR Register and Constant Rd Rd v K Z, N, V 1
EOR Rd, Rr Exclusive OR Registers Rd Rd Rr Z, N, V 1
COM Rd One’s Complement Rd 0xFF Rd Z, C, N, V 1
NEG Rd Two’s Complement Rd 0x00 Rd Z, C, N, V, H 1
SBR Rd,K Set Bit(s) in Register Rd Rd v K Z, N, V 1
CBR Rd,K Clear Bit(s) in Register Rd Rd (0xFF - K) Z, N, V 1
INC Rd Increment Rd Rd + 1 Z, N, V 1
DEC Rd Decrement Rd Rd 1 Z, N, V 1
TST Rd Test for Zero or Minus Rd Rd Rd Z, N, V 1
CLR Rd Clear Register Rd Rd Rd Z, N, V 1
SER Rd Set Register Rd 0xFF None 1
MUL Rd, Rr Multiply Unsigned R1:R0 Rd x Rr Z, C 2
MULS Rd, Rr Multiply Signed R1:R0 Rd x Rr Z, C 2
MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 Rd x Rr Z, C 2
FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 (Rd x Rr) << 1 Z, C 2
FMULS Rd, Rr Fractional Multiply Signed R1:R0 (Rd x Rr) << 1 Z, C 2
FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 (Rd x Rr) << 1 Z, C 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC Z None 2
RCALL k Relative Subroutine Call PC PC + k + 1 None 3
ICALL Indirect Call to (Z) PC Z None 3
RET Subroutine Return PC STACK None 4
RETI Interrupt Return PC STACK I 4
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC PC + 2 or 3 None 1 / 2 / 3
CP Rd,Rr Compare Rd Rr Z, N, V, C, H 1
CPC Rd,Rr Compare with Carry Rd Rr C Z, N, V, C, H 1
CPI Rd,K Compare Register with Immediate Rd K Z, N, V, C, H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC PC + 2 or 3 None 1 / 2 / 3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC PC + 2 or 3 None 1 / 2 / 3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC PC + 2 or 3 None 1 / 2 / 3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC PC + 2 or 3 None 1 / 2 / 3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PCPC+k + 1 None 1 / 2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PCPC+k + 1 None 1 / 2
BREQ k Branch if Equal if (Z = 1) then PC PC + k + 1 None 1 / 2
BRNE k Branch if Not Equal if (Z = 0) then PC PC + k + 1 None 1 / 2
BRCS k Branch if Carry Set if (C = 1) then PC PC + k + 1 None 1 / 2
BRCC k Branch if Carry Cleared if (C = 0) then PC PC + k + 1 None 1 / 2
BRSH k Branch if Same or Higher if (C = 0) then PC PC + k + 1 None 1 / 2
BRLO k Branch if Lower if (C = 1) then PC PC + k + 1 None 1 / 2
BRMI k Branch if Minus if (N = 1) then PC PC + k + 1 None 1 / 2
BRPL k Branch if Plus if (N = 0) then PC PC + k + 1 None 1 / 2
BRGE k Branch if Greater or Equal, Signed if (N V= 0) then PC PC + k + 1 None 1 / 2
BRLT k Branch if Less Than Zero, Signed if (N V= 1) then PC PC + k + 1 None 1 / 2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC PC + k + 1 None 1 / 2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC PC + k + 1 None 1 / 2
BRTS k Branch if T Flag Set if (T = 1) then PC PC + k + 1 None 1 / 2
BRTC k Branch if T Flag Cleared if (T = 0) then PC PC + k + 1 None 1 / 2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC PC + k + 1 None 1 / 2
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC PC + k + 1 None 1 / 2312
2486AA–AVR–02/2013
ATmega8(L)
Mnemonics Operands Description Operation Flags #Clocks
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC PC + k + 1 None 1 / 2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC PC + k + 1 None 1 / 2
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd K None 1
LD Rd, X Load Indirect Rd (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd (X), X X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X X - 1, Rd (X) None 2
LD Rd, Y Load Indirect Rd (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd (Y), Y Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y Y - 1, Rd (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd (Y + q) None 2
LD Rd, Z Load Indirect Rd (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd (Z), Z Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z Z - 1, Rd (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd (k) None 2
ST X, Rr Store Indirect (X) Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) Rr, X X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X X - 1, (X) Rr None 2
ST Y, Rr Store Indirect (Y) Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) Rr, Y Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y Y - 1, (Y) Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) Rr None 2
ST Z, Rr Store Indirect (Z) Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) Rr, Z Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z Z - 1, (Z) Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) Rr None 2
STS k, Rr Store Direct to SRAM (k) Rr None 2
LPM Load Program Memory R0 (Z) None 3
LPM Rd, Z Load Program Memory Rd (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd (Z), Z Z+1 None 3
SPM Store Program Memory (Z) R1:R0 None -
IN Rd, P In Port Rd P None 1
OUT P, Rr Out Port P Rr None 1
PUSH Rr Push Register on Stack STACK Rr None 2
POP Rd Pop Register from Stack Rd STACK None 2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) 0 None 2
LSL Rd Logical Shift Left Rd(n+1) Rd(n), Rd(0) 0 Z, C, N, V 1
LSR Rd Logical Shift Right Rd(n) Rd(n+1), Rd(7) 0 Z, C, N, V 1
ROL Rd Rotate Left Through Carry Rd(0)C,Rd(n+1) Rd(n),CRd(7) Z, C, N, V 1
ROR Rd Rotate Right Through Carry Rd(7)C,Rd(n) Rd(n+1),CRd(0) Z, C, N, V 1
ASR Rd Arithmetic Shift Right Rd(n) Rd(n+1), n=0..6 Z, C, N, V 1
SWAP Rd Swap Nibbles Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) None 1
BSET s Flag Set SREG(s) 1 SREG(s) 1
BCLR s Flag Clear SREG(s) 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) T None 1
SEC Set Carry C 1 C1
CLC Clear Carry C 0 C 1
SEN Set Negative Flag N 1 N1
CLN Clear Negative Flag N 0 N 1
SEZ Set Zero Flag Z 1 Z1
CLZ Clear Zero Flag Z 0 Z 1
SEI Global Interrupt Enable I 1 I1
CLI Global Interrupt Disable I 0 I 1
SES Set Signed Test Flag S 1 S1
CLS Clear Signed Test Flag S 0 S 1
SEV Set Twos Complement Overflow. V 1 V1
CLV Clear Twos Complement Overflow V 0 V 1
SET Set T in SREG T 1 T1
Instruction Set Summary (Continued)313
2486AA–AVR–02/2013
ATmega8(L)
Mnemonics Operands Description Operation Flags #Clocks
CLT Clear T in SREG T 0 T 1
SEH Set Half Carry Flag in SREG H 1 H1
CLH Clear Half Carry Flag in SREG H 0 H 1
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
Instruction Set Summary (Continued)314
2486AA–AVR–02/2013
ATmega8(L)
Ordering Information
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities
2. Pb-free packaging complies to the European Directive for Restriction of Hazardous Substances (RoHS directive). Also
Halide free and fully Green
3. Tape & Reel
4. See characterization specification at 105C
Speed (MHz) Power Supply (V) Ordering Code(2) Package(1) Operation Range
8 2.7 - 5.5
ATmega8L-8AU
ATmega8L-8AUR(3)
ATmega8L-8PU
ATmega8L-8MU
ATmega8L-8MUR(3)
32A
32A
28P3
32M1-A
32M1-A Industrial
(-40C to 85C)
16 4.5 - 5.5
ATmega8-16AU
ATmega8-16AUR(3)
ATmega8-16PU
ATmega8-16MU
ATmega8-16MUR(3)
32A
32A
28P3
32M1-A
32M1-A
8 2.7 - 5.5
ATmega8L-8AN
ATmega8L-8ANR(3)
ATmega8L-8PN
ATmega8L-8MN
ATmega8L-8MUR(3)
32A
32A
28P3
32M1-A
32M1-A Industrial
(-40C to 105C)
16 4.5 - 5.5
ATmega8-16AN
ATmega8-16ANR(3)
ATmega8-16PN
ATmega8-16MN
ATmega8-16MUR(3)
32A
32A
28P3
32M1-A
32M1-A
Package Type
32A 32-lead, Thin (1.0mm) Plastic Quad Flat Package (TQFP)
28P3 28-lead, 0.300” Wide, Plastic Dual Inline Package (PDIP)
32M1-A 32-pad, 5 × 5 × 1.0 body, Lead Pitch 0.50mm Quad Flat No-Lead/Micro Lead Frame Package (QFN/MLF)315
2486AA–AVR–02/2013
ATmega8(L)
Packaging Information
32A
TITLE DRAWING NO. REV.
32A, 32-lead, 7 x 7mm body size, 1.0mm body thickness,
0.8mm lead pitch, thin profile plastic quad flat package (TQFP) 32A C
2010-10-20
PIN 1 IDENTIFIER
0°~7°
PIN 1
L
C
A1 A2 A
D1
D
e E1 E
B
Notes:
1. This package conforms to JEDEC reference MS-026, Variation ABA.
2. Dimensions D1 and E1 do not include mold protrusion. Allowable
protrusion is 0.25mm per side. Dimensions D1 and E1 are maximum
plastic body size dimensions including mold mismatch.
3. Lead coplanarity is 0.10mm maximum.
A – – 1.20
A1 0.05 – 0.15
A2 0.95 1.00 1.05
D 8.75 9.00 9.25
D1 6.90 7.00 7.10 Note 2
E 8.75 9.00 9.25
E1 6.90 7.00 7.10 Note 2
B 0.30 – 0.45
C 0.09 – 0.20
L 0.45 – 0.75
e 0.80 TYP
COMMON DIMENSIONS
(Unit of measure = mm)
SYMBOL MIN NOM MAX NOTE316
2486AA–AVR–02/2013
ATmega8(L)
28P3
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
28P3, 28-lead (0.300"/7.62mm Wide) Plastic Dual
Inline Package (PDIP) 28P3 B
09/28/01
PIN
1
E1
A1
B
REF
E
B1
C
L
SEATING PLANE
A
0º ~ 15º
D
e
eB
B2
(4 PLACES)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
A – – 4.5724
A1 0.508 – –
D 34.544 – 34.798 Note 1
E 7.620 – 8.255
E1 7.112 – 7.493 Note 1
B 0.381 – 0.533
B1 1.143 – 1.397
B2 0.762 – 1.143
L 3.175 – 3.429
C 0.203 – 0.356
eB – – 10.160
e 2.540 TYP
Note: 1. Dimensions D and E1 do not include mold Flash or Protrusion.
Mold Flash or Protrusion shall not exceed 0.25mm (0.010"). 317
2486AA–AVR–02/2013
ATmega8(L)
32M1-A
2325 Orchard Parkway
San Jose, CA 95131
TITLE DRAWING NO.
R
REV.
32M1-A, 32-pad, 5 x 5 x 1.0mm Body, Lead Pitch 0.50mm, 32M1-A E
5/25/06
3.10mm Exposed Pad, Micro Lead Frame Package (MLF)
COMMON DIMENSIONS
(Unit of Measure = mm)
SYMBOL MIN NOM MAX NOTE
D1
D
E1 E
b e
A3
A2
A1
A
D2
E2
0.08 C
L
1
2
3
P
P
0
1
2
3
A 0.80 0.90 1.00
A1 – 0.02 0.05
A2 – 0.65 1.00
A3 0.20 REF
b 0.18 0.23 0.30
D
D1
D2 2.95 3.10 3.25
4.90 5.00 5.10
4.70 4.75 4.80
4.70 4.75 4.80
4.90 5.00 5.10
E
E1
E2 2.95 3.10 3.25
e 0.50 BSC
L 0.30 0.40 0.50
P – – 0.60
– – 12o
Note: JEDEC Standard MO-220, Fig. 2 (Anvil Singulation), VHHD-2.
TOP VIEW
SIDE VIEW
BOTTOM VIEW
0
Pin 1 ID
Pin #1 Notch
(0.20 R)
K 0.20 – –
K
K318
2486AA–AVR–02/2013
ATmega8(L)
Errata The revision letter in this section refers to the revision of the ATmega8 device.
ATmega8
Rev. D to I, M
• First Analog Comparator conversion may be delayed
• Interrupts may be lost when writing the timer registers in the asynchronous timer
• Signature may be Erased in Serial Programming Mode
• CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32KHz Oscillator is
Used to Clock the Asynchronous Timer/Counter2
• Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt request
1. First Analog Comparator conversion may be delayed
If the device is powered by a slow rising VCC, the first Analog Comparator conversion will
take longer than expected on some devices.
Problem Fix / Workaround
When the device has been powered or reset, disable then enable theAnalog Comparator
before the first conversion.
2. Interrupts may be lost when writing the timer registers in the asynchronous timer
The interrupt will be lost if a timer register that is synchronized to the asynchronous timer
clock is written when the asynchronous Timer/Counter register(TCNTx) is 0x00.
Problem Fix / Workaround
Always check that the asynchronous Timer/Counter register neither have the value 0xFF nor
0x00 before writing to the asynchronous Timer Control Register(TCCRx), asynchronous
Timer Counter Register(TCNTx), or asynchronous Output Compare Register(OCRx).
3. Signature may be Erased in Serial Programming Mode
If the signature bytes are read before a chiperase command is completed, the signature may
be erased causing the device ID and calibration bytes to disappear. This is critical, especially,
if the part is running on internal RC oscillator.
Problem Fix / Workaround:
Ensure that the chiperase command has exceeded before applying the next command.
4. CKOPT Does not Enable Internal Capacitors on XTALn/TOSCn Pins when 32KHz
Oscillator is Used to Clock the Asynchronous Timer/Counter2
When the internal RC Oscillator is used as the main clock source, it is possible to run the
Timer/Counter2 asynchronously by connecting a 32KHz Oscillator between XTAL1/TOSC1
and XTAL2/TOSC2. But when the internal RC Oscillator is selected as the main clock
source, the CKOPT Fuse does not control the internal capacitors on XTAL1/TOSC1 and
XTAL2/TOSC2. As long as there are no capacitors connected to XTAL1/TOSC1 and
XTAL2/TOSC2, safe operation of the Oscillator is not guaranteed.
Problem Fix / Workaround
Use external capacitors in the range of 20pF - 36pF on XTAL1/TOSC1 and XTAL2/TOSC2.
This will be fixed in ATmega8 Rev. G where the CKOPT Fuse will control internal capacitors
also when internal RC Oscillator is selected as main clock source. For ATmega8 Rev. G,
CKOPT = 0 (programmed) will enable the internal capacitors on XTAL1 and XTAL2. Customers
who want compatibility between Rev. G and older revisions, must ensure that
CKOPT is unprogrammed (CKOPT = 1).319
2486AA–AVR–02/2013
ATmega8(L)
5. Reading EEPROM by using ST or STS to set EERE bit triggers unexpected interrupt
request.
Reading EEPROM by using the ST or STS command to set the EERE bit in the EECR register
triggers an unexpected EEPROM interrupt request.
Problem Fix / Workaround
Always use OUT or SBI to set EERE in EECR.320
2486AA–AVR–02/2013
ATmega8(L)
Datasheet
Revision
History
Please note that the referring page numbers in this section are referred to this document. The
referring revision in this section are referring to the document revision.
Changes from Rev.
2486Z- 02/11 to
Rev. 2486AA- 02/2013
1. Updated the datasheet according to the Atmel new Brand Style Guide.
2.Removed the reference to “On-chip debugging” from the content.
3.Added “Electrical Characteristics – TA = -40°C to 105°C” on page 242.
4.Added “ATmega8 Typical Characteristics – TA = -40°C to 105°C” on page 282.
5.Updated “Ordering Information” on page 314.
Changes from Rev.
2486Y- 10/10 to
Rev. 2486Z- 02/11
1. Updated the datasheet according to the Atmel new Brand Style Guide.
2. Updated “Ordering Information” on page 314. Added Ordering Information for
“Tape & Reel” devices
Changes from Rev.
2486X- 06/10 to
Rev. 2486Y- 10/10
1. Max Rise/Fall time in Table 102 on page 239 has been corrected from 1.6ns to 1600ns.
2. Note is added to “Performing Page Erase by SPM” on page 209.
3. Updated/corrected several short-cuts and added some new ones.
4. Updated last page according to new standard.
Changes from Rev.
2486W- 02/10 to
Rev. 2486X- 06/10
1. Updated “DC Characteristics” on page 235 with new VOL maximum value (0.9V and
0.6V).
Changes from Rev.
2486V- 05/09 to
Rev. 2486W- 02/10
1. Updated “ADC Characteristics” on page 241 with VINT maximum value (2.9V).
Changes from Rev.
2486U- 08/08 to
Rev. 2486V- 05/09
1. Updated “Errata” on page 318.
2. Updated the last page with Atmel’s new adresses.
Changes from Rev.
2486T- 05/08 to
Rev. 2486U- 08/08
1. Updated “DC Characteristics” on page 235 with I
CC typical values.321
2486AA–AVR–02/2013
ATmega8(L)
Changes from Rev.
2486S- 08/07 to
Rev. 2486T- 05/08
1. Updated Table 98 on page 233.
2. Updated “Ordering Information” on page 314.
- Commercial Ordering Code removed.
- No Pb-free packaging option removed.
Changes from Rev.
2486R- 07/07 to
Rev. 2486S- 08/07
1. Updated “Features” on page 1.
2. Added “Data Retention” on page 7.
3. Updated “Errata” on page 318.
4. Updated “Slave Mode” on page 125.
Changes from Rev.
2486Q- 10/06 to
Rev. 2486R- 07/07
1. Added text to Table 81 on page 211.
2. Fixed typo in “Peripheral Features” on page 1.
3. Updated Table 16 on page 42.
4. Updated Table 75 on page 199.
5. Removed redundancy and updated typo in Notes section of “DC Characteristics” on
page 235.
Changes from Rev.
2486P- 02/06 to
Rev. 2486Q- 10/06
1. Updated “Timer/Counter Oscillator” on page 32.
2. Updated “Fast PWM Mode” on page 88.
3. Updated code example in “USART Initialization” on page 134.
4. Updated Table 37 on page 96, Table 39 on page 97, Table 42 on page 115, Table 44 on
page 115, and Table 98 on page 233.
5. Updated “Errata” on page 318.
Changes from Rev.
2486O-10/04 to
Rev. 2486P- 02/06
1. Added “Resources” on page 7.
2. Updated “External Clock” on page 32.
3. Updated “Serial Peripheral Interface – SPI” on page 121.
4. Updated Code Example in “USART Initialization” on page 134.
5. Updated Note in “Bit Rate Generator Unit” on page 164.
6. Updated Table 98 on page 233.
7. Updated Note in Table 103 on page 241.322
2486AA–AVR–02/2013
ATmega8(L)
8. Updated “Errata” on page 318.
Changes from Rev.
2486N-09/04 to
Rev. 2486O-10/04
1. Removed to instances of “analog ground”. Replaced by “ground”.
2. Updated Table 7 on page 29, Table 15 on page 38, and Table 100 on page 237.
3. Updated “Calibrated Internal RC Oscillator” on page 30 with the 1MHz default value.
4. Table 89 on page 218 and Table 90 on page 218 moved to new section “Page Size” on
page 218.
5. Updated descripton for bit 4 in “Store Program Memory Control Register – SPMCR”
on page 206.
6. Updated “Ordering Information” on page 314.
Changes from Rev.
2486M-12/03 to
Rev. 2486N-09/04
1. Added note to MLF package in “Pin Configurations” on page 2.
2. Updated “Internal Voltage Reference Characteristics” on page 42.
3. Updated “DC Characteristics” on page 235.
4. ADC4 and ADC5 support 10-bit accuracy. Document updated to reflect this.
Updated features in “Analog-to-Digital Converter” on page 189.
Updated “ADC Characteristics” on page 241.
5. Removed reference to “External RC Oscillator application note” from “External RC
Oscillator” on page 28.
Changes from Rev.
2486L-10/03 to
Rev. 2486M-12/03
1. Updated “Calibrated Internal RC Oscillator” on page 30.
Changes from Rev.
2486K-08/03 to
Rev. 2486L-10/03
1. Removed “Preliminary” and TBDs from the datasheet.
2. Renamed ICP to ICP1 in the datasheet.
3. Removed instructions CALL and JMP from the datasheet.
4. Updated tRST in Table 15 on page 38, VBG in Table 16 on page 42, Table 100 on page
237 and Table 102 on page 239.
5. Replaced text “XTAL1 and XTAL2 should be left unconnected (NC)” after Table 9 in
“Calibrated Internal RC Oscillator” on page 30. Added text regarding XTAL1/XTAL2
and CKOPT Fuse in “Timer/Counter Oscillator” on page 32.
6. Updated Watchdog Timer code examples in “Timed Sequences for Changing the
Configuration of the Watchdog Timer” on page 45.
7. Removed bit 4, ADHSM, from “Special Function IO Register – SFIOR” on page 58.
8. Added note 2 to Figure 103 on page 208.323
2486AA–AVR–02/2013
ATmega8(L)
9. Updated item 4 in the “Serial Programming Algorithm” on page 231.
10. Added tWD_FUSE to Table 97 on page 232 and updated Read Calibration Byte, Byte 3, in
Table 98 on page 233.
11. Updated Absolute Maximum Ratings* and DC Characteristics in “Electrical Characteristics
– TA = -40°C to 85°C” on page 235.
Changes from Rev.
2486J-02/03 to
Rev. 2486K-08/03
1. Updated VBOT values in Table 15 on page 38.
2. Updated “ADC Characteristics” on page 241.
3. Updated “ATmega8 Typical Characteristics – TA = -40°C to 85°C” on page 244.
4. Updated “Errata” on page 318.
Changes from Rev.
2486I-12/02 to Rev.
2486J-02/03
1. Improved the description of “Asynchronous Timer Clock – clkASY” on page 26.
2. Removed reference to the “Multipurpose Oscillator” application note and the “32kHz
Crystal Oscillator” application note, which do not exist.
3. Corrected OCn waveforms in Figure 38 on page 89.
4. Various minor Timer 1 corrections.
5. Various minor TWI corrections.
6. Added note under “Filling the Temporary Buffer (Page Loading)” on page 209 about
writing to the EEPROM during an SPM Page load.
7. Removed ADHSM completely.
8. Added section “EEPROM Write during Power-down Sleep Mode” on page 23.
9. Removed XTAL1 and XTAL2 description on page 5 because they were already
described as part of “Port B (PB7..PB0) XTAL1/XTAL2/TOSC1/TOSC2” on page 5.
10. Improved the table under “SPI Timing Characteristics” on page 239 and removed the
table under “SPI Serial Programming Characteristics” on page 234.
11. Corrected PC6 in “Alternate Functions of Port C” on page 61.
12. Corrected PB6 and PB7 in “Alternate Functions of Port B” on page 58.
13. Corrected 230.4 Mbps to 230.4 kbps under “Examples of Baud Rate Setting” on page
153.
14. Added information about PWM symmetry for Timer 2 in “Phase Correct PWM Mode”
on page 111.
15. Added thick lines around accessible registers in Figure 76 on page 163.324
2486AA–AVR–02/2013
ATmega8(L)
16. Changed “will be ignored” to “must be written to zero” for unused Z-pointer bits
under “Performing a Page Write” on page 209.
17. Added note for RSTDISBL Fuse in Table 87 on page 216.
18. Updated drawings in “Packaging Information” on page 315.
Changes from Rev.
2486H-09/02 to
Rev. 2486I-12/02
1. Added errata for Rev D, E, and F on page 318.
Changes from Rev.
2486G-09/02 to
Rev. 2486H-09/02
1. Changed the Endurance on the Flash to 10,000 Write/Erase Cycles.
Changes from Rev.
2486F-07/02 to
Rev. 2486G-09/02
1. Updated Table 103, “ADC Characteristics,” on page 241.
Changes from Rev.
2486E-06/02 to
Rev. 2486F-07/02
1. Changes in “Digital Input Enable and Sleep Modes” on page 55.
2. Addition of OCS2 in “MOSI/OC2 – Port B, Bit 3” on page 59.
3. The following tables have been updated:
Table 51, “CPOL and CPHA Functionality,” on page 127, Table 59, “UCPOL Bit Settings,”
on page 152, Table 72, “Analog Comparator Multiplexed Input(1),” on page 188, Table 73,
“ADC Conversion Time,” on page 193, Table 75, “Input Channel Selections,” on page 199,
and Table 84, “Explanation of Different Variables used in Figure 103 on page 208 and the
Mapping to the Z-pointer,” on page 214.
4. Changes in “Reading the Calibration Byte” on page 227.
5. Corrected Errors in Cross References.
Changes from Rev.
2486D-03/02 to
Rev. 2486E-06/02
1. Updated Some Preliminary Test Limits and Characterization Data
The following tables have been updated:
Table 15, “Reset Characteristics,” on page 38, Table 16, “Internal Voltage Reference Characteristics,”
on page 42, DC Characteristics on page 235, Table , “ADC Characteristics,” on
page 241.
2. Changes in External Clock Frequency
Added the description at the end of “External Clock” on page 32.
Added period changing data in Table 99, “External Clock Drive,” on page 237.
3. Updated TWI Chapter
More details regarding use of the TWI bit rate prescaler and a Table 65, “TWI Bit Rate Prescaler,”
on page 167.325
2486AA–AVR–02/2013
ATmega8(L)
Changes from Rev.
2486C-03/02 to
Rev. 2486D-03/02
1. Updated Typical Start-up Times.
The following tables has been updated:
Table 5, “Start-up Times for the Crystal Oscillator Clock Selection,” on page 28, Table 6,
“Start-up Times for the Low-frequency Crystal Oscillator Clock Selection,” on page 28,
Table 8, “Start-up Times for the External RC Oscillator Clock Selection,” on page 29, and
Table 12, “Start-up Times for the External Clock Selection,” on page 32.
2. Added “ATmega8 Typical Characteristics – TA = -40°C to 85°C” on page 244.
Changes from Rev.
2486B-12/01 to
Rev. 2486C-03/02
1. Updated TWI Chapter.
More details regarding use of the TWI Power-down operation and using the TWI as Master
with low TWBRR values are added into the datasheet.
Added the note at the end of the “Bit Rate Generator Unit” on page 164.
Added the description at the end of “Address Match Unit” on page 164.
2. Updated Description of OSCCAL Calibration Byte.
In the datasheet, it was not explained how to take advantage of the calibration bytes for 2, 4,
and 8MHz Oscillator selections. This is now added in the following sections:
Improved description of “Oscillator Calibration Register – OSCCAL” on page 31 and “Calibration
Byte” on page 218.
3. Added Some Preliminary Test Limits and Characterization Data.
Removed some of the TBD’s in the following tables and pages:
Table 3 on page 26, Table 15 on page 38, Table 16 on page 42, Table 17 on page 44, “TA =
-40°C to +85°C, VCC = 2.7V to 5.5V (unless otherwise noted)” on page 235, Table 99 on
page 237, and Table 102 on page 239.
4. Updated Programming Figures.
Figure 104 on page 219 and Figure 112 on page 230 are updated to also reflect that AVCC
must be connected during Programming mode.
5. Added a Description on how to Enter Parallel Programming Mode if RESET Pin is Disabled
or if External Oscillators are Selected.
Added a note in section “Enter Programming Mode” on page 221.1
2486AA–AVR–02/2013
ATmega8(L)
Table of Contents
Features 1
Pin Configurations 2
Overview 3
Block Diagram 3
Disclaimer 4
Pin Descriptions 5
Resources 7
Data Retention 7
About Code Examples 8
Atmel AVR CPU Core 9
Introduction 9
Architectural Overview 9
Arithmetic Logic Unit – ALU 11
Status Register 11
General Purpose Register File 12
Stack Pointer 13
Instruction Execution Timing 13
Reset and Interrupt Handling 14
AVR ATmega8 Memories 17
In-System Reprogrammable Flash Program Memory 17
SRAM Data Memory 18
Data Memory Access Times 19
EEPROM Data Memory 19
I/O Memory 24
System Clock and Clock Options 25
Clock Systems and their Distribution 25
Clock Sources 26
Crystal Oscillator 27
Low-frequency Crystal Oscillator 28
External RC Oscillator 28
Calibrated Internal RC Oscillator 30
External Clock 32
Timer/Counter Oscillator 32
Power Management and Sleep Modes 33
Idle Mode 342
2486AA–AVR–02/2013
ATmega8(L)
ADC Noise Reduction Mode 34
Power-down Mode 34
Power-save Mode 34
Standby Mode 35
Minimizing Power Consumption 35
System Control and Reset 37
Internal Voltage Reference 42
Watchdog Timer 43
Timed Sequences for Changing the Configuration of the Watchdog Timer 45
Interrupts 46
Interrupt Vectors in ATmega8 46
I/O Ports 51
Introduction 51
Ports as General Digital I/O 52
Alternate Port Functions 56
Register Description for I/O Ports 65
External Interrupts 66
8-bit Timer/Counter0 69
Overview 69
Timer/Counter Clock Sources 70
Counter Unit 70
Operation 70
Timer/Counter Timing Diagrams 70
8-bit Timer/Counter Register Description 71
Timer/Counter0 and Timer/Counter1 Prescalers 73
16-bit Timer/Counter1 75
Overview 75
Accessing 16-bit Registers 77
Timer/Counter Clock Sources 80
Counter Unit 80
Input Capture Unit 81
Output Compare Units 83
Compare Match Output Unit 85
Modes of Operation 87
Timer/Counter Timing Diagrams 94
16-bit Timer/Counter Register Description 96
8-bit Timer/Counter2 with PWM and Asynchronous Operation 102
Overview 1023
2486AA–AVR–02/2013
ATmega8(L)
Timer/Counter Clock Sources 103
Counter Unit 104
Output Compare Unit 105
Compare Match Output Unit 107
Modes of Operation 108
Timer/Counter Timing Diagrams 112
8-bit Timer/Counter Register Description 114
Asynchronous Operation of the Timer/Counter 117
Timer/Counter Prescaler 120
Serial Peripheral Interface – SPI 121
SS Pin Functionality 125
Data Modes 127
USART 129
Overview 129
Clock Generation 130
Frame Formats 133
USART Initialization 134
Data Transmission – The USART Transmitter 136
Data Reception – The USART Receiver 138
Asynchronous Data Reception 142
Multi-processor Communication Mode 145
Accessing UBRRH/UCSRC Registers 146
USART Register Description 148
Examples of Baud Rate Setting 153
Two-wire Serial Interface 157
Features 157
Two-wire Serial Interface Bus Definition 157
Data Transfer and Frame Format 158
Multi-master Bus Systems, Arbitration and Synchronization 161
Overview of the TWI Module 163
TWI Register Description 165
Using the TWI 168
Transmission Modes 171
Multi-master Systems and Arbitration 184
Analog Comparator 186
Analog Comparator Multiplexed Input 188
Analog-to-Digital Converter 189
Features 189
Starting a Conversion 191
Prescaling and Conversion Timing 191
Changing Channel or Reference Selection 1944
2486AA–AVR–02/2013
ATmega8(L)
ADC Noise Canceler 195
ADC Conversion Result 199
Boot Loader Support – Read-While-Write Self-Programming 202
Boot Loader Features 202
Application and Boot Loader Flash Sections 202
Read-While-Write and No Read-While-Write Flash Sections 202
Boot Loader Lock Bits 204
Entering the Boot Loader Program 205
Addressing the Flash During Self-Programming 207
Self-Programming the Flash 208
Memory Programming 215
Program And Data Memory Lock Bits 215
Fuse Bits 216
Signature Bytes 218
Calibration Byte 218
Page Size 218
Parallel Programming Parameters, Pin Mapping, and Commands 219
Parallel Programming 221
Serial Downloading 230
Serial Programming Pin Mapping 230
Electrical Characteristics – TA = -40°C to 85°C 235
Absolute Maximum Ratings* 235
DC Characteristics 235
External Clock Drive Waveforms 237
External Clock Drive 237
Two-wire Serial Interface Characteristics 238
SPI Timing Characteristics 239
ADC Characteristics 241
Electrical Characteristics – TA = -40°C to 105°C 242
Absolute Maximum Ratings* 242
DC Characteristics
TA = -40C to 105C, VCC = 2.7V to 5.5V (unless otherwise noted) 242
ATmega8 Typical Characteristics – TA = -40°C to 85°C 244
ATmega8 Typical Characteristics – TA = -40°C to 105°C 282
Active Supply Current 282
Idle Supply Current 284
Power-down Supply Current 286
Pin Pull-up 287
Pin Driver Strength 289
Pin Thresholds and Hysteresis 2935
2486AA–AVR–02/2013
ATmega8(L)
Bod Thresholds and Analog Comparator Offset 298
Internal Oscillator Speed 300
Current Consumption of Peripheral Units 305
Current Consumption in Reset and Reset Pulsewidth 308
Register Summary 309
Instruction Set Summary 311
Ordering Information 314
Packaging Information 315
32A 315
28P3 316
32M1-A 317
Errata 318
ATmega8
Rev. D to I, M 318
Datasheet Revision History 320
Changes from Rev. 2486Z- 02/11 to Rev. 2486AA- 02/2013 320
Changes from Rev. 2486Y- 10/10 to Rev. 2486Z- 02/11 320
Changes from Rev. 2486X- 06/10 to Rev. 2486Y- 10/10 320
Changes from Rev. 2486W- 02/10 to Rev. 2486X- 06/10 320
Changes from Rev. 2486V- 05/09 to Rev. 2486W- 02/10 320
Changes from Rev. 2486U- 08/08 to Rev. 2486V- 05/09 320
Changes from Rev. 2486T- 05/08 to Rev. 2486U- 08/08 320
Changes from Rev. 2486S- 08/07 to Rev. 2486T- 05/08 321
Changes from Rev. 2486R- 07/07 to Rev. 2486S- 08/07 321
Changes from Rev. 2486Q- 10/06 to Rev. 2486R- 07/07 321
Changes from Rev. 2486P- 02/06 to Rev. 2486Q- 10/06 321
Changes from Rev. 2486O-10/04 to Rev. 2486P- 02/06 321
Changes from Rev. 2486N-09/04 to Rev. 2486O-10/04 322
Changes from Rev. 2486M-12/03 to Rev. 2486N-09/04 322
Changes from Rev. 2486L-10/03 to Rev. 2486M-12/03 322
Changes from Rev. 2486K-08/03 to Rev. 2486L-10/03 322
Changes from Rev. 2486J-02/03 to Rev. 2486K-08/03 323
Changes from Rev. 2486I-12/02 to Rev. 2486J-02/03 323
Changes from Rev. 2486H-09/02 to Rev. 2486I-12/02 324
Changes from Rev. 2486G-09/02 to Rev. 2486H-09/02 324
Changes from Rev. 2486F-07/02 to Rev. 2486G-09/02 324
Changes from Rev. 2486E-06/02 to Rev. 2486F-07/02 324
Changes from Rev. 2486D-03/02 to Rev. 2486E-06/02 324
Changes from Rev. 2486C-03/02 to Rev. 2486D-03/02 325
Changes from Rev. 2486B-12/01 to Rev. 2486C-03/02 3252486AA–AVR–02/2013
Atmel Corporation
1600 Technology Drive
San Jose, CA 95110
USA
Tel: (+1) (408) 441-0311
Fax: (+1) (408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 01-5 & 16, 19F
BEA Tower, Millennium City 5
418 Kwun Tong Roa
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan G.K.
16F Shin-Osaki Kangyo Bldg
1-6-4 Osaki, Shinagawa-ku
Tokyo 141-0032
JAPAN
Tel: (+81) (3) 6417-0300
Fax: (+81) (3) 6417-0370
© 2013 Atmel Corporation. All rights reserved. / Rev.: 2486AA–AVR–02/2013
Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation or its
subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
Table of Contents 1
8127F–AVR–02/2013
Features
• High Performance, Low Power AVR® 8-Bit Microcontroller
• Advanced RISC Architecture
– 54 Powerful Instructions – Most Single Clock Cycle Execution
– 16 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 12 MIPS Throughput at 12 MHz
• Non-volatile Program and Data Memories
– 512/1024 Bytes of In-System Programmable Flash Program Memory
– 32 Bytes Internal SRAM
– Flash Write/Erase Cycles: 10,000
– Data Retention: 20 Years at 85oC / 100 Years at 25oC
• Peripheral Features
– QTouch® Library Support for Capacitive Touch Sensing (1 Channel)
– One 16-bit Timer/Counter with Prescaler and Two PWM Channels
– Programmable Watchdog Timer with Separate On-chip Oscillator
– 4-channel, 8-bit Analog to Digital Converter (ATtiny5/10, only)
– On-chip Analog Comparator
• Special Microcontroller Features
– In-System Programmable (at 5V, only)
– External and Internal Interrupt Sources
– Low Power Idle, ADC Noise Reduction, and Power-down Modes
– Enhanced Power-on Reset Circuit
– Programmable Supply Voltage Level Monitor with Interrupt and Reset
– Internal Calibrated Oscillator
• I/O and Packages
– Four Programmable I/O Lines
– 6-pin SOT and 8-pad UDFN
• Operating Voltage:
– 1.8 – 5.5V
• Programming Voltage:
– 5V
• Speed Grade
– 0 – 4 MHz @ 1.8 – 5.5V
– 0 – 8 MHz @ 2.7 – 5.5V
– 0 – 12 MHz @ 4.5 – 5.5V
• Industrial and Extended Temperature Ranges
• Low Power Consumption
– Active Mode:
• 200µA at 1MHz and 1.8V
– Idle Mode:
• 25µA at 1MHz and 1.8V
– Power-down Mode:
• < 0.1µA at 1.8V
Atmel 8-bit AVR Microcontroller with 512/1024
Bytes In-System Programmable Flash
ATtiny4 / ATtiny5 / ATtiny9 / ATtiny10
Rev. 8127F–AVR–02/2013ATtiny4/5/9/10 [DATASHEET] 2
8127F–AVR–02/2013
1. Pin Configurations
Figure 1-1. Pinout of ATtiny4/5/9/10
1.1 Pin Description
1.1.1 VCC
Supply voltage.
1.1.2 GND
Ground.
1.1.3 Port B (PB3..PB0)
This is a 4-bit, bi-directional I/O port with internal pull-up resistors, individually selectable for each bit. The output
buffers have symmetrical drive characteristics, with both high sink and source capability. As inputs, the port pins
that are externally pulled low will source current if pull-up resistors are activated. Port pins are tri-stated when a
reset condition becomes active, even if the clock is not running.
The port also serves the functions of various special features of the ATtiny4/5/9/10, as listed on page 36.
1.1.4 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock
is not running and provided the reset pin has not been disabled. The minimum pulse length is given in Table 16-4
on page 118. Shorter pulses are not guaranteed to generate a reset.
The reset pin can also be used as a (weak) I/O pin.
1
2
3
6
5
4
(PCINT0/TPIDATA/OC0A/ADC0/AIN0) PB0
GND
(PCINT1/TPICLK/CLKI/ICP0/OC0B/ADC1/AIN1) PB1
PB3 (RESET/PCINT3/ADC3)
VCC
PB2 (T0/CLKO/PCINT2/INT0/ADC2)
SOT-23
1
2
3
4
8
7
6
5
(PCINT1/TPICLK/CLKI/ICP0/OC0B/ADC1/AIN1) PB1
NC
NC
GND
PB2 (T0/CLKO/PCINT2/INT0/ADC2)
VCC
PB3 (RESET/PCINT3/ADC3)
PB0 (AIN0/ADC0/OC0A/TPIDATA/PCINT0)
UDFNATtiny4/5/9/10 [DATASHEET] 3
8127F–AVR–02/2013
2. Overview
ATtiny4/5/9/10 are low-power CMOS 8-bit microcontrollers based on the compact AVR enhanced RISC architecture.
By executing powerful instructions in a single clock cycle, the ATtiny4/5/9/10 achieve throughputs
approaching 1 MIPS per MHz, allowing the system designer to optimize power consumption versus processing
speed.
Figure 2-1. Block Diagram
The AVR core combines a rich instruction set with 16 general purpose working registers and system registers. All
registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be
accessed in one single instruction executed in one clock cycle. The resulting architecture is compact and code efficient
while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
The ATtiny4/5/9/10 provide the following features: 512/1024 byte of In-System Programmable Flash, 32 bytes of
SRAM, four general purpose I/O lines, 16 general purpose working registers, a 16-bit timer/counter with two PWM
STACK
POINTER
SRAM
PROGRAM
COUNTER
PROGRAMMING
LOGIC
ISP
INTERFACE
INTERNAL
OSCILLATOR
WATCHDOG
TIMER
RESET FLAG
REGISTER
MCU STATUS
REGISTER
TIMER/
COUNTER0
CALIBRATED
OSCILLATOR
TIMING AND
CONTROL
INTERRUPT
UNIT
ANALOG
COMPARATOR ADC
GENERAL
PURPOSE
REGISTERS
X
Y
Z
ALU
STATUS
REGISTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
CONTROL
LINES
VCC RESET
DATA REGISTER
PORT B
DIRECTION
REG. PORT B
DRIVERS
PORT B
GND PB3:0
8-BIT DATA BUSATtiny4/5/9/10 [DATASHEET] 4
8127F–AVR–02/2013
channels, internal and external interrupts, a programmable watchdog timer with internal oscillator, an internal calibrated
oscillator, and four software selectable power saving modes. ATtiny5/10 are also equipped with a fourchannel,
8-bit Analog to Digital Converter (ADC).
Idle mode stops the CPU while allowing the SRAM, timer/counter, ADC (ATtiny5/10, only), analog comparator, and
interrupt system to continue functioning. ADC Noise Reduction mode minimizes switching noise during ADC conversions
by stopping the CPU and all I/O modules except the ADC. In Power-down mode registers keep their
contents and all chip functions are disabled until the next interrupt or hardware reset. In Standby mode, the oscillator
is running while the rest of the device is sleeping, allowing very fast start-up combined with low power
consumption.
The device is manufactured using Atmel’s high density non-volatile memory technology. The on-chip, in-system
programmable Flash allows program memory to be re-programmed in-system by a conventional, non-volatile
memory programmer.
The ATtiny4/5/9/10 AVR are supported by a suite of program and system development tools, including macro
assemblers and evaluation kits.
2.1 Comparison of ATtiny4, ATtiny5, ATtiny9 and ATtiny10
A comparison of the devices is shown in Table 2-1.
Table 2-1. Differences between ATtiny4, ATtiny5, ATtiny9 and ATtiny10
Device Flash ADC Signature
ATtiny4 512 bytes No 0x1E 0x8F 0x0A
ATtiny5 512 bytes Yes 0x1E 0x8F 0x09
ATtiny9 1024 bytes No 0x1E 0x90 0x08
ATtiny10 1024 bytes Yes 0x1E 0x90 0x03ATtiny4/5/9/10 [DATASHEET] 5
8127F–AVR–02/2013
3. General Information
3.1 Resources
A comprehensive set of drivers, application notes, data sheets and descriptions on development tools are available
for download at http://www.atmel.com/microcontroller/avr.
3.2 Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These
code examples assume that the part specific header file is included before compilation. Be aware that not all C
compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent.
Please confirm with the C compiler documentation for more details.
3.3 Capacitive Touch Sensing
Atmel QTouch Library provides a simple to use solution for touch sensitive interfaces on Atmel AVR microcontrollers.
The QTouch Library includes support for QTouch® and QMatrix® acquisition methods.
Touch sensing is easily added to any application by linking the QTouch Library and using the Application Programming
Interface (API) of the library to define the touch channels and sensors. The application then calls the API to
retrieve channel information and determine the state of the touch sensor.
The QTouch Library is free and can be downloaded from the Atmel website. For more information and details of
implementation, refer to the QTouch Library User Guide – also available from the Atmel website.
3.4 Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20
years at 85°C or 100 years at 25°C.ATtiny4/5/9/10 [DATASHEET] 6
8127F–AVR–02/2013
4. CPU Core
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct
program execution. The CPU must therefore be able to access memories, perform calculations, control
peripherals, and handle interrupts.
4.1 Architectural Overview
Figure 4-1. Block Diagram of the AVR Architecture
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with separate memories
and buses for program and data. Instructions in the program memory are executed with a single level pipelining.
While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept
enables instructions to be executed in every clock cycle. The program memory is In-System reprogrammable
Flash memory.
The fast-access Register File contains 16 x 8-bit general purpose working registers with a single clock cycle
access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands
are output from the Register File, the operation is executed, and the result is stored back in the Register File
– in one clock cycle.
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Program
Counter
Control Lines
16 x 8
General
Purpose
Registrers
ALU
Status
and Control
I/O Lines
Data Bus 8-bit
Data
SRAM
Direct Addressing
Indirect Addressing
Interrupt
Unit
Watchdog
Timer
Analog
Comparator
Timer/Counter 0
ADCATtiny4/5/9/10 [DATASHEET] 7
8127F–AVR–02/2013
Six of the 16 registers can be used as three 16-bit indirect address register pointers for data space addressing –
enabling efficient address calculations. One of the these address pointers can also be used as an address pointer
for look up tables in Flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register,
described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single
register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated
to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, capable of directly addressing
the whole address space. Most AVR instructions have a single 16-bit word format but 32-bit wide instructions also
exist. The actual instruction set varies, as some devices only implement a part of the instruction set.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack
is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the SRAM size
and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or
interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can
easily be accessed through the four different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in
the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have
priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the
priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other
I/O functions. The I/O memory can be accessed as the data space locations, 0x0000 - 0x003F.
4.2 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 16 general purpose working registers.
Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an
immediate are executed. The ALU operations are divided into three main categories – arithmetic, logical, and bitfunctions.
Some implementations of the architecture also provide a powerful multiplier supporting both
signed/unsigned multiplication and fractional format. See document “AVR Instruction Set” and section “Instruction
Set Summary” on page 150 for a detailed description.
4.3 Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This
information can be used for altering program flow in order to perform conditional operations. Note that the Status
Register is updated after all ALU operations, as specified in document “AVR Instruction Set” and section “Instruction
Set Summary” on page 150. This will in many cases remove the need for using the dedicated compare
instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored when returning
from an interrupt. This must be handled by software.
4.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance
and flexibility, the following input/output schemes are supported by the Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• One 16-bit output operand and one 16-bit result inputATtiny4/5/9/10 [DATASHEET] 8
8127F–AVR–02/2013
Figure 4-2 below shows the structure of the 16 general purpose working registers in the CPU.
Figure 4-2. AVR CPU General Purpose Working Registers
Note: A typical implementation of the AVR register file includes 32 general prupose registers but ATtiny4/5/9/10 implement
only 16 registers. For reasons of compatibility the registers are numbered R16...R31, not R0...R15.
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single
cycle instructions.
4.4.1 The X-register, Y-register, and Z-register
Registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit
address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are
defined as described in Figure 4-3.
Figure 4-3. The X-, Y-, and Z-registers
7 0
R16
R17
General R18
Purpose …
Working R26 X-register Low Byte
Registers R27 X-register High Byte
R28 Y-register Low Byte
R29 Y-register High Byte
R30 Z-register Low Byte
R31 Z-register High Byte
15 XH XL 0
X-register 7 07 0
R27 R26
15 YH YL 0
Y-register 7 07 0
R29 R28
15 ZH ZL 0
Z-register 7 07 0
R31 R30ATtiny4/5/9/10 [DATASHEET] 9
8127F–AVR–02/2013
In different addressing modes these address registers function as automatic increment and automatic decrement
(see document “AVR Instruction Set” and section “Instruction Set Summary” on page 150 for details).
4.5 Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses
after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the
Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a
Stack PUSH command decreases the Stack Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This
Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts
are enabled. The Stack Pointer must be set to point above 0x40. The Stack Pointer is decremented by one
when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return
address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when
data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the
Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is
implementation dependent. Note that the data space in some implementations of the AVR architecture is so small
that only SPL is needed. In this case, the SPH Register will not be present.
4.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the
CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used.
Figure 4-4. The Parallel Instruction Fetches and Instruction Executions
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture
and the fast access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with
the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit.
Figure 4-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using
two register operands is executed, and the result is stored back to the destination register.
clk
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
T1 T2 T3 T4
CPUATtiny4/5/9/10 [DATASHEET] 10
8127F–AVR–02/2013
Figure 4-5. Single Cycle ALU Operation
4.7 Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a
separate Program Vector in the program memory space. All interrupts are assigned individual enable bits which
must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the
interrupt.
The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors.
The complete list of vectors is shown in “Interrupts” on page 35. The list also determines the priority levels of the
different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next
is INT0 – the External Interrupt Request 0.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software
can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current
interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. For
these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt
handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing
a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding
interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the
flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit
is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is
set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily
have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will
not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction
before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when
returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be
executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction.
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
T1 T2 T3 T4
clkCPUATtiny4/5/9/10 [DATASHEET] 11
8127F–AVR–02/2013
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending
interrupts, as shown in the following example.
Note: See “Code Examples” on page 5.
4.7.1 Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock
cycles the Program Vector address for the actual interrupt handling routine is executed. During this four clock cycle
period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and
this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction
is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution
response time is increased by four clock cycles. This increase comes in addition to the start-up time from the
selected sleep mode.
A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program
Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG
is set.
4.8 Register Description
4.8.1 CCP – Configuration Change Protection Register
• Bits 7:0 – CCP[7:0] – Configuration Change Protection
In order to change the contents of a protected I/O register the CCP register must first be written with the correct
signature. After CCP is written the protected I/O registers may be written to during the next four CPU instruction
cycles. All interrupts are ignored during these cycles. After these cycles interrupts are automatically handled again
by the CPU, and any pending interrupts will be executed according to their priority.
When the protected I/O register signature is written, CCP[0] will read as one as long as the protected feature is
enabled, while CCP[7:1] will always read as zero.
Table 4-1 shows the signatures that are in recognised.
Assembly Code Example
sei ; set Global Interrupt Enable
sleep ; enter sleep, waiting for interrupt
; note: will enter sleep before any pending interrupt(s)
Bit 7 6 5 4 3 2 1 0
0x3C CCP[7:0] CCP
Read/Write W W W W W W W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 4-1. Signatures Recognised by the Configuration Change Protection Register
Signature Group Description
0xD8 IOREG: CLKMSR, CLKPSR, WDTCSR Protected I/O registerATtiny4/5/9/10 [DATASHEET] 12
8127F–AVR–02/2013
4.8.2 SPH and SPL — Stack Pointer Register
4.8.3 SREG – Status Register
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control
is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts
are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an
interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set
and cleared by the application with the SEI and CLI instructions, as described in the document “AVR Instruction
Set” and “Instruction Set Summary” on page 150.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated
bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be
copied into a bit in a register in the Register File by the BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful in BCD arithmetic.
See document “AVR Instruction Set” and section “Instruction Set Summary” on page 150 for detailed information.
• Bit 4 – S: Sign Bit, S = N V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement Overflow Flag V. See
document “AVR Instruction Set” and section “Instruction Set Summary” on page 150 for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See document “AVR Instruction
Set” and section “Instruction Set Summary” on page 150 for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See document “AVR Instruction
Set” and section “Instruction Set Summary” on page 150 for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See document “AVR Instruction Set” and
section “Instruction Set Summary” on page 150 for detailed information.
Bit 15 14 13 12 11 10 9 8
0x3E SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
0x3D SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
Initial Value RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
Bit 7 6 5 4 3 2 1 0
0x3F I T H S V N Z C SREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny4/5/9/10 [DATASHEET] 13
8127F–AVR–02/2013
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See document “AVR Instruction Set” and
section “Instruction Set Summary” on page 150 for detailed information.ATtiny4/5/9/10 [DATASHEET] 14
8127F–AVR–02/2013
5. Memories
This section describes the different memories in the ATtiny4/5/9/10. Devices have two main memory areas, the
program memory space and the data memory space.
5.1 In-System Re-programmable Flash Program Memory
The ATtiny4/5/9/10 contain 512/1024 bytes of on-chip, in-system reprogrammable Flash memory for program storage.
Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 256/512 x 16.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATtiny4/5/9/10 Program Counter
(PC) is 9 bits wide, thus capable of addressing the 256/512 program memory locations, starting at 0x000. “Memory
Programming” on page 106 contains a detailed description on Flash data serial downloading.
Constant tables can be allocated within the entire address space of program memory. Since program memory can
not be accessed directly, it has been mapped to the data memory. The mapped program memory begins at byte
address 0x4000 in data memory (see Figure 5-1 on page 15). Although programs are executed starting from
address 0x000 in program memory it must be addressed starting from 0x4000 when accessed via the data
memory.
Internal write operations to Flash program memory have been disabled and program memory therefore appears to
firmware as read-only. Flash memory can still be written to externally but internal write operations to the program
memory area will not be succesful.
Timing diagrams of instruction fetch and execution are presented in “Instruction Execution Timing” on page 9.
5.2 Data Memory
Data memory locations include the I/O memory, the internal SRAM memory, the non-volatile memory lock bits, and
the Flash memory. See Figure 5-1 on page 15 for an illustration on how the ATtiny4/5/9/10 memory space is
organized.
The first 64 locations are reserved for I/O memory, while the following 32 data memory locations address the internal
data SRAM.
The non-volatile memory lock bits and all the Flash memory sections are mapped to the data memory space.
These locations appear as read-only for device firmware.
The four different addressing modes for data memory are direct, indirect, indirect with pre-decrement, and indirect
with post-increment. In the register file, registers R26 to R31 function as pointer registers for indirect addressing.
The IN and OUT instructions can access all 64 locations of I/O memory. Direct addressing using the LDS and STS
instructions reaches the 128 locations between 0x0040 and 0x00BF.
The indirect addressing reaches the entire data memory space. When using indirect addressing modes with automatic
pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented.ATtiny4/5/9/10 [DATASHEET] 15
8127F–AVR–02/2013
Figure 5-1. Data Memory Map (Byte Addressing)
5.2.1 Data Memory Access Times
This section describes the general access timing concepts for internal memory access. The internal data SRAM
access is performed in two clkCPU cycles as described in Figure 5-2.
Figure 5-2. On-chip Data SRAM Access Cycles
0x0000 ... 0x003F
0x0040 ... 0x005F
0x0060 ... 0x3EFF
0x3F00 ... 0x3F01
0x3F02 ... 0x3F3F
0x3F40 ... 0x3F41
0x3F42 ... 0x3F7F
0x3F80 ... 0x3F81
0x3F82 ... 0x3FBF
0x3FC0 ... 0x3FC3
0x3FC4 ... 0x3FFF
0x4000 ... 0x41FF/0x43FF
0x4400 ... 0xFFFF
I/O SPACE
SRAM DATA MEMORY
(reserved)
NVM LOCK BITS
(reserved)
CONFIGURATION BITS
(reserved)
CALIBRATION BITS
(reserved)
DEVICE ID BITS
(reserved)
FLASH PROGRAM MEMORY
(reserved)
clk
WR
RD
Data
Data
Address Address valid
T1 T2 T3
Compute Address
Read Write
CPU
Memory Access Instruction Next InstructionATtiny4/5/9/10 [DATASHEET] 16
8127F–AVR–02/2013
5.3 I/O Memory
The I/O space definition of the ATtiny4/5/9/10 is shown in “Register Summary” on page 148.
All ATtiny4/5/9/10 I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed using the LD
and ST instructions, enabling data transfer between the 16 general purpose working registers and the I/O space.
I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In
these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. See document
“AVR Instruction Set” and section “Instruction Set Summary” on page 150 for more details. When using the I/O
specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used.
For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory
addresses should never be written.
Some of the status flags are cleared by writing a logical one to them. Note that CBI and SBI instructions will only
operate on the specified bit, and can therefore be used on registers containing such status flags. The CBI and SBI
instructions work on registers in the address range 0x00 to 0x1F, only.
The I/O and Peripherals Control Registers are explained in later sections.ATtiny4/5/9/10 [DATASHEET] 17
8127F–AVR–02/2013
6. Clock System
Figure 6-1 presents the principal clock systems and their distribution in ATtiny4/5/9/10. All of the clocks need not
be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be
halted by using different sleep modes and power reduction register bits, as described in “Power Management and
Sleep Modes” on page 23. The clock systems is detailed below.
Figure 6-1. Clock Distribution
6.1 Clock Subsystems
The clock subsystems are detailed in the sections below.
6.1.1 CPU Clock – clkCPU
The CPU clock is routed to parts of the system concerned with operation of the AVR Core. Examples of such modules
are the General Purpose Register File, the System Registers and the SRAM data memory. Halting the CPU
clock inhibits the core from performing general operations and calculations.
6.1.2 I/O Clock – clkI/O
The I/O clock is used by the majority of the I/O modules, like Timer/Counter. The I/O clock is also used by the
External Interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing
such interrupts to be detected even if the I/O clock is halted.
6.1.3 NVM clock - clkNVM
The NVM clock controls operation of the Non-Volatile Memory Controller. The NVM clock is usually active simultaneously
with the CPU clock.
CLOCK CONTROL UNIT
GENERAL
I/O MODULES
ANALOG-TO-DIGITAL
CONVERTER
CPU
CORE
WATCHDOG
TIMER
RESET
LOGIC
CLOCK
PRESCALER
RAM
CLOCK
SWITCH
NVM
CALIBRATED
OSCILLATOR
clk ADC
SOURCE CLOCK
clk I/O
clk CPU
clk NVM
WATCHDOG
CLOCK
WATCHDOG
OSCILLATOR
EXTERNAL
CLOCKATtiny4/5/9/10 [DATASHEET] 18
8127F–AVR–02/2013
6.1.4 ADC Clock – clkADC
The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce
noise generated by digital circuitry. This gives more accurate ADC conversion results.
The ADC is available in ATtiny5/10, only.
6.2 Clock Sources
All synchronous clock signals are derived from the main clock. The device has three alternative sources for the
main clock, as follows:
• Calibrated Internal 8 MHz Oscillator (see page 18)
• External Clock (see page 18)
• Internal 128 kHz Oscillator (see page 19)
See Table 6-3 on page 21 on how to select and change the active clock source.
6.2.1 Calibrated Internal 8 MHz Oscillator
The calibrated internal oscillator provides an approximately 8 MHz clock signal. Though voltage and temperature
dependent, this clock can be very accurately calibrated by the user. See Table 16-2 on page 117, Figure 17-39 on
page 141 and Figure 17-40 on page 141 for more details.
This clock may be selected as the main clock by setting the Clock Main Select bits CLKMS[1:0] in CLKMSR to
0b00. Once enabled, the oscillator will operate with no external components. During reset, hardware loads the calibration
byte into the OSCCAL register and thereby automatically calibrates the oscillator. The accuracy of this
calibration is shown as Factory calibration in Table 16-2 on page 117.
When this oscillator is used as the main clock, the watchdog oscillator will still be used for the watchdog timer and
reset time-out. For more information on the pre-programmed calibration value, see section “Calibration Section” on
page 109.
6.2.2 External Clock
To use the device with an external clock source, CLKI should be driven as shown in Figure 6-2. The external clock
is selected as the main clock by setting CLKMS[1:0] bits in CLKMSR to 0b10.
Figure 6-2. External Clock Drive Configuration
When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure
stable operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next can lead to
unpredictable behavior. It is required to ensure that the MCU is kept in reset during such changes in the clock
frequency.
EXTERNAL
CLOCK
SIGNAL
CLKI
GNDATtiny4/5/9/10 [DATASHEET] 19
8127F–AVR–02/2013
6.2.3 Internal 128 kHz Oscillator
The internal 128 kHz oscillator is a low power oscillator providing a clock of 128 kHz. The frequency depends on
supply voltage, temperature and batch variations. This clock may be select as the main clock by setting the
CLKMS[1:0] bits in CLKMSR to 0b01.
6.2.4 Switching Clock Source
The main clock source can be switched at run-time using the “CLKMSR – Clock Main Settings Register” on page
21. When switching between any clock sources, the clock system ensures that no glitch occurs in the main clock.
6.2.5 Default Clock Source
The calibrated internal 8 MHz oscillator is always selected as main clock when the device is powered up or has
been reset. The synchronous system clock is the main clock divided by 8, controlled by the System Clock Prescaler.
The Clock Prescaler Select Bits can be written later to change the system clock frequency. See “System
Clock Prescaler”.
6.3 System Clock Prescaler
The system clock is derived from the main clock via the System Clock Prescaler. The system clock can be divided
by setting the “CLKPSR – Clock Prescale Register” on page 22. The system clock prescaler can be used to
decrease power consumption at times when requirements for processing power is low or to bring the system clock
within limits of maximum frequency. The prescaler can be used with all main clock source options, and it will affect
the clock frequency of the CPU and all synchronous peripherals.
The System Clock Prescaler can be used to implement run-time changes of the internal clock frequency while still
ensuring stable operation.
6.3.1 Switching Prescaler Setting
When switching between prescaler settings, the system clock prescaler ensures that no glitch occurs in the system
clock and that no intermediate frequency is higher than neither the clock frequency corresponding the previous setting,
nor the clock frequency corresponding to the new setting.
The ripple counter that implements the prescaler runs at the frequency of the main clock, which may be faster than
the CPU's clock frequency. Hence, it is not possible to determine the state of the prescaler - even if it were readable,
and the exact time it takes to switch from one clock division to another cannot be exactly predicted.
From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2*T2 before the new clock frequency
is active. In this interval, two active clock edges are produced. Here, T1 is the previous clock period, and
T2 is the period corresponding to the new prescaler setting.ATtiny4/5/9/10 [DATASHEET] 20
8127F–AVR–02/2013
6.4 Starting
6.4.1 Starting from Reset
The internal reset is immediately asserted when a reset source goes active. The internal reset is kept asserted until
the reset source is released and the start-up sequence is completed. The start-up sequence includes three steps,
as follows.
1. The first step after the reset source has been released consists of the device counting the reset start-up
time. The purpose of this reset start-up time is to ensure that supply voltage has reached sufficient levels.
The reset start-up time is counted using the internal 128 kHz oscillator. See Table 6-1 for details of reset
start-up time.
Note that the actual supply voltage is not monitored by the start-up logic. The device will count until the
reset start-up time has elapsed even if the device has reached sufficient supply voltage levels earlier.
2. The second step is to count the oscillator start-up time, which ensures that the calibrated internal oscillator
has reached a stable state before it is used by the other parts of the system. The calibrated internal oscillator
needs to oscillate for a minimum number of cycles before it can be considered stable. See Table 6-1
for details of the oscillator start-up time.
3. The last step before releasing the internal reset is to load the calibration and the configuration values from
the Non-Volatile Memory to configure the device properly. The configuration time is listed in Table 6-1.
Notes: 1. After powering up the device or after a reset the system clock is automatically set to calibrated internal 8 MHz oscillator,
divided by 8
6.4.2 Starting from Power-Down Mode
When waking up from Power-Down sleep mode, the supply voltage is assumed to be at a sufficient level and only
the oscillator start-up time is counted to ensure the stable operation of the oscillator. The oscillator start-up time is
counted on the selected main clock, and the start-up time depends on the clock selected. See Table 6-2 for details.
Notes: 1. The start-up time is measured in main clock oscillator cycles.
6.4.3 Starting from Idle / ADC Noise Reduction / Standby Mode
When waking up from Idle, ADC Noise Reduction or Standby Mode, the oscillator is already running and no oscillator
start-up time is introduced.
The ADC is available in ATtiny5/10, only.
Table 6-1. Start-up Times when Using the Internal Calibrated Oscillator
Reset Oscillator Configuration Total start-up time
64 ms 6 cycles 21 cycles 64 ms + 6 oscillator cycles + 21 system clock cycles (1)
Table 6-2. Start-up Time from Power-Down Sleep Mode.
Oscillator start-up time Total start-up time
6 cycles 6 oscillator cycles (1)ATtiny4/5/9/10 [DATASHEET] 21
8127F–AVR–02/2013
6.5 Register Description
6.5.1 CLKMSR – Clock Main Settings Register
• Bit 7:2 – Res: Reserved Bits
These bits are reserved and always read zero.
• Bit 1:0 – CLKMS[1:0]: Clock Main Select Bits
These bits select the main clock source of the system. The bits can be written at run-time to switch the source of
the main clock. The clock system ensures glitch free switching of the main clock source.
The main clock alternatives are shown in Table 6-3.
To avoid unintentional switching of main clock source, a protected change sequence must be followed to change
the CLKMS bits, as follows:
1. Write the signature for change enable of protected I/O register to register CCP
2. Within four instruction cycles, write the CLKMS bits with the desired value
6.5.2 OSCCAL – Oscillator Calibration Register .
• Bits 7:0 – CAL[7:0]: Oscillator Calibration Value
The oscillator calibration register is used to trim the calibrated internal oscillator and remove process variations
from the oscillator frequency. A pre-programmed calibration value is automatically written to this register during
chip reset, giving the factory calibrated frequency as specified in Table 16-2, “Calibration Accuracy of Internal RC
Oscillator,” on page 117.
The application software can write this register to change the oscillator frequency. The oscillator can be calibrated
to frequencies as specified in Table 16-2, “Calibration Accuracy of Internal RC Oscillator,” on page 117. Calibration
outside the range given is not guaranteed.
The CAL[7:0] bits are used to tune the frequency of the oscillator. A setting of 0x00 gives the lowest frequency, and
a setting of 0xFF gives the highest frequency.
Bit 7 6 5 4 3 2 1 0
0x37 – – – – – – CLKMS1 CLKMS0 CLKMSR
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 6-3. Selection of Main Clock
CLKM1 CLKM0 Main Clock Source
0 0 Calibrated Internal 8 MHzOscillator
0 1 Internal 128 kHz Oscillator (WDT Oscillator)
1 0 External clock
1 1 Reserved
Bit 7 6 5 4 3 2 1 0
0x39 CAL7 CAL6 CAL5 CAL4 CAL3 CAL2 CAL1 CAL0 OSCCAL
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value X X X X X X X XATtiny4/5/9/10 [DATASHEET] 22
8127F–AVR–02/2013
6.5.3 CLKPSR – Clock Prescale Register
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read as zero.
• Bits 3:0 – CLKPS[3:0]: Clock Prescaler Select Bits 3 - 0
These bits define the division factor between the selected clock source and the internal system clock. These bits
can be written at run-time to vary the clock frequency and suit the application requirements. As the prescaler
divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced accordingly. The
division factors are given in Table 6-4.
To avoid unintentional changes of clock frequency, a protected change sequence must be followed to change the
CLKPS bits:
1. Write the signature for change enable of protected I/O register to register CCP
2. Within four instruction cycles, write the desired value to CLKPS bits
At start-up, CLKPS bits are reset to 0b0011 to select the clock division factor of 8. If the selected clock source has
a frequency higher than the maximum allowed the application software must make sure a sufficient division factor
is used. To make sure the write procedure is not interrupted, interrupts must be disabled when changing prescaler
settings.
Bit 7 6 5 4 3 2 1 0
0x36 – – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 CLKPSR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 1 1
Table 6-4. Clock Prescaler Select
CLKPS3 CLKPS2 CLKPS1 CLKPS0 Clock Division Factor
0000 1
0001 2
0010 4
0 0 1 1 8 (default)
0 1 0 0 16
0 1 0 1 32
0 1 1 0 64
0 1 1 1 128
1 0 0 0 256
1 0 0 1 Reserved
1 0 1 0 Reserved
1 0 1 1 Reserved
1 1 0 0 Reserved
1 1 0 1 Reserved
1 1 1 0 Reserved
1 1 1 1 ReservedATtiny4/5/9/10 [DATASHEET] 23
8127F–AVR–02/2013
7. Power Management and Sleep Modes
The high performance and industry leading code efficiency makes the AVR microcontrollers an ideal choise for low
power applications. In addition, sleep modes enable the application to shut down unused modules in the MCU,
thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to
the application’s requirements.
7.1 Sleep Modes
Figure 6-1 on page 17 presents the different clock systems and their distribution in ATtiny4/5/9/10. The figure is
helpful in selecting an appropriate sleep mode. Table 7-1 shows the different sleep modes and their wake up
sources.
Note: 1. The ADC is available in ATtiny5/10, only
2. For INT0, only level interrupt.
To enter any of the four sleep modes, the SE bits in SMCR must be written to logic one and a SLEEP instruction
must be executed. The SM2:0 bits in the SMCR register select which sleep mode (Idle, ADC Noise Reduction,
Standby or Power-down) will be activated by the SLEEP instruction. See Table 7-2 for a summary.
If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for
four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction
following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from
sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector.
Note that if a level triggered interrupt is used for wake-up the changed level must be held for some time to wake up
the MCU (and for the MCU to enter the interrupt service routine). See “External Interrupts” on page 36 for details.
7.1.1 Idle Mode
When bits SM2:0 are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but
allowing the analog comparator, timer/counter, watchdog, and the interrupt system to continue operating. This
sleep mode basically halts clkCPU and clkNVM, while allowing the other clocks to run.
Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the timer
overflow. If wake-up from the analog comparator interrupt is not required, the analog comparator can be powered
down by setting the ACD bit in “ACSR – Analog Comparator Control and Status Register” on page 80. This will
reduce power consumption in idle mode. If the ADC is enabled (ATtiny5/10, only), a conversion starts automatically
when this mode is entered.
Table 7-1. Active Clock Domains and Wake-up Sources in Different Sleep Modes
Sleep Mode
Active Clock Domains Oscillators Wake-up Sources clkCPU clkNVM clkIO clkADC (1) Main Clock Source Enabled INT0 and Pin Change ADC (1) Other I/O Watchdog Interrupt
VLM Interrupt
Idle X X X X X X X X
ADC Noise Reduction X X X (2) X XX
Standby X X (2) X
Power-down X (2) XATtiny4/5/9/10 [DATASHEET] 24
8127F–AVR–02/2013
7.1.2 ADC Noise Reduction Mode
When bits SM2:0 are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode,
stopping the CPU but allowing the ADC, the external interrupts, and the watchdog to continue operating (if
enabled). This sleep mode halts clkI/O, clkCPU, and clkNVM, while allowing the other clocks to run.
This mode improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is
enabled, a conversion starts automatically when this mode is entered.
This mode is available in all devices, although only ATtiny5/10 are equipped with an ADC.
7.1.3 Power-down Mode
When bits SM2:0 are written to 010, the SLEEP instruction makes the MCU enter Power-down mode. In this mode,
the oscillator is stopped, while the external interrupts, and the watchdog continue operating (if enabled). Only a
watchdog reset, an external level interrupt on INT0, or a pin change interrupt can wake up the MCU. This sleep
mode halts all generated clocks, allowing operation of asynchronous modules only.
7.1.4 Standby Mode
When bits SM2:0 are written to 100, the SLEEP instruction makes the MCU enter Standby mode. This mode is
identical to Power-down with the exception that the oscillator is kept running. This reduces wake-up time, because
the oscillator is already running and doesn't need to be started up.
7.2 Power Reduction Register
The Power Reduction Register (PRR), see “PRR – Power Reduction Register” on page 26, provides a method to
reduce power consumption by stopping the clock to individual peripherals. When the clock for a peripheral is
stopped then:
• The current state of the peripheral is frozen.
• The associated registers can not be read or written.
• Resources used by the peripheral will remain occupied.
The peripheral should in most cases be disabled before stopping the clock. Clearing the PRR bit wakes up the
peripheral and puts it in the same state as before shutdown.
Peripheral shutdown can be used in Idle mode and Active mode to significantly reduce the overall power consumption.
See “Supply Current of I/O Modules” on page 121 for examples. In all other sleep modes, the clock is already
stopped.
7.3 Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR Core controlled
system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so
that as few as possible of the device’s functions are operating. All functions not needed should be disabled. In particular,
the following modules may need special consideration when trying to achieve the lowest possible power
consumption.
7.3.1 Analog Comparator
When entering Idle mode, the analog comparator should be disabled if not used. In the power-down mode, the
analog comparator is automatically disabled. See “Analog Comparator” on page 80 for further details.ATtiny4/5/9/10 [DATASHEET] 25
8127F–AVR–02/2013
7.3.2 Analog to Digital Converter
If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be disabled before entering
any sleep mode. When the ADC is turned off and on again, the next conversion will be an extended conversion.
See “Analog to Digital Converter” on page 82 for details on ADC operation.
The ADC is available in ATtiny5/10, only.
7.3.3 Watchdog Timer
If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is
enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this
will contribute significantly to the total current consumption. Refer to “Watchdog Timer” on page 30 for details on
how to configure the Watchdog Timer.
7.3.4 Port Pins
When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing
is then to ensure that no pins drive resistive loads. In sleep modes where the I/O clock (clkI/O) is stopped, the input
buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed.
In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. Refer to the
section “Digital Input Enable and Sleep Modes” on page 44 for details on which pins are enabled. If the input buffer
is enabled and the input signal is left floating or has an analog signal level close to VCC/2, the input buffer will use
excessive power.
For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VCC/2
on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to
the Digital Input Disable Register (DIDR0). Refer to “DIDR0 – Digital Input Disable Register 0” on page 81 for
details.
7.4 Register Description
7.4.1 SMCR – Sleep Mode Control Register
The SMCR Control Register contains control bits for power management.
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 3:1 – SM2..SM0: Sleep Mode Select Bits 2..0
These bits select between available sleep modes, as shown in Table 7-2.
Bit 7 6 5 4 3 2 1 0
0x3A – – – – SM2 SM1 SM0 SE SMCR
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
Table 7-2. Sleep Mode Select
SM2 SM1 SM0 Sleep Mode
0 0 0 Idle
0 0 1 ADC noise reduction (1)
0 1 0 Power-down
0 1 1 Reserved
1 0 0 StandbyATtiny4/5/9/10 [DATASHEET] 26
8127F–AVR–02/2013
Note: 1. This mode is available in all devices, although only ATtiny5/10 are equipped with an ADC
• Bit 0 – SE: Sleep Enable
The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed.
To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to
write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately
after waking up.
7.4.2 PRR – Power Reduction Register
• Bits 7:2 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 1 – PRADC: Power Reduction ADC
Writing a logic one to this bit shuts down the ADC. The ADC must be disabled before shut down. The analog comparator
cannot use the ADC input MUX when the ADC is shut down.
The ADC is available in ATtiny5/10, only.
• Bit 0 – PRTIM0: Power Reduction Timer/Counter0
Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation
will continue like before the shutdown.
1 0 1 Reserved
1 1 0 Reserved
1 1 1 Reserved
Table 7-2. Sleep Mode Select
SM2 SM1 SM0 Sleep Mode
Bit 7 6 5 4 3 2 1 0
0x35 – – – – – – PRADC PRTIM0 PRR
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny4/5/9/10 [DATASHEET] 27
8127F–AVR–02/2013
8. System Control and Reset
8.1 Resetting the AVR
During reset, all I/O registers are set to their initial values, and the program starts execution from the Reset Vector.
The instruction placed at the Reset Vector must be a RJMP – Relative Jump – instruction to the reset handling routine.
If the program never enables an interrupt source, the interrupt vectors are not used, and regular program code
can be placed at these locations. The circuit diagram in Figure 8-1 shows the reset logic. Electrical parameters of
the reset circuitry are defined in section “System and Reset Characteristics” on page 118.
Figure 8-1. Reset Logic
The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not
require any clock source to be running.
After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the
power to reach a stable level before normal operation starts. The start up sequence is described in “Starting from
Reset” on page 20.
8.2 Reset Sources
The ATtiny4/5/9/10 have three sources of reset:
• Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset threshold (VPOT)
• External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum
pulse length
• Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled
8.2.1 Power-on Reset
A Power-on Reset (POR) pulse is generated by an on-chip detection circuit. The detection level is defined in section
“System and Reset Characteristics” on page 118. The POR is activated whenever VCC is below the detection
level. The POR circuit can be used to trigger the Start-up Reset, as well as to detect a failure in supply voltage.
Reset Flag Register
(RSTFLR)
CK Delay Counters
TIMEOUT
WDRF
EXTRF
PORF
DATA BUS
Clock
Generator
SPIKE
FILTER
Pull-up Resistor
Watchdog
Oscillator
Power-on Reset
Circuit
VLMATtiny4/5/9/10 [DATASHEET] 28
8127F–AVR–02/2013
A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the Power-on Reset
threshold voltage invokes the delay counter, which determines how long the device is kept in reset after VCC rise.
The reset signal is activated again, without any delay, when VCC decreases below the detection level.
Figure 8-2. MCU Start-up, RESET Tied to VCC
Figure 8-3. MCU Start-up, RESET Extended Externally
8.2.2 VCC Level Monitoring
ATtiny4/5/9/10 have a VCC Level Monitoring (VLM) circuit that compares the voltage level at the VCC pin against
fixed trigger levels. The trigger levels are set with VLM2:0 bits, see “VLMCSR – VCC Level Monitoring Control and
Status register” on page 33.
The VLM circuit provides a status flag, VLMF, that indicates if voltage on the VCC pin is below the selected trigger
level. The flag can be read from VLMCSR, but it is also possible to have an interrupt generated when the VLMF
status flag is set. This interrupt is enabled by the VLMIE bit in the VLMCSR register. The flag can be cleared by
changing the trigger level or by writing it to zero. The flag is automatically cleared when the voltage at VCC rises
back above the selected trigger level.
The VLM can also be used to improve reset characteristics at falling supply. Without VLM, the Power-On Reset
(POR) does not activate before supply voltage has dropped to a level where the MCU is not necessarily functional
any more. With VLM, it is possible to generate a reset earlier.
When active, the VLM circuit consumes some power, as illustrated in Figure 17-48 on page 145. To save power
the VLM circuit can be turned off completely, or it can be switched on and off at regular intervals. However, detection
takes some time and it is therefore recommended to leave the circuitry on long enough for signals to settle.
See “VCC Level Monitor” on page 118.
V
TIME-OUT
RESET
RESET
TOUT
INTERNAL
t
VPOT
VRST
CC
V
TIME-OUT
TOUT
TOUT
INTERNAL
CC
t
VPOT
VRST
> t
RESET
RESETATtiny4/5/9/10 [DATASHEET] 29
8127F–AVR–02/2013
When VLM is active and voltage at VCC is above the selected trigger level operation will be as normal and the VLM
can be shut down for a short period of time. If voltage at VCC drops below the selected threshold the VLM will either
flag an interrupt or generate a reset, depending on the configuration.
When the VLM has been configured to generate a reset at low supply voltage it will keep the device in reset as long
as VCC is below the reset level. See Table 8-4 on page 34 for reset level details. If supply voltage rises above the
reset level the condition is removed and the MCU will come out of reset, and initiate the power-up start-up
sequence.
If supply voltage drops enough to trigger the POR then PORF is set after supply voltage has been restored.
8.2.3 External Reset
An External Reset is generated by a low level on the RESET pin if enabled. Reset pulses longer than the minimum
pulse width (see section “System and Reset Characteristics” on page 118) will generate a reset, even if the clock is
not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset
Threshold Voltage – VRST – on its positive edge, the delay counter starts the MCU after the time-out period – tTOUT
– has expired. External reset is ignored during Power-on start-up count. After Power-on reset the internal reset is
extended only if RESET pin is low when the initial Power-on delay count is complete. See Figure 8-2 and Figure 8-
3 on page 28.
Figure 8-4. External Reset During Operation
8.2.4 Watchdog Reset
When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of
this pulse, the delay timer starts counting the time-out period tTOUT. See page 30 for details on operation of the
Watchdog Timer and Table 16-4 on page 118 for details on reset time-out.
CCATtiny4/5/9/10 [DATASHEET] 30
8127F–AVR–02/2013
Figure 8-5. Watchdog Reset During Operation
8.3 Watchdog Timer
The Watchdog Timer is clocked from an on-chip oscillator, which runs at 128 kHz. See Figure 8-6. By controlling
the Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as shown in Table 8-2 on page 32.
The WDR – Watchdog Reset – instruction resets the Watchdog Timer. The Watchdog Timer is also reset when it is
disabled and when a device reset occurs. Ten different clock cycle periods can be selected to determine the reset
period. If the reset period expires without another Watchdog Reset, the ATtiny4/5/9/10 resets and executes from
the Reset Vector. For timing details on the Watchdog Reset, refer to Table 8-3 on page 33.
Figure 8-6. Watchdog Timer
The Wathdog Timer can also be configured to generate an interrupt instead of a reset. This can be very helpful
when using the Watchdog to wake-up from Power-down.
To prevent unintentional disabling of the Watchdog or unintentional change of time-out period, two different safety
levels are selected by the fuse WDTON as shown in Table 8-1 on page 31. See “Procedure for Changing the
Watchdog Timer Configuration” on page 31 for details.
CK
CC
OSC/2K
OSC/4K
OSC/8K
OSC/16K
OSC/32K
OSC/64K
OSC/128K
OSC/256K
OSC/512K
OSC/1024K
MCU RESET
WATCHDOG
PRESCALER
128 kHz
OSCILLATOR
WATCHDOG
RESET
WDP0
WDP1
WDP2
WDP3
WDE
MUXATtiny4/5/9/10 [DATASHEET] 31
8127F–AVR–02/2013
8.3.1 Procedure for Changing the Watchdog Timer Configuration
The sequence for changing configuration differs between the two safety levels, as follows:
8.3.1.1 Safety Level 1
In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the WDE bit to one without any
restriction. A special sequence is needed when disabling an enabled Watchdog Timer. To disable an enabled
Watchdog Timer, the following procedure must be followed:
1. Write the signature for change enable of protected I/O registers to register CCP
2. Within four instruction cycles, in the same operation, write WDE and WDP bits
8.3.1.2 Safety Level 2
In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read as one. A protected change
is needed when changing the Watchdog Time-out period. To change the Watchdog Time-out, the following procedure
must be followed:
1. Write the signature for change enable of protected I/O registers to register CCP
2. Within four instruction cycles, write the WDP bit. The value written to WDE is irrelevant
8.3.2 Code Examples
The following code example shows how to turn off the WDT. The example assumes that interrupts are controlled
(e.g., by disabling interrupts globally) so that no interrupts will occur during execution of these functions.
Note: See “Code Examples” on page 5.
Table 8-1. WDT Configuration as a Function of the Fuse Settings of WDTON
WDTON
Safety
Level
WDT
Initial State
How to
Disable the WDT
How to
Change Time-out
Unprogrammed 1 Disabled Protected change
sequence
No limitations
Programmed 2 Enabled Always enabled Protected change
sequence
Assembly Code Example
WDT_off:
wdr
; Clear WDRF in RSTFLR
in r16, RSTFLR
andi r16, ~(1<
Table 9-1. Reset and Interrupt Vectors
Vector No. Program Address Label Interrupt Source
1 0x0000 RESET External Pin, Power-on Reset,
VLM Reset, Watchdog Reset
2 0x0001 INT0 External Interrupt Request 0
3 0x0002 PCINT0 Pin Change Interrupt Request 0
4 0x0003 TIM0_CAPT Timer/Counter0 Input Capture
5 0x0004 TIM0_OVF Timer/Counter0 Overflow
6 0x0005 TIM0_COMPA Timer/Counter0 Compare Match A
7 0x0006 TIM0_COMPB Timer/Counter0 Compare Match B
8 0x0007 ANA_COMP Analog Comparator
9 0x0008 WDT Watchdog Time-out
10 0x0009 VLM VCC Voltage Level Monitor
11 0x000A ADC ADC Conversion Complete (1)ATtiny4/5/9/10 [DATASHEET] 36
8127F–AVR–02/2013
0x000B RESET: ldi r16, high(RAMEND); Main program start
0x000C out SPH,r16 ; Set Stack Pointer
0x000D ldi r16, low(RAMEND) ; to top of RAM
0x000E out SPL,r16
0x000F sei ; Enable interrupts
0x0010
... ...
9.2 External Interrupts
External Interrupts are triggered by the INT0 pin or any of the PCINT3..0 pins. Observe that, if enabled, the interrupts
will trigger even if the INT0 or PCINT3..0 pins are configured as outputs. This feature provides a way of
generating a software interrupt. Pin change 0 interrupts PCI0 will trigger if any enabled PCINT3..0 pin toggles. The
PCMSK Register controls which pins contribute to the pin change interrupts. Pin change interrupts on PCINT3..0
are detected asynchronously, which means that these interrupts can be used for waking the part also from sleep
modes other than Idle mode.
The INT0 interrupt can be triggered by a falling or rising edge or a low level. This is set up as shown in “EICRA –
External Interrupt Control Register A” on page 37. When the INT0 interrupt is enabled and configured as level triggered,
the interrupt will trigger as long as the pin is held low. Note that recognition of falling or rising edge interrupts
on INT0 requires the presence of an I/O clock, as described in “Clock System” on page 17.
9.2.1 Low Level Interrupt
A low level interrupt on INT0 is detected asynchronously. This means that the interrupt source can be used for
waking the part also from sleep modes other than Idle (the I/O clock is halted in all sleep modes except Idle).
Note that if a level triggered interrupt is used for wake-up from Power-down, the required level must be held long
enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of
the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined as
described in “Clock System” on page 17.
If the low level on the interrupt pin is removed before the device has woken up then program execution will not be
diverted to the interrupt service routine but continue from the instruction following the SLEEP command.
9.2.2 Pin Change Interrupt Timing
A timing example of a pin change interrupt is shown in Figure 9-1.ATtiny4/5/9/10 [DATASHEET] 37
8127F–AVR–02/2013
Figure 9-1. Timing of pin change interrupts
9.3 Register Description
9.3.1 EICRA – External Interrupt Control Register A
The External Interrupt Control Register A contains control bits for interrupt sense control.
• Bits 7:2 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 1:0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt
mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 9-2. The
value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer
than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
PCINT(0)
pin_sync
pcint_syn pin_lat D Q
LE
pcint_setflag
PCIF
clk
clk PCINT(0) in PCMSK(x)
pcint_in_(0) 0
x
Bit 7 6 5 4 3 2 1 0
0x15 – – – – – – ISC01 ISC00 EICRA
Read/Write R R R R R R R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny4/5/9/10 [DATASHEET] 38
8127F–AVR–02/2013
low level interrupt is selected, the low level must be held until the completion of the currently executing instruction
to generate an interrupt.
9.3.2 EIMSK – External Interrupt Mask Register
• Bits 7:1 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 0 – INT0: External Interrupt Request 0 Enable
When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is
enabled. The Interrupt Sense Control bits (ISC01 and ISC00) in the External Interrupt Control Register A (EICRA)
define whether the external interrupt is activated on rising and/or falling edge of the INT0 pin or level sensed. Activity
on the pin will cause an interrupt request even if INT0 is configured as an output. The corresponding interrupt of
External Interrupt Request 0 is executed from the INT0 Interrupt Vector.
9.3.3 EIFR – External Interrupt Flag Register
• Bits 7:1 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 0 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pin triggers an interrupt request, INTF0 becomes set (one). If the I-bit in
SREG and the INT0 bit in EIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector.
The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical
one to it.
This flag is constantly zero when INT0 is configured as a level interrupt.
Table 9-2. Interrupt 0 Sense Control
ISC01 ISC00 Description
0 0 The low level of INT0 generates an interrupt request.
0 1 Any logical change on INT0 generates an interrupt request.
1 0 The falling edge of INT0 generates an interrupt request.
1 1 The rising edge of INT0 generates an interrupt request.
Bit 7 6 5 4 3 2 1 0
0x13 – – – – – – – INTO EIMSK
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x14 – – – – – – – INTF0 EIFR
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny4/5/9/10 [DATASHEET] 39
8127F–AVR–02/2013
9.3.4 PCICR – Pin Change Interrupt Control Register
• Bits 7:1 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 0 – PCIE0: Pin Change Interrupt Enable 0
When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 0 is
enabled. Any change on any enabled PCINT3..0 pin will cause an interrupt. The corresponding interrupt of Pin
Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT3..0 pins are enabled individually by
the PCMSK Register.
9.3.5 PCIFR – Pin Change Interrupt Flag Register
• Bits 7:1 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bit 0 – PCIF0: Pin Change Interrupt Flag 0
When a logic change on any PCINT3..0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in
SREG and the PCIE0 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag
is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it.
9.3.6 PCMSK – Pin Change Mask Register
• Bits 7:4 – Res: Reserved Bits
These bits are reserved and will always read zero.
• Bits 3:0 – PCINT3..0: Pin Change Enable Mask 3..0
Each PCINT3..0 bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT3..0 is
set and the PCIE0 bit in PCICR is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT3..0 is
cleared, pin change interrupt on the corresponding I/O pin is disabled.
Bit 7 6 5 4 3 2 1 0
0x12 – – – – – – – PCIE0 PCICR
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x11 – – – – – – – PCIF0 PCIFR
Read/Write R R R R R R R R/W
Initial Value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x10 – – – – PCINT3 PCINT2 PCINT1 PCINT0 PCMSK
Read/Write R R R R R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0ATtiny4/5/9/10 [DATASHEET] 40
8127F–AVR–02/2013
10. I/O Ports
10.1 Overview
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that
the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the
SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling
of pull-up resistors. Each output buffer has symmetrical drive characteristics with both high sink and source
capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable
pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VCC and
Ground as indicated in Figure 10-1 on page 40. See “Electrical Characteristics” on page 115 for a complete list of
parameters.
Figure 10-1. I/O Pin Equivalent Schematic
All registers and bit references in this section are written in general form. A lower case “x” represents the numbering
letter for the port, and a lower case “n” represents the bit number. However, when using the register or bit
defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented
generally as PORTxn. The physical I/O Registers and bit locations are listed in “Register Description” on
page 50.
Four I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data
Direction Register – DDRx, Pull-up Enable Register – PUEx, and the Port Input Pins – PINx. The Port Input Pins
I/O location is read only, while the Data Register, the Data Direction Register, and the Pull-up Enable Register are
read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit
in the Data Register.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on page 41. Most port pins
are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes
with the port pin is described in “Alternate Port Functions” on page 45. Refer to the individual module sections
for a full description of the alternate functions.
Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port
as general digital I/O.
Cpin
Logic
Rpu
See Figure
"General Digital I/O" for
Details
PxnATtiny4/5/9/10 [DATASHEET] 41
8127F–AVR–02/2013
10.2 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional description of
one I/O-port pin, here generically called Pxn.
Figure 10-2. General Digital I/O(1)
Note: 1. WEx, WRx, WPx, WDx, REx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, and SLEEP
are common to all ports.
10.2.1 Configuring the Pin
Each port pin consists of four register bits: DDxn, PORTxn, PUExn, and PINxn. As shown in “Register Description”
on page 50, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, the
PUExn bits at the PUEx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured
as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.
clk
RPx
RRx
RDx
WDx
WEx
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
clkI/O: I/O CLOCK
RDx: READ DDRx
WEx: WRITE PUEx
REx: READ PUEx
D
L
Q
Q
REx
RESET
RESET
Q
D Q
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BUS
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
WPx
RESET
Q
Q D
CLR
PUExn
0
1
WRx
WPx: WRITE PINx REGISTERATtiny4/5/9/10 [DATASHEET] 42
8127F–AVR–02/2013
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If
PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero).
The pull-up resistor is activated, if the PUExn is written logic one. To switch the pull-up resistor off, PUExn has to
be written logic zero.
Table 10-1 summarizes the control signals for the pin value.
Port pins are tri-stated when a reset condition becomes active, even when no clocks are running.
10.2.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.
10.2.3 Break-Before-Make Switching
In Break-Before-Make mode, switching the DDRxn bit from input to output introduces an immediate tri-state period
lasting one system clock cycle, as indicated in Figure 10-3. For example, if the system clock is 4 MHz and the
DDRxn is written to make an output, an immediate tri-state period of 250 ns is introduced before the value of
PORTxn is seen on the port pin.
To avoid glitches it is recommended that the maximum DDRxn toggle frequency is two system clock cycles. The
Break-Before-Make mode applies to the entire port and it is activated by the BBMx bit. For more details, see
“PORTCR – Port Control Register” on page 50.
When switching the DDRxn bit from output to input no immediate tri-state period is introduced.
Table 10-1. Port Pin Configurations
DDxn PORTxn PUExn I/O Pull-up Comment
0 X 0 Input No Tri-state (hi-Z)
0 X 1 Input Yes Sources current if pulled low externally
1 0 0 Output No Output low (sink)
1 0 1 Output Yes
NOT RECOMMENDED.
Output low (sink) and internal pull-up active.
Sources current through the internal pull-up
resistor and consumes power constantly
1 1 0 Output No Output high (source)
1 1 1 Output Yes Output high (source) and internal pull-up activeATtiny4/5/9/10 [DATASHEET] 43
8127F–AVR–02/2013
Figure 10-3. Switching Between Input and Output in Break-Before-Make-Mode
10.2.4 Reading the Pin Value
Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As
shown in Figure 10-2 on page 41, the PINxn Register bit and the preceding latch constitute a synchronizer. This is
needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces
a delay. Figure 10-4 shows a timing diagram of the synchronization when reading an externally applied pin
value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
Figure 10-4. Synchronization when Reading an Externally Applied Pin value
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when
the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the “SYNC
LATCH” signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at
the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition
on the pin will be delayed between ½ and 1½ system clock period depending upon the time of assertion.
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 10-5
on page 44. The out instruction sets the “SYNC LATCH” signal at the positive edge of the clock. In this case, the
delay tpd through the synchronizer is one system clock period.
out DDRx, r16 nop
0x02 0x01
SYSTEM CLK
INSTRUCTIONS
DDRx
intermediate tri-state cycle
out DDRx, r17
PORTx 0x55
0x01
intermediate tri-state cycle
Px0
Px1
tri-state
tri-state tri-state
r17 0x01
r16 0x02
XXX in r17, PINx
0x00 0xFF
INSTRUCTIONS
SYNC LATCH
PINxn
r17
XXX
SYSTEM CLK
tpd, max
tpd, minATtiny4/5/9/10 [DATASHEET] 44
8127F–AVR–02/2013
Figure 10-5. Synchronization when Reading a Software Assigned Pin Value
10.2.5 Digital Input Enable and Sleep Modes
As shown in Figure 10-2 on page 41, the digital input signal can be clamped to ground at the input of the schmitttrigger.
The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down and Standby
modes to avoid high power consumption if some input signals are left floating, or have an analog signal level close
to VCC/2.
SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled,
SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in
“Alternate Port Functions” on page 45.
If a logic high level (“one”) is present on an asynchronous external interrupt pin configured as “Interrupt on Rising
Edge, Falling Edge, or Any Logic Change on Pin” while the external interrupt is not enabled, the corresponding
External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these
sleep mode produces the requested logic change.
10.2.6 Unconnected Pins
If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of
the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to
reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle
mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the
pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use
an external pull-up or pulldown. Connecting unused pins directly to VCC or GND is not recommended, since this
may cause excessive currents if the pin is accidentally configured as an output.
out PORTx, r16 nop in r17, PINx
0xFF
0x00 0xFF
SYSTEM CLK
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
t pdATtiny4/5/9/10 [DATASHEET] 45
8127F–AVR–02/2013
10.2.7 Program Example
The following code example shows how to set port B pin 0 high, pin 1 low, and define the port pins from 2 to 3 as
input with a pull-up assigned to port pin 2. The resulting pin values are read back again, but as previously discussed,
a nop instruction is included to be able to read back the value recently assigned to some of the pins.
Note: See “Code Examples” on page 5.
10.3 Alternate Port Functions
Most port pins have alternate functions in addition to being general digital I/Os. In Figure 10-6 below is shown how
the port pin control signals from the simplified Figure 10-2 on page 41 can be overridden by alternate functions.
Assembly Code Example
...
; Define pull-ups and set outputs high
; Define directions for port pins
ldi r16,(1<> Cx must be observed for proper operation; a typical load capacitance (Cx) ranges from
5 – 20 pF while Cs is usually about 2 – 50 nF.
Increasing amounts of Cx destroy gain, therefore it is important to limit the amount of stray capacitance on both SNS
terminals. This can be done, for example, by minimizing trace lengths and widths and keeping these traces away
from power or ground traces or copper pours.
The traces and any components associated with SNS and SNSK will become touch sensitive and should be treated
with caution to limit the touch area to the desired location.
A series resistor, Rs, should be placed in line with SNSK to the electrode to suppress ESD and EMC effects.
2.4 Sensitivity
2.4.1 Introduction
The sensitivity on the QT1010 is a function of things like the value of Cs, electrode size and capacitance, electrode
shape and orientation, the composition and aspect of the object to be sensed, the thickness and composition of any
overlaying panel material, and the degree of ground coupling of both sensor and object.
2.4.2 Increasing Sensitivity
In some cases it may be desirable to increase sensitivity; for example, when using the sensor with very thick panels
having a low dielectric constant, or when the device is used as a proximity sensor. Sensitivity can often be increased
by using a larger electrode or reducing panel thickness. Increasing electrode size can have diminishing returns, as
high values of Cx will reduce sensor gain. AT42QT1010 [DATASHEET] 6
9541I–AT42–05/2013
The value of Cs also has a dramatic effect on sensitivity, and this can be increased in value with the trade-off of
slower response time and more power. Increasing the electrode's surface area will not substantially increase touch
sensitivity if its diameter is already much larger in surface area than the object being detected. Panel material can
also be changed to one having a higher dielectric constant, which will better help to propagate the field.
In the case of proximity detection, usually the object being detected is on an approaching hand, so a larger surface
area can be effective.
Ground planes around and under the electrode and its SNSK trace will cause high Cx loading and destroy gain. The
possible signal-to-noise ratio benefits of ground area are more than negated by the decreased gain from the circuit,
and so ground areas around electrodes are discouraged. Metal areas near the electrode will reduce the field strength
and increase Cx loading and should be avoided, if possible. Keep ground away from the electrodes and traces.
2.4.3 Decreasing Sensitivity
In some cases the QT1010 may be too sensitive. In this case gain can be easily lowered further by decreasing Cs.
2.4.4 Proximity Sensing
By increasing the sensitivity, the QT1010 can be used as a very effective proximity sensor, allowing the presence of
a nearby object (typically a hand) to be detected.
In this scenario, as the object being sensed is typically a hand, very large electrode sizes can be used, which is
extremely effective in increasing the sensitivity of the detector. In this case, the value of Cs will also need to be
increased to ensure improved sensitivity, as mentioned in Section 2.4.2. Note that, although this affects the
responsiveness of the sensor, it is less of an issue in proximity sensing applications; in such applications it is
necessary to detect simply the presence of a large object, rather than a small, precise touch.AT42QT1010 [DATASHEET] 7 9541I–AT42–05/2013
3. Operation Specifics
3.1 Run Modes
3.1.1 Introduction
The QT1010 has three running modes which depend on the state of the SYNC pin (high or low).
3.1.2 Fast Mode
The QT1010 runs in Fast mode if the SYNC pin is permanently high. In this mode the QT1010 runs at maximum
speed at the expense of increased current consumption. Fast mode is useful when speed of response is the prime
design requirement. The delay between bursts in Fast mode is approximately 1 ms, as shown in Figure 3-1.
Figure 3-1. Fast Mode Bursts (SYNC Held High)
3.1.3 Low Power Mode
The QT1010 runs in Low Power (LP) mode if the SYNC pin is held low. In this mode it sleeps for approximately
80 ms at the end of each burst, saving power but slowing response. On detecting a possible key touch, it temporarily
switches to Fast mode until either the key touch is confirmed or found to be spurious (via the detect integration
process). It then returns to LP mode after the key touch is resolved, as shown in Figure 3-2.
Figure 3-2. Low Power Mode (SYNC Held Low)
SNSK
SYNC
~1 ms
sleep sleep
SYNC
SNSK sleep
fast detect
integrator
OUT
Key
~80 ms
touchAT42QT1010 [DATASHEET] 8
9541I–AT42–05/2013
3.1.4 SYNC Mode
It is possible to synchronize the device to an external clock source by placing an appropriate waveform on the SYNC
pin. SYNC mode can synchronize multiple QT1010 devices to each other to prevent cross-interference, or it can be
used to enhance noise immunity from low frequency sources such as 50Hz or 60Hz mains signals.
The SYNC pin is sampled at the end of each burst. If the device is in Fast mode and the SYNC pin is sampled high,
then the device continues to operate in Fast mode (Figure 3-1 on page 7). If SYNC is sampled low, then the device
goes to sleep. From then on, it will operate in SYNC mode (Figure 3-2). Therefore, to guarantee entry into SYNC
mode the low period of the SYNC signal should be longer than the burst length (Figure 3-3).
Figure 3-3. SYNC Mode (Triggered by SYNC Edges)
However, once SYNC mode has been entered, if the SYNC signal consists of a series of short pulses (>10 µs) then
a burst will only occur on the falling edge of each pulse (Figure 3-4) instead of on each change of SYNC signal, as
normal (Figure 3-3).
In SYNC mode, the device will sleep after each measurement burst (just as in LP mode) but will be awakened by a
change in the SYNC signal in either direction, resulting in a new measurement burst. If SYNC remains unchanged
for a period longer than the LP mode sleep period (about 80 ms), the device will resume operation in either Fast or
LP mode depending on the level of the SYNC pin (Figure 3-3).
There is no detect integrator (DI) in SYNC mode (each touch is a detection) but the Max On-duration will depend on
the time between SYNC pulses; see Section 3.3 and Section 3.4 on page 9. Recalibration timeout is a fixed number
of measurements so will vary with the SYNC period.
Figure 3-4. SYNC Mode (Short Pulses)
SYNC
SYNC
SNSK
SNSK
slow mode sleep period
sleep
sleep
sleep sleep
sleep sleep
Revert to Fast Mode
Revert to Slow Mode
slow mode sleep period
SNSK
SYNC
>10 sμ >10 sμ >10 sμAT42QT1010 [DATASHEET] 9 9541I–AT42–05/2013
3.2 Threshold
The internal signal threshold level is fixed at 10 counts of change with respect to the internal reference level, which in
turn adjusts itself slowly in accordance with the drift compensation mechanism.
The QT1010 employs a hysteresis dropout of two counts of the delta between the reference and threshold levels.
3.3 Max On-duration
If an object or material obstructs the sense pad the signal may rise enough to create a detection, preventing further
operation. To prevent this, the sensor includes a timer which monitors detections. If a detection exceeds the timer
setting the sensor performs a full recalibration. This is known as the Max On-duration feature and is set to ~60s (at
3V in LP mode). This will vary slightly with Cs and if SYNC mode is used. As the internal timebase for Max Onduration
is determined by the burst rate, the use of SYNC can cause dramatic changes in this parameter depending
on the SYNC pulse spacing. For example, at 60Hz SYNC mode the Max On-duration will be ~6s at 3V.
3.4 Detect Integrator
It is desirable to suppress detections generated by electrical noise or from quick brushes with an object. To
accomplish this, the QT1010 incorporates a detect integration (DI) counter that increments with each detection until
a limit is reached, after which the output is activated. If no detection is sensed prior to the final count, the counter is
reset immediately to zero. In the QT1010, the required count is four. In LP mode the device will switch to Fast mode
temporarily in order to resolve the detection more quickly; after a touch is either confirmed or denied the device will
revert back to normal LP mode operation automatically.
The DI can also be viewed as a “consensus filter” that requires four successive detections to create an output.
3.5 Forced Sensor Recalibration
The QT1010 has no recalibration pin; a forced recalibration is accomplished when the device is powered up or after
the recalibration timeout. However, supply drain is low so it is a simple matter to treat the entire IC as a controllable
load; driving the QT1010's Vdd pin directly from another logic gate or a microcontroller port will serve as both power
and “forced recalibration”. The source resistance of most CMOS gates and microcontrollers is low enough to provide
direct power without problem.
3.6 Drift Compensation
Signal drift can occur because of changes in Cx and Cs over time. It is crucial that drift be compensated for,
otherwise false detections, non-detections, and sensitivity shifts will follow.
Drift compensation (Figure 3-5) is performed by making the reference level track the raw signal at a slow rate, but
only while there is no detection in effect. The rate of adjustment must be performed slowly, otherwise legitimate
detections could be ignored. The QT1010 drift compensates using a slew-rate limited change to the reference level;
the threshold and hysteresis values are slaved to this reference.
Once an object is sensed, the drift compensation mechanism ceases since the signal is legitimately high, and
therefore should not cause the reference level to change.AT42QT1010 [DATASHEET] 10
9541I–AT42–05/2013
Figure 3-5. Drift Compensation
The QT1010 drift compensation is asymmetric; the reference level drift-compensates in one direction faster than it
does in the other. Specifically, it compensates faster for decreasing signals than for increasing signals. Increasing
signals should not be compensated for quickly, since an approaching finger could be compensated for partially or
entirely before even approaching the sense electrode. However, an obstruction over the sense pad, for which the
sensor has already made full allowance, could suddenly be removed leaving the sensor with an artificially elevated
reference level and thus become insensitive to touch. In this latter case, the sensor will compensate for the object's
removal very quickly, usually in only a few seconds.
With large values of Cs and small values of Cx, drift compensation will appear to operate more slowly than with the
converse. Note that the positive and negative drift compensation rates are different.
3.7 Response Time
The QT1010's response time is highly dependent on run mode and burst length, which in turn is dependent on Cs
and Cx. With increasing Cs, response time slows, while increasing levels of Cx reduce response time. The response
time will also be a lot slower in LP or SYNC mode due to a longer time between burst measurements.
3.8 Spread Spectrum
The QT1010 modulates its internal oscillator by ±7.5% during the measurement burst. This spreads the generated
noise over a wider band, reducing emission levels. This also reduces susceptibility since there is no longer a single
fundamental burst frequency.
3.9 Output Features
3.9.1 Output
The output of the QT1010 is active-high upon detection. The output will remain active-high for the duration of the
detection, or until the Max On-duration expires, whichever occurs first. If a Max On-duration timeout occurs first, the
sensor performs a full recalibration and the output becomes inactive (low) until the next detection.
3.9.2 HeartBeat Output
The QT1010 output has a HeartBeat “health” indicator superimposed on it in all modes. This operates by taking the
output pin into a three-state mode for 15 µs, once before every QT burst. This output state can be used to determine
that the sensor is operating properly, using one of several simple methods, or it can be ignored.
The HeartBeat indicator can be sampled by using a pull-up resistor on the OUT pin (Figure 3-6), and feeding the
resulting positive-going pulse into a counter, flip flop, one-shot, or other circuit. The pulses will only be visible when
the chip is not detecting a touch.
Threshold
Signal
Hysteresis
Reference
OutputAT42QT1010 [DATASHEET] 11 9541I–AT42–05/2013
Figure 3-6. Obtaining HeartBeat Pulses with a Pull-up Resistor (SOT23-6)
If the sensor is wired to a microcontroller as shown in Figure 3-7 on page 11, the microcontroller can reconfigure the
load resistor to either Vss or Vdd depending on the output state of the QT1010, so that the pulses are evident in
either state.
Figure 3-7. Using a Microcontroller to Obtain HeartBeat Pulses in Either Output State (SOT23-6)
Electromechanical devices like relays will usually ignore the short HeartBeat pulse. The pulse also has too low a duty
cycle to visibly affect LEDs. It can be filtered completely if desired, by adding an RC filter to the output, or if
interfacing directly and only to a high-impedance CMOS input, by doing nothing or at most adding a small noncritical
capacitor from OUT to Vss.
3.9.3 Output Drive
The OUT pin is active high and can sink or source up to 2 mA. When a large value of Cs (>20 nF) is used the OUT
current should be limited to <1 mA to prevent gain-shifting side effects, which happen when the load current creates
voltage drops on the die and bonding wires; these small shifts can materially influence the signal level to cause
detection instability.
OUT
VDD
SNSK
SNS
SYNC/MODE
VSS
2
6
4
1 3
5
VDD
HeartBeat" Pulse Ro
OUT SNSK
SNS
SYNC/MODE 6
4
1 3 Ro
Microcontroller
Port_M.x
Port_M.yAT42QT1010 [DATASHEET] 12
9541I–AT42–05/2013
4. Circuit Guidelines
4.1 More Information
Refer to Application Note QTAN0002, Secrets of a Successful QTouch Design and the Touch Sensors Design Guide
(both downloadable from the Atmel website), for more information on construction and design methods.
4.2 Sample Capacitor
Cs is the charge sensing sample capacitor. The required Cs value depends on the thickness of the panel and its
dielectric constant. Thicker panels require larger values of Cs. Typical values are 2 nF to 50 nF depending on the
sensitivity required; larger values of Cs demand higher stability and better dielectric to ensure reliable sensing.
The Cs capacitor should be a stable type, such as X7R ceramic or PPS film. For more consistent sensing from unit
to unit, 5% tolerance capacitors are recommended. X7R ceramic types can be obtained in 5% tolerance at little or no
extra cost. In applications where high sensitivity (long burst length) is required the use of PPS capacitors is
recommended.
For battery powered operation a higher value sample capacitor is recommended (typical value 8.2 nF).
4.3 UDFN/USON Package Restrictions
The central pad on the underside of the UDFN/USON chip is connected to ground. Do not run any tracks underneath
the body of the chip, only ground.
4.4 Power Supply and PCB Layout
See Section 5.2 on page 14 for the power supply range. At 3 V current drain averages less than 500 µA in Fast
mode.
If the power supply is shared with another electronic system, care should be taken to ensure that the supply is free of
digital spikes, sags, and surges which can adversely affect the QT1010. The QT1010 will track slow changes in Vdd,
but it can be badly affected by rapid voltage fluctuations. It is highly recommended that a separate voltage regulator
be used just for the QT1010 to isolate it from power supply shifts caused by other components.
If desired, the supply can be regulated using a Low Dropout (LDO) regulator, although such regulators often have
poor transient line and load stability. See Application Note QTAN0002, Secrets of a Successful QTouch™ Design for
further information.
Parts placement: The chip should be placed to minimize the SNSK trace length to reduce low frequency pickup,
and to reduce stray Cx which degrades gain. The Cs and Rs resistors (see Figure 1-1 on page 4) should be placed
as close to the body of the chip as possible so that the trace between Rs and the SNSK pin is very short, thereby
reducing the antenna-like ability of this trace to pick up high frequency signals and feed them directly into the chip. A
ground plane can be used under the chip and the associated discrete components, but the trace from the Rs resistor
and the electrode should not run near ground, to reduce loading.
For best EMC performance the circuit should be made entirely with SMT components.
Electrode trace routing: Keep the electrode trace (and the electrode itself) away from other signal, power, and
ground traces including over or next to ground planes. Adjacent switching signals can induce noise onto the sensing
signal; any adjacent trace or ground plane next to, or under, the electrode trace will cause an increase in Cx load and
desensitize the device.
Note: For proper operation a 100 nF (0.1 µF) ceramic bypass capacitor must be used directly between Vdd and
Vss, to prevent latch-up if there are substantial Vdd transients; for example, during an ESD event. The
bypass capacitor should be placed very close to the Vss and Vdd pins.AT42QT1010 [DATASHEET] 13 9541I–AT42–05/2013
4.5 Power On
On initial power up, the QT1010 requires approximately 100 ms to power on to allow power supplies to stabilize.
During this time the OUT pin state is not valid and should be ignored.AT42QT1010 [DATASHEET] 14
9541I–AT42–05/2013
5. Specifications
5.1 Absolute Maximum Specifications
5.2 Recommended Operating Conditions
5.3 AC Specifications
Operating temperature –40°C to +85°C
Storage temperature –55°C to +125°C
VDD 0 to +6.5 V
Max continuous pin current, any control or drive pin ±20 mA
Short circuit duration to Vss, any pin Infinite
Short circuit duration to Vdd, any pin Infinite
Voltage forced onto any pin –0.6V to (Vdd + 0.6) V
CAUTION: Stresses beyond those listed under Absolute Maximum Specifications may cause permanent damage to
the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those
indicated in the operational sections of this specification is not implied. Exposure to absolute maximum specification
conditions for extended periods may affect device reliability
VDD +1.8 to 5.5 V
Short-term supply ripple + noise ±20 mV
Long-term supply stability ±100 mV
Cs value 2 to 50 nF
Cx value 5 to 50 pF
Vdd = 3.0 V, Cs = 4.7 nF, Cx = 5 pF, Ta = recommended range, unless otherwise noted
Parameter Description Min Typ Max Units Notes
TRC Recalibration time – 200 – ms Cs, Cx dependent
TPC Charge duration – 3.05 – µs ±7.5% spread spectrum variation
TPT Transfer duration – 9.0 – µs ±7.5% spread spectrum variation
TG1 Time between end of burst and
start of the next (Fast mode) – 1.2 – ms
TG2 Time between end of burst and
start of the next (LP mode) – 80 – ms Increases with decreasing VDD
See Figure 5-1 on page 15AT42QT1010 [DATASHEET] 15 9541I–AT42–05/2013
Figure 5-1. TG2 – Time Between Bursts (LP Mode)
Figure 5-2. TBL – Burst Length
TBL Burst length – 2.45 – ms
VDD, Cs and Cx dependent. See
Section 4.2 for capacitor
selection.
TR Response time – – 100 ms
THB HeartBeat pulse width – 15 – µs
Vdd = 3.0 V, Cs = 4.7 nF, Cx = 5 pF, Ta = recommended range, unless otherwise noted
Parameter Description Min Typ Max Units NotesAT42QT1010 [DATASHEET] 16
9541I–AT42–05/2013
5.4 Signal Processing
5.5 DC Specifications
Vdd = 3.0V, Cs = 4.7 nF, Cx = 5 pF, Ta = recommended range, unless otherwise noted
Description Min Typ Max Units Notes
Threshold differential 10 counts
Hysteresis 2 counts
Consensus filter length 4 samples
Max on-duration 60 seconds (At 3 V in LP mode) Will vary
in SYNC mode and with Vdd
Vdd = 3.0V, Cs = 4.7 nF, Cx = 5 pF, Ta = recommended range, unless otherwise noted
Parameter Description Min Typ Max Units Notes
VDD Supply voltage 1.8 5.5 V
IDD Supply current, Fast mode –
203.0
246.0
378.5
542.5
729.0
– µA
1.8 V
2.0 V
3.0 V
4.0 V
5.0 V
IDDI Supply current, LP mode –
16.5
19.5
34.0
51.5
73.5
– µA
1.8 V
2.0 V
3.0 V
4.0 V
5.0 V
VDDS Supply turn-on slope 10 – – V/s Required for proper start-up
VIL Low input logic level – – 0.2 × Vdd
0.3 × Vdd V Vdd = 1.8 V – 2.4 V
Vdd = 2.4 V – 5.5 V
VHL High input logic level 0.7 × Vdd
0.6 × Vdd – – V Vdd = 1.8 V – 2.4 V
Vdd = 2.4 V – 5.5 V
VOL Low output voltage – – 0.5 V OUT, 4 mA sink
VOH High output voltage 2.3 – – V OUT, 1 mA source
IIL Input leakage current – <0.05 1 µA
CX Load capacitance range 2 – 50 pF
AR Acquisition resolution – 9 14 bitsAT42QT1010 [DATASHEET] 17 9541I–AT42–05/2013
5.6 Mechanical Dimensions
5.6.1 6-pin SOT23-6
9524D–AT42–05/2013
Features
Number of QTouch® Keys:
Up to four
Discrete Outputs:
Four discrete outputs indicating individual key touch
Technology:
Patented spread-spectrum charge-transfer (direct mode)
Electrode Design:
Simple self-capacitance style (refer to the Touch Sensors Design Guide)
Electrode Materials:
Etched copper, silver, carbon, Indium Tin Oxide (ITO)
Electrode Substrates:
PCB, FPCB, plastic films, glass
Panel Materials:
Plastic, glass, composites, painted surfaces (low particle density metallic
paints possible)
Panel Thickness:
Up to 10 mm glass, 5 mm plastic (electrode size dependent)
Key Sensitivity:
Fixed key threshold, sensitivity adjusted via sample capacitor value
Adjacent Key Suppression
Patented Adjacent Key Suppression® (AKS®) technology to enable accurate
key detection
Interface:
Pin-per-key outputs, plus debug mode to observe sensor signals
Moisture Tolerance:
Increased moisture tolerance based on hardware design and firmware tuning
Signal Processing:
Self-calibration, auto drift compensation, noise filtering
Applications:
Mobile, consumer, white goods, toys, kiosks, POS, and so on
Power:
1.8 V – 5.5 V
Package:
20-pin 3 x 3 mm VQFN RoHS compliant
Atmel AT42QT1040
Four-key QTouch® Touch Sensor IC
DATASHEETAT42QT1040 [DATASHEET] 2
9524D–AT42–05/2013
1. Pinout and Schematic
1.1 Pinout Configuration
NC
NC
VSS
VDD
NC
SNS2
SNSK1
SNS1
SNSK0
SNS0 OUT0
OUT1
1
2
3
4
5 11
12
13
14
15
20 19 18 17 16
6 7 8 9 10
QT1040 OUT3
OUT2
SNSK3
SNSK2
NC
NC
NC
SNS3AT42QT1040 [DATASHEET] 3 9524D–AT42–05/2013
1.2 Pin Descriptions
I/O CMOS input and output OD CMOS open drain output P Ground or power
Table 1-1. Pin Listing
Pin Name Type Function Notes If Unused...
1 SNS2 I/O Sense pin To Cs2 Leave open
2 SNSK1 I/O Sense pin and option detect To Cs1 and option resistor +
key
Connect to option
resistor*
3 SNS1 I/O Sense pin To Cs1 Leave open
4 SNSK0 I/O Sense pin and option detect To Cs0 and option resistor +
key
Connect to option
resistor*
5 SNS0 I/O Sense pin To Cs0 Leave open
6 N/C – – –
7 N/C – – –
8 Vss P Supply ground –
9 Vdd P Power –
10 N/C – – –
11 OUT0 OD Out 0 Alternative function: Debug
CLK Leave open
12 OUT1 OD Out 1 Alternative function: Debug
DATA Leave open
13 OUT3 OD Out 3 Leave open
14 OUT2 OD Out 2 Leave open
15 SNSK3 I/O Sense pin To Cs3 + key Leave open
16 SNS3 I/O Sense pin To Cs3 Leave open
17 N/C – – –
18 N/C – – –
19 N/C – – –
20 SNSK2 I/O Sense pin To Cs2 + key Leave open
* Option resistor should always be fitted even if channel is unused and Cs capacitor is not fixed.AT42QT1040 [DATASHEET] 4
9524D–AT42–05/2013
1.3 Schematic
Figure 1-1. Typical Circuit
Suggested regulator manufacturers:
Torex (XC6215 series)
Seiko (S817 series)
BCDSemi (AP2121 series)
For component values in Figure 1-1 check the following sections:
Section 3.1 on page 7: Cs capacitors (Cs0 – Cs3)
Section 3.5 on page 7: Voltage levels
Section 3.3 on page 7: LED traces
SLOW
FAST
OFF
LED3
LED2
LED1
LED0
VDD
VDD
2
1
3
J2
VDD
2
1
3
J1
ON
2 2
5 5
4 4
3 3
1 1
J3
VDD 9 VSS 8
N/C 19
N/C 10
OUT2 14
SNSK3 15
SNSK2 20
SNSK1 2
SNSK0 4
N/C 18
N/C 7
N/C 17
OUT1 12
OUT0 11
SNS3 16
SNS1 3
N/C 6
OUT3 13 SNS0 5
SNS2 1
SPEED SELECT
AKS SELECT
NOTES:
1) The central pad on the underside of the VQFN chip is a Vss pin and should be connected
to ground. Do not put any other tracks underneath the body of the chip.
2) It is important to place all Cs and Rs components physically near to the chip.
Add a 100 nF capacitor close to pin 9.
QT1040
Creg Creg
VREG
Follow regulator manufacturer's
recommended values for input
and output bypass capacitors (Creg).
Key0
Key1
Key2
Key3
VUNREG
GND
Cs0
Cs1
Cs2
Cs3
RL0
RL1
RL2
RL3
RAKS
RFS
Rs0
Rs1
Rs2
Rs3
Example use of output pinsAT42QT1040 [DATASHEET] 5 9524D–AT42–05/2013
2. Overview of the AT42QT1040
2.1 Introduction
The AT42QT1040 (QT1040) is a digital burst mode charge-transfer (QT™) capacitive sensor driver designed for
touch-key applications. The device can sense from one to four keys; one to three keys can be disabled by not
installing their respective sense capacitors. Any of the four channels can be disabled in this way.
The device includes all signal processing functions necessary to provide stable sensing under a wide variety of
changing conditions, and the outputs are fully de-bounced. Only a few external parts are required for operation.
The QT1040 modulates its bursts in a spread-spectrum fashion in order to heavily suppress the effects of external
noise, and to suppress RF emissions.
2.2 Signal Processing
2.2.1 Detect Threshold
The internal signal threshold level is fixed at 10 counts of change with respect to the internal reference level. This in
turn adjusts itself slowly in accordance with the drift compensation mechanism. See Section 3.1 on page 7 for details
on how to adjust the sensitivity of each key.
When going out of detect there is a hysteresis element to the detection. The signal threshold must drop below 8
counts of change with respect to the internal reference level to register as un-touched.
2.2.2 Detection Integrator
The device features a detection integration mechanism, which acts to confirm a detection in a robust fashion. A perkey
counter is incremented each time the key has exceeded its threshold, and a key is only finally declared to be
touched when this counter reaches a fixed limit of 5. In other words, the device has to exceed its threshold, and stay
there for 5 acquisitions in succession without going below the threshold level, before the key is declared to be
touched.
2.2.3 Burst Length Limitations
Burst length is the number of times the charge transfer process is performed on a given channel; that is, the number
of pulses it takes to measure the key capacitance.
The maximum burst length is 2048 pulses. The recommended design is to use a capacitor that gives a signal of
<1000 pulses. Longer bursts take more time and use more power.
Note that the keys are independent of each other. It is therefore possible, for example, to have a signal of 100 on one
key and a signal of 1000 on another.
Refer to Application Note QTAN0002, Secrets of a Successful QTouch Design (downloadable from the Atmel
website), for more information on using a scope to measure the pulses and hence determine the burst length. Refer
also to the Touch Sensors Design Guide.
2.2.4 Adjacent Key Suppression Technology
The device includes the Atmel-patented Adjacent Key Suppression (AKS) technology, to allow the use of tightly
spaced keys on a keypad with no loss of selectability by the user.
There is one global AKS group, implemented so that only one key in the group may be reported as being touched at
any one time.
The use of AKS is selected by connecting a 1 M resistor between Vdd and the SNSK0 pin (see Section 4.1 on
page 9 for more information). When AKS is disabled, any combinations of keys can enter detect.AT42QT1040 [DATASHEET] 6
9524D–AT42–05/2013
2.2.5 Auto Drift Compensation
Signal drift can occur because of changes in Cx and Cs over time. It is crucial that drift be compensated for,
otherwise false detections, non-detections, and sensitivity shifts will follow.
Drift compensation is performed by making the reference level track the raw signal at a slow rate, but only while
there is no detection in effect. The rate of adjustment must be performed slowly otherwise legitimate detections could
be ignored.
Once an object is sensed and a key is in detect, the drift compensation mechanism ceases, since the signal is
legitimately high and should not therefore cause the reference level to change.
The QT1040 drift compensation is asymmetric, that is, the reference level drift-compensates in one direction faster
than it does in the other. Specifically, it compensates faster for decreasing (towards touch) signals than for
increasing (away from touch) signals. The reason for this difference in compensation rates is that increasing signals
should not be compensated for quickly, since a nearby finger could be compensated for partially or entirely before
even approaching the sense electrode. However, decreasing signals need to be compensated for more quickly. For
example, an obstruction over the sense pad (for which the sensor has already made full allowance) could suddenly
be removed, leaving the sensor with an artificially elevated reference level and thus become insensitive to touch. In
this latter case, the sensor will compensate for the object's removal very quickly, usually in only a few seconds.
Negative drift (that is, towards touch) occurs at a rate of ~3 seconds, while positive drift occurs at a rate of
~1 second.
Drifting only occurs when no keys are in detect state.
2.2.6 Response Time
The QT1040 response time is highly dependent on run mode and burst length, which in turn is dependent on Cs and
Cx. With increasing Cs, response time slows, while increasing levels of Cx reduce response time. The response time
will also be slower in slow mode due to a longer time between burst measurements. This mode offers an increased
detection latency in favor of reduced average current consumption.
2.2.7 Spread Spectrum
The QT1040 modulates its internal oscillator by ±7.5% during the measurement burst. This spreads the generated
noise over a wider band reducing emission levels. This also reduces susceptibility since there is no longer a single
fundamental burst frequency.
2.2.8 Max On-duration
If an object or material obstructs the sense pad, the signal may rise enough to create a detection, preventing further
operation. To prevent this, the sensor includes a timer known as the Max On-duration feature which monitors
detections. If a detection exceeds the timer setting, the sensor performs an automatic recalibration. Max On-duration
is set to ~30s.AT42QT1040 [DATASHEET] 7 9524D–AT42–05/2013
3. Wiring and Parts
3.1 Cs Sample Capacitors
Cs0 – Cs3 are the charge sensing sample capacitors; normally they are identical in nominal value. The optimal Cs
values depend on the corresponding keys electrode design, the thickness of the panel and its dielectric constant.
Thicker panels require larger values of Cs. Values can be in the range 2.2 nF (for faster operation) to 22 nF (for best
sensitivity); typical values are 4.7 nF to 10 nF.
The value of Cs should be chosen such that a light touch on a key mounted in a production unit or a prototype panel
causes a reliable detection. The chosen Cs value should never be so large that the key signals exceed ~1000, as
reported by the chip in the debug data.
The Cs capacitors must be X7R or PPS film type, for stability. For consistent sensitivity, they should have a 10%
tolerance. Twenty percent tolerance may cause small differences in sensitivity from key to key and unit to unit. If a
key is not used, the Cs capacitor may be omitted.
3.2 Rs Resistors
The series resistors Rs0 – Rs3 are in line with the electrode connections (close to the QT1040 chip) and are used to
limit electrostatic discharge (ESD) currents and to suppress radio frequency (RF) interference. A typical value is
4.7 k, but up to 20 k can be used if it is found to be of benefit.
Although these resistors may be omitted, the device may become susceptible to external noise or radio frequency
interference (RFI). For details on how to select these resistors refer to Application Note QTAN0002, Secrets of a
Successful QTouch Design, and the Touch Sensors Design Guide, both downloadable from the Touch Technology
area of the Atmel website, www.atmel.com.
3.3 LED Traces and Other Switching Signals
For advice on LEDs and nearby traces, refer to Application Note QTAN0002, Secrets of a Successful QTouch
Design, and the Touch Sensors Design Guide, both downloadable from the Touch Technology area of Atmel’s
website, www.atmel.com.
3.4 PCB Cleanliness
Modern no-clean flux is generally compatible with capacitive sensing circuits.
3.5 Power Supply
See Section 5.2 on page 15 for the power supply range. If the power supply fluctuates slowly with temperature, the
device tracks and compensates for these changes automatically with only minor changes in sensitivity. If the supply
voltage drifts or shifts quickly, the drift compensation mechanism is not able to keep up, causing sensitivity
anomalies or false detections.
The usual power supply considerations with QT parts apply to the device. The power should be clean and come from
a separate regulator if possible. However, this device is designed to minimize the effects of unstable power, and
except in extreme conditions should not require a separate Low Dropout (LDO) regulator.
CAUTION: If a PCB is reworked to correct soldering faults relating to the device, or
to any associated traces or components, be sure that you fully understand the
nature of the flux used during the rework process. Leakage currents from
hygroscopic ionic residues can stop capacitive sensors from functioning. If you
have any doubts, a thorough cleaning after rework may be the only safe option.AT42QT1040 [DATASHEET] 8
9524D–AT42–05/2013
See under Figure 1.3 on page 4 for suggested regulator manufacturers.
It is assumed that a larger bypass capacitor (for example, 1 µF) is somewhere else in the power circuit; for example,
near the regulator.
To assist with transient regulator stability problems, the QT1040 waits 500 µs any time it wakes up from a sleep state
(that is, in Sleep mode) before acquiring, to allow Vdd to fully stabilize.
3.6 VQFN Package Restrictions
The central pad on the underside of the VQFN chip should be connected to ground. Do not run any tracks
underneath the body of the chip, only ground. Figure 3-1 shows an example of good/bad tracking.
Figure 3-1. Examples of Good and Bad Tracking
Caution: A regulator IC shared with other logic can result in erratic operation and is
not advised.
A single ceramic 0.1 µF bypass capacitor, with short traces, should be placed very
close to the power pins of the IC. Failure to do so can result in device oscillation, high
current consumption, erratic operation, and so on.
Example of GOOD tracking Example of BAD trackingAT42QT1040 [DATASHEET] 9 9524D–AT42–05/2013
4. Detailed Operations
4.1 Adjacent Key Suppression
The use of AKS is selected by the connection of a 1 M resistor (RAKS resistor) between the SNSK0 pin and either
Vdd (AKS mode on) or Vss (AKS mode off).
Note: Changing the RAKS option will affect the sensitivity of the particular key. Always check that the sensitivity is
suitable after a change. Retune Cs0 if necessary.
4.2 Discrete Outputs
There are four discrete outputs (channels 0 to 3), located on pins OUT0 to OUT3. An output pin goes active when
the corresponding key is touched. The outputs are open-drain type and are active-low.
On the OUT2 pin there is a ~500 ns low pulse occurring approximately 20 ms after a power-up/reset (see Figure 4-1
for an example oscilloscope trace of this pulse at two zoom levels). This pulse may need to be considered from the
system design perspective.
The discrete outputs have sufficient current sinking capability to directly drive LEDs. Try to limit the sink current to
less than 5 mA per output and be cautious if connecting LEDs to a power supply other than Vdd; if the LED supply is
higher than Vdd it may cause erratic behavior of the QT1040 and back-power the QT1040 through its I/O pins.
Table 4-1. RAKS Resistor
RAKS Connected To... Mode
Vdd AKS on
Vss AKS off
The RAKS resistor should always be connected to either Vdd or Vss and should not be
changed during operation of the device.AT42QT1040 [DATASHEET] 10
9524D–AT42–05/2013
Figure 4-1. ~500 ns Pulse On OUT2 Pin
4.3 Speed Selection
Speed selection is determined by a 1 M resistor (RFS resistor) connected between SNSK1 and either Vdd (Fast
Mode) or Vss (Slow Mode).
In Fast Mode, the device sleeps for 16 ms between burst acquisitions. In Slow Mode, the device sleeps for 64 ms
between acquisitions. Hence, Slow Mode conserves more power but results in slightly less responsiveness.
Note: The RFS resistor should always be connected to either Vdd or Vss and not changed during operation of the
device. Changing the RFS option will affect the sensitivity of the particular key. Always check that the
sensitivity is suitable after a change. Retune Cs1 if necessary.
4.4 Moisture Tolerance
The presence of water (condensation, sweat, spilt water, and so on) on a sensor can alter the signal values
measured and thereby affect the performance of any capacitive device. The moisture tolerance of QTouch devices
can be improved by designing the hardware and fine-tuning the firmware following the recommendations in the
application note Atmel AVR3002: Moisture Tolerant QTouch Design (www.atmel.com/Images/doc42017.pdf).
Pulse on OUT2
SNS0K
OUT2
SNS0K
OUT2
Power-on/ ~20 ms
Reset
Table 4-2. RFS Resistor
RFS Connected To Mode
Vdd Fast mode
Vss Slow modeAT42QT1040 [DATASHEET] 11 9524D–AT42–05/2013
4.5 Calibration
Calibration is the process by which the sensor chip assesses the background capacitance on each channel. During
calibration, a number of samples are taken in quick succession to get a baseline for the channel reference value.
Calibration takes place ~50 ms after power is applied to the device. Calibration also occurs if the Max On-duration is
exceeded or a positive re-calibration occurs.
4.6 Debug Mode
An added feature to this device is a debug option whereby internal parameters from the IC can be clocked out and
monitored externally.
Debug mode is entered by shorting the CS3 capacitor (SNSK3 and SNS3 pins) on power-up and removing the short
within 5 seconds.
Note: If the short is not removed within 5 seconds, debug mode is still entered, but with Channel 3 unusable until
a re-calibration occurs. Note that as Channel 3 will show as being in detect, a recalibration will occur after
Max On-duration (~30 seconds).
Debug CLK pin (OUT0) and Debug Data pin (OUT1) float while debug data is not being output and are driven
outputs once debug output starts (that is, not open drain).
The serial data is clocked out at a rate of ~200 kHz, MSB first, as in Table 4-3.
Table 4-3. Serial Data Output
Byte Purpose Notes
0 Frame Number Framing index number 0-255
1 Chip Version Upper nibble: major revision
Lower nibble: minor revision
2 Reference 0 Low Byte
Unsigned 16-bit integer
3 Reference 0 High Byte
4 Reference 1 Low Byte
Unsigned 16-bit integer
5 Reference 1 High Byte
6 Reference 2 Low Byte
Unsigned 16-bit integer
7 Reference 2 High Byte
8 Reference 3 Low Byte
Unsigned 16-bit integer
9 Reference 3 High Byte
10 Signal 0 Low Byte
Unsigned 16-bit integer
11 Signal 0 High Byte
12 Signal 1 Low Byte
Unsigned 16-bit integer
13 Signal 1 High Byte
14 Signal 2 Low Byte
Unsigned 16-bit integer
15 Signal 2 High Byte
16 Signal 3 Low Byte
Unsigned 16-bit integer
17 Signal 3 High ByteAT42QT1040 [DATASHEET] 12
9524D–AT42–05/2013
Bit 7: This bit is set during calibration
Bits 4 – 6: Contains the number of keys active
Bits 0 – 3: Show the touch status of the corresponding keys
Figure 4-2 to Figure 4-5 show the usefulness of the debug data out feature. Channels can be monitored and tweaked
to the specific application with great accuracy.
18 Delta 0 Low Byte
Signed 16-bit integer
19 Delta 0 High Byte
20 Delta 1 Low Byte
Signed 16-bit integer
21 Delta 1 High Byte
22 Delta 2 Low Byte
Signed 16-bit integer
23 Delta 2 High Byte
24 Delta 3 Low Byte
Signed 16-bit integer
25 Delta 3 High Byte
26 Flags Various operational flags
27 Flags2 Unsigned bytes
28 Status Byte Unsigned byte. See Table 4-4
29 Frame Number Repeat of framing index number in
byte 0
Table 4-4. Status Byte (Byte 28)
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
CAL Number of Keys (2 – 4) Key 3 Key 2 Key 1 Key 0
Table 4-3. Serial Data Output (Continued)
Byte Purpose NotesAT42QT1040 [DATASHEET] 13 9524D–AT42–05/2013
Figure 4-2. Byte Clocked Out (~5 µs Period)
Figure 4-3. Byte Following Byte (~ 30 µs Period)
Figure 4-4. Full Debug Send (30 Bytes)AT42QT1040 [DATASHEET] 14
9524D–AT42–05/2013
Figure 4-5. Debug Lines Floating Between Debug Data Sends (30 Bytes, ~2 ms to Send)AT42QT1040 [DATASHEET] 15 9524D–AT42–05/2013
5. Specifications
5.1 Absolute Maximum Specifications
5.2 Recommended Operating Conditions
5.3 DC Specifications
Vdd –0.5 to +6.0 V
Max continuous pin current, any control or drive pin ±10 mA
Voltage forced onto any pin –0.5 V to (Vdd + 0.5) V
Operating temperature –40°C to +85°C
Storage temperature –55°C to +125°C
Vdd 1.8 V to 5.5 V
Supply ripple + noise ±20 mV maximum
Cx capacitance per key 2 to 20 pF
Vdd = 5.0 V, Cs = 4.7 nF, Ta = recommended range, unless otherwise noted
Parameter Description Min Typ Max Units Notes
Vil Low input logic level –0.5 – 0.3 V
Vih High input logic level 0.6 × Vdd Vdd Vdd + 0.5 V
Vol Low output voltage 0 – 0.7 V 10 mA sink current
Voh High output voltage 0.8 × Vdd – Vdd V 10 mA source current
Iil Input leakage current – <0.05 1 µA
Rrst Internal RST pull-up resistor 20 – 50 k
CAUTION: Stresses beyond those listed under Absolute Maximum Specifications may cause permanent damage
the device. This is a stress rating only and functional operation of the device at these or other conditions beyo
those indicated in the operational sections of this specification is not implied. Exposure to absolute maximu
specification conditions for extended periods may affect device reliabilityAT42QT1040 [DATASHEET] 16
9524D–AT42–05/2013
5.4 Timing Specifications
5.5 Power Consumption
Parameter Description Min Typ Max Units Notes
TBS Burst duration – 3.5 – ms Cx = 5 pF, Cs = 18 nF
Fc Burst center frequency – 119 – kHz
Fm Burst modulation, percentage –7.5 – +7.5 %
TPW Burst pulse width – 2 – µs
Vdd (V) AKS Mode (RAKS) Speed (RFS) Power Consumption (µA)
1.8
Off Slow 31
Off Fast 104
On Slow 36
On Fast 114
3.3
Off Slow 100
Off Fast 340
On Slow 117
On Fast 380
5.0
Off Slow 215
Off Fast 710
On Slow 245
On Fast 800AT42QT1040 [DATASHEET] 17 9524D–AT42–05/2013
5.6 Mechanical Dimensions
Features
• High performance, low power AVR® 8-bit Microcontroller
• Advanced RISC architecture
– 135 powerful instructions – most single clock cycle execution
– 32 × 8 general purpose working registers
– Fully static operation
– Up to 16MIPS throughput at 16MHz
– On-chip 2-cycle multiplier
• Non-volatile program and data memories
– 64/128Kbytes of in-system self-programmable flash
• Endurance: 100,000 write/erase cycles
– Optional Boot Code section with independent lock bits
• USB boot loader programmed by default in the factory
• In-system programming by on-chip boot program hardware activated after
reset
• True read-while-write operation
• All supplied parts are pre-programed with a default USB bootloader
– 2K/4K (64K/128K flash version) bytes EEPROM
• Endurance: 100,000 write/erase cycles
– 4K/8K (64K/128K flash version) bytes internal SRAM
– Up to 64Kbytes optional external memory space
– Programming lock for software security
• JTAG (IEEE std. 1149.1 compliant) interface
– Boundary-scan capabilities according to the JTAG standard
– Extensive on-chip debug support
– Programming of flash, EEPROM, fuses, and lock bits through the JTAG interface
• USB 2.0 full-speed/low-speed device and on-the-go module
– Complies fully with:
– Universal serial bus specification REV 2.0
– On-the-go supplement to the USB 2.0 specification rev 1.0
– Supports data transfer rates up to 12Mbit/s and 1.5Mbit/s
• USB full-speed/low speed device module with interrupt on transfer completion
– Endpoint 0 for control transfers: up to 64-bytes
– Six programmable endpoints with in or out directions and with bulk, interrupt or
isochronous transfers
– Configurable endpoints size up to 256bytes in double bank mode
– Fully independent 832bytes USB DPRAM for endpoint memory allocation
– Suspend/resume interrupts
– Power-on reset and USB bus reset
– 48MHz PLL for full-speed bus operation
– USB bus disconnection on microcontroller request
• USB OTG reduced host:
– Supports host negotiation protocol (HNP) and session request protocol (SRP) for
OTG dual-role devices
– Provide status and control signals for software implementation of HNP and SRP
– Provides programmable times required for HNP and SRP
• Peripheral features
– Two 8-bit timer/counters with separate prescaler and compare mode
– Two16-bit timer/counter with separate prescaler, compare- and capture mode
8-bit Atmel
Microcontroller
with
64/128Kbytes
of ISP Flash
and USB
Controller
AT90USB646
AT90USB647
AT90USB1286
AT90USB1287
7593L–AVR–09/122
7593L–AVR–09/12
AT90USB64/128
– Real time counter with separate oscillator
– Four 8-bit PWM channels
– Six PWM channels with programmable resolution from 2 to 16 bits
– Output compare modulator
– 8-channels, 10-bit ADC
– Programmable serial USART
– Master/slave SPI serial interface
– Byte oriented 2-wire serial interface
– Programmable watchdog timer with separate on-chip oscillator
– On-chip analog comparator
– Interrupt and wake-up on pin change
• Special microcontroller features
– Power-on reset and programmable brown-out detection
– Internal calibrated oscillator
– External and internal interrupt sources
– Six sleep modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby
• I/O and packages
– 48 programmable I/O lines
– 64-lead TQFP and 64-lead QFN
• Operating voltages
– 2.7 - 5.5V
• Operating temperature
– Industrial (-40°C to +85°C)
• Maximum frequency
– 8MHz at 2.7V - industrial range
– 16MHz at 4.5V - industrial range3
7593L–AVR–09/12
AT90USB64/128
1. Pin configurations
Figure 1-1. Pinout Atmel AT90USB64/128-TQFP.
AT90USB90128/64
TQFP64
(INT.7/AIN.1/UVcon) PE7
UVcc
D-
D+
UGnd
UCap
VBus
(IUID) PE3
(SS/PCINT0) PB0
(INT.6/AIN.0) PE6
(PCINT1/SCLK) PB1
(PDI/PCINT2/MOSI) PB2
(PDO/PCINT3/MISO) PB3
(PCINT4/OC.2A) PB4
(PCINT5/OC.1A) PB5
(PCINT6/OC.1B) PB6
(PCINT7/OC.0A/OC.1C) PB7
(INT4/TOSC1) PE4
(INT.5/TOSC2) PE5
RESET
VCC
GND
XTAL2
XTAL1
(OC0B/SCL/INT0) PD0
(OC2B/SDA/INT1) PD1
(RXD1/INT2) PD2
(TXD1/INT3) PD3
(ICP1) PD4
(XCK1) PD5
PA3 (AD3)
PA4 (AD4)
PA5 (AD5)
PA6 (AD6)
PA7 (AD7)
PE2 (ALE/HWB)
PC7 (A15/IC.3/CLKO)
PC6 (A14/OC.3A)
PC5 (A13/OC.3B)
PC4 (A12/OC.3C)
PC3 (A11/T.3)
PC2 (A10)
PC1 (A9)
PC0 (A8)
PE1 (RD)
PE0 (WR)
AVCC
GND
AREF
PF0 (ADC0)
PF1 (ADC1)
PF2 (ADC2)
PF3 (ADC3)
PF4 (ADC4/TCK)
PF5 (ADC5/TMS)
PF6 (ADC6/TDO)
PF7 (ADC7/TDI)
GND
VCC
PA0 (AD0)
PA1 (AD1)
PA2 (AD2)
(T1) PD6
(T0) PD7
INDEX CORNER
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
48
47
46
45
44
43
42
41
40
39
38
37
36
35
34
33
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
324
7593L–AVR–09/12
AT90USB64/128
Figure 1-2. Pinout Atmel AT90USB64/128-QFN.
Note: The large center pad underneath the MLF packages is made of metal and internally connected to
GND. It should be soldered or glued to the board to ensure good mechanical stability. If the center
pad is left unconnected, the package might loosen from the board.
2
3
1
4
5
6
7
8
9
10
11
12
13
14
16 33
15
47
46
48
45
44
43
42
41
40
39
38
37
36
35
34
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
AT90USB128/64
(64-lead QFN top view)
INDEX CORNER
AVCC
G
N
D
AREF
PF0 (ADC0)
PF1 (ADC1)
PF2 (ADC2)
PF3 (ADC3)
PF4 (ADC4/TCK)
PF5 (ADC5/TMS)
PF6 (ADC6/TDO)
PF7 (ADC7/TDI)
G
N
D
VCC
PA0 (AD0)
PA1 (AD1)
PA2 (AD2)
(INT.7/AIN.1/UVcon) PE7
UVcc
D-
D+
UGnd
UCap
VBus
(IUID) PE3
(SS/PCINT0) PB0
(INT.6/AIN.0) PE6
(PCINT1/SCLK) PB1
(PDI/PCINT2/MOSI) PB2
(PDO/PCINT3/MISO) PB3
(PCINT4/OC.2A) PB4
(PCINT5/OC.1A) PB5
(PCINT6/OC.1B) PB6
(PCI
NT7/OC.0A/OC.1C) PB7
(INT4/TOSC1) PE4
(INT.5/TOSC2) PE5
VCC
G
N
D
XTAL2
XTAL1
(OC0B/SCL/I
NT0) PD0
(OC2B/SDA/I
NT1) PD1
(RXD1/I
NT2) PD2
(TXD1/I
NT3) PD3
(ICP1) PD4
(XCK1) PD5
(T1) PD6
(T0) PD7
RESET
PA3 (AD3)
PA4 (AD4)
PA5 (AD5)
PA6 (AD6)
PA7 (AD7)
PE2 (ALE/HWB)
PC7 (A15/IC.3/CLKO)
PC6 (A14/OC.3A)
PC5 (A13/OC.3B)
PC4 (A12/OC.3C)
PC3 (A11/T.3)
PC2 (A10)
PC1 (A9)
PC0 (A8)
PE1 (RD)
PE0 (WR)5
7593L–AVR–09/12
AT90USB64/128
2. Overview
The Atmel® AVR® AT90USB64/128 is a low-power CMOS 8-bit microcontroller based on the
Atmel® AVR® enhanced RISC architecture. By executing powerful instructions in a single clock
cycle, the AT90USB64/128 achieves throughputs approaching 1MIPS per MHz allowing the system
designer to optimize power consumption versus processing speed.6
7593L–AVR–09/12
AT90USB64/128
2.1 Block diagram
Figure 2-1. Block diagram.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the
32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
PROGRAM
COUNTER
ST ACK
POINTER
PROGRAM
FLASH
MCU CONTROL
REGISTER SRAM
GENERAL
PURPOSE
REGISTERS
INSTRUCTION
REGISTER
TIMER/
COUNTERS
INSTRUCTION
DECODER
DATA DIR.
REG. PORTB
DATA DIR.
REG. PORTE
DATA DIR.
REG. PORT A
DATA DIR.
REG. PORTD
DATA REGISTER
PORTB
DATA REGISTER
PORTE
DATA REGISTER
PORT A
DATA REGISTER
PORTD
INTERRUPT
UNIT
EEPROM
USART1 SPI
ST ATUS
REGISTER
Z
Y
X
ALU
POR TE DRIVERS POR TB DRIVERS
POR TF DRIVERS POR TA DRIVERS
POR TD DRIVERS
POR TC DRIVERS
PE7 - PE0 PB7 - PB0
PF7 - PF0 PA7 - P A0
RESET
VCC
AGND
GND
AREF
XT AL1
XT AL2
CONTROL
LINES
+
-
ANALOG
COMP ARATOR
PC7 - PC0
INTERNAL
OSCILLA TOR
WATCHDOG
TIMER
8-BIT DA TA BUS
AVCC
USB
TIMING AND
CONTROL
OSCILLA TOR
CALIB. OSC
DATA DIR.
REG. PORT C
DATA REGISTER
PORT C
ON-CHIP DEBUG
JTAG TAP
PROGRAMMING
LOGIC
BOUNDARYSCAN
DATA DIR.
REG. PORT F
DATA REGISTER
PORT F
ADC
POR - BOD
RESET
PD7 - PD0
TWO-WIRE SERIAL
INTERFACE
PLL7
7593L–AVR–09/12
AT90USB64/128
architecture is more code efficient while achieving throughputs up to ten times faster than conventional
CISC microcontrollers.
The Atmel AT90USB64/128 provides the following features: 64/128Kbytes of In-System Programmable
Flash with Read-While-Write capabilities, 2K/4Kbytes EEPROM, 4K/8K bytes
SRAM, 48 general purpose I/O lines, 32 general purpose working registers, Real Time Counter
(RTC), four flexible Timer/Counters with compare modes and PWM, one USART, a byte oriented
2-wire Serial Interface, a 8-channels, 10-bit ADC with optional differential input stage with
programmable gain, programmable Watchdog Timer with Internal Oscillator, an SPI serial port,
IEEE std. 1149.1 compliant JTAG test interface, also used for accessing the On-chip Debug system
and programming and six software selectable power saving modes. The Idle mode stops
the CPU while allowing the SRAM, Timer/Counters, SPI port, and interrupt system to continue
functioning. The Power-down mode saves the register contents but freezes the Oscillator, disabling
all other chip functions until the next interrupt or Hardware Reset. In Power-save mode,
the asynchronous timer continues to run, allowing the user to maintain a timer base while the
rest of the device is sleeping. The ADC Noise Reduction mode stops the CPU and all I/O modules
except Asynchronous Timer and ADC, to minimize switching noise during ADC
conversions. In Standby mode, the Crystal/Resonator Oscillator is running while the rest of the
device is sleeping. This allows very fast start-up combined with low power consumption. In
Extended Standby mode, both the main Oscillator and the Asynchronous Timer continue to run.
The device is manufactured using the Atmel high-density nonvolatile memory technology. The
On-chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI
serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program
running on the AVR core. The boot program can use any interface to download the
application program in the application Flash memory. Software in the Boot Flash section will
continue to run while the Application Flash section is updated, providing true Read-While-Write
operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a
monolithic chip, the AT90USB64/128 is a powerful microcontroller that provides a highly flexible
and cost effective solution to many embedded control applications.
The AT90USB64/128 AVR is supported with a full suite of program and system development
tools including: C compilers, macro assemblers, program debugger/simulators, in-circuit emulators,
and evaluation kits.8
7593L–AVR–09/12
AT90USB64/128
2.2 Pin descriptions
2.2.1 VCC
Digital supply voltage.
2.2.2 GND
Ground.
2.2.3 AVCC
Analog supply voltage.
2.2.4 Port A (PA7..PA0)
Port A is an 8-bit bidirectional I/O port with internal pull-up resistors (selected for each bit). The
Port A output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port A pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port A pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port A also serves the functions of various special features of the Atmel AT90USB64/128 as
listed on page 78.
2.2.5 Port B (PB7..PB0)
Port B is an 8-bit bidirectional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port B has better driving capabilities than the other ports.
Port B also serves the functions of various special features of the AT90USB64/128 as listed on
page 79.
2.2.6 Port C (PC7..PC0)
Port C is an 8-bit bidirectional I/O port with internal pull-up resistors (selected for each bit). The
Port C output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port C also serves the functions of special features of the AT90USB64/128 as listed on page 82.
2.2.7 Port D (PD7..PD0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port D also serves the functions of various special features of the AT90USB64/128 as listed on
page 83. 9
7593L–AVR–09/12
AT90USB64/128
2.2.8 Port E (PE7..PE0)
Port E is an 8-bit bidirectional I/O port with internal pull-up resistors (selected for each bit). The
Port E output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port E pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port E also serves the functions of various special features of the AT90USB64/128 as listed on
page 86.
2.2.9 Port F (PF7..PF0)
Port F serves as analog inputs to the A/D Converter.
Port F also serves as an 8-bit bidirectional I/O port, if the A/D Converter is not used. Port pins
can provide internal pull-up resistors (selected for each bit). The Port F output buffers have symmetrical
drive characteristics with both high sink and source capability. As inputs, Port F pins
that are externally pulled low will source current if the pull-up resistors are activated. The Port F
pins are tri-stated when a reset condition becomes active, even if the clock is not running. If the
JTAG interface is enabled, the pull-up resistors on pins PF7(TDI), PF5(TMS), and PF4(TCK) will
be activated even if a reset occurs.
Port F also serves the functions of the JTAG interface.
2.2.10 DUSB
Full speed / Low Speed Negative Data Upstream Port. Should be connected to the USB Dconnector
pin with a serial 22Ω resistor.
2.2.11 D+
USB Full speed / Low Speed Positive Data Upstream Port. Should be connected to the USB D+
connector pin with a serial 22Ω resistor.
2.2.12 UGND
USB Pads Ground.
2.2.13 UVCC
USB Pads Internal Regulator Input supply voltage.
2.2.14 UCAP
USB Pads Internal Regulator Output supply voltage. Should be connected to an external capacitor
(1µF).
2.2.15 VBUS
USB VBUS monitor and OTG negociations.
2.2.16 RESET
Reset input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running. The minimum pulse length is given in Table 9-1 on page
58. Shorter pulses are not guaranteed to generate a reset.
2.2.17 XTAL1
Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.10
7593L–AVR–09/12
AT90USB64/128
2.2.18 XTAL2
Output from the inverting oscillator amplifier.
2.2.19 AVCC
AVCC is the supply voltage pin for Port F and the A/D Converter. It should be externally connected
to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC
through a low-pass filter.
2.2.20 AREF
This is the analog reference pin for the A/D Converter.
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
4. About code examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.
These code examples assume that the part specific header file is included before compilation.
For I/O registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI"
instructions must be replaced with instructions that allow access to extended I/O. Typically
"LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR".11
7593L–AVR–09/12
AT90USB64/128
5. AVR CPU core
5.1 Introduction
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
5.2 Architectural overview
Figure 5-1. Block diagram of the AVR architecture.
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Re-programmable Flash memory.
Flash
program
memory
Instruction
register
Instruction
decoder
Program
counter
Control lines
32 x 8
general
purpose
registrers
ALU
Status
and control
I/O lines
EEPROM
Data bus 8-bit
Data
SRAM
Direct addressing
Indirect addressing
Interrupt
unit
SPI
unit
Watchdog
timer
Analog
comparator
I/O Module 2
I/O Module1
I/O Module n12
7593L–AVR–09/12
AT90USB64/128
The fast-access Register File contains 32 × 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format.
Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the Atmel
AT90USB64/128 has Extended I/O space from 0x60 - 0xFF in SRAM where only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
5.3 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See the “Instruction set summary” on page 423 for a detailed description.13
7593L–AVR–09/12
AT90USB64/128
5.4 Status register
The status register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform conditional
operations. Note that the status register is updated after all ALU operations, as specified in the
Instruction Set Reference. This will in many cases remove the need for using the dedicated compare
instructions, resulting in faster and more compact code.
The status register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.
The AVR status register – SREG – is defined as:
• Bit 7 – I: Global Interrupt Enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination
for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
• Bit 5 – H: Half Carry Flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful
in BCD arithmetic. See the “Instruction set summary” on page 423 for detailed information.
• Bit 4 – S: Sign Bit, S = N ⊕ V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction set summary” on page 423 for detailed information.
• Bit 3 – V: Two’s Complement Overflow Flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction set summary” on page 423 for detailed information.
• Bit 2 – N: Negative Flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction set summary” on page 423 for detailed information.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
set summary” on page 423 for detailed information.
Bit 7 6 5 4 3 2 1 0
I T H S V N Z C SREG
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 014
7593L–AVR–09/12
AT90USB64/128
• Bit 0 – C: Carry Flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction set
summary” on page 423 for detailed information.
5.5 General purpose register file
The register file is optimized for the AVR Enhanced RISC instruction set. In order to achieve the
required performance and flexibility, the following input/output schemes are supported by the
register file:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 5-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 5-2. AVR CPU general purpose working registers.
Most of the instructions operating on the Register File have direct access to all registers, and
most of them are single cycle instructions.
As shown in Figure 5-2, each register is also assigned a data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y-, and Z-pointer registers can be set to index any register in the file.
5.5.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 5-3.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
purpose R15 0x0F
working R16 0x10
registers R17 0x11
…
R26 0x1A X-register Low byte
R27 0x1B X-register High byte
R28 0x1C Y-register Low byte
R29 0x1D Y-register High byte
R30 0x1E Z-register Low byte
R31 0x1F Z-register High byte15
7593L–AVR–09/12
AT90USB64/128
Figure 5-3. The X-, Y-, and Z-registers.
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
5.6 Stack pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x0100. The initial value of the stack pointer is the last address of the internal
SRAM. The Stack Pointer is decremented by one when data is pushed onto the Stack with the
PUSH instruction, and it is decremented by three when the return address is pushed onto the
Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is
popped from the Stack with the POP instruction, and it is incremented by three when data is
popped from the Stack with return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations
of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
15 XH XL 0
X-register 7 07 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 07 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 70 7 0
R31 (0x1F) R30 (0x1E)
Bit 15 14 13 12 11 10 9 8
SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 1 0 0 0 0 0
1111111116
7593L–AVR–09/12
AT90USB64/128
5.6.1 RAMPZ - Extended Z-pointer register for ELPM/SPM
For ELPM/SPM instructions, the Z-pointer is a concatenation of RAMPZ, ZH, and ZL, as shown
in Figure 5-4. Note that LPM is not affected by the RAMPZ setting.
Figure 5-4. The Z-pointer used by ELPM and SPM.
The actual number of bits is implementation dependent. Unused bits in an implementation will
always read as zero. For compatibility with future devices, be sure to write these bits to zero.
5.7 Instruction execution timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the
chip. No internal clock division is used.
Figure 5-5 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 5-5. The parallel instruction fetches and instruction executions.
Figure 5-6 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Bit 7 6 5 4 3 2 1 0
RAMPZ7 RAMPZ6 RAMPZ5 RAMPZ4 RAMPZ3 RAMPZ2 RAMPZ1 RAMPZ0 RAMPZ
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit (individually) 7 0 7 0 7 0
RAMPZ ZH ZL
Bit (Z-pointer) 23 16 15 8 7 0
clk
1st instruction fetch
1st instruction execute
2nd instruction fetch
2nd instruction execute
3rd instruction fetch
3rd instruction execute
4th instruction fetch
T1 T2 T3 T4
CPU17
7593L–AVR–09/12
AT90USB64/128
Figure 5-6. Single cycle ALU operation.
5.8 Reset and interrupt handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate program vector in the program memory space. All interrupts are
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt. Depending on the Program
Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12
are programmed. This feature improves software security. See the section “Memory programming”
on page 359 for details.
The lowest addresses in the program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 68. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request
0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL
bit in the MCU Control Register (MCUCR). Refer to “Interrupts” on page 68 for more information.
The Reset Vector can also be moved to the start of the Boot Flash section by programming the
BOOTRST Fuse, see “Memory programming” on page 359.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s)
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt
Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Total execution time
Register operands fetch
ALU operation execute
Result write back
T1 T2 T3 T4
clkCPU18
7593L–AVR–09/12
AT90USB64/128
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed
before any pending interrupts, as shown in this example.
Assembly code example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C code example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
__disable_interrupt();
EECR |= (1< CSn2:0 > 1). The number of system clock cycles from
when the timer is enabled to the first count occurs can be from 1 to N+1 system clock cycles,
where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution.
However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
13.3 External clock source
An external clock source applied to the Tn pin can be used as Timer/Counter clock (clkTn). The
Tn pin is sampled once every system clock cycle by the pin synchronization logic. The synchronized
(sampled) signal is then passed through the edge detector. Figure 13-1 shows a functional
equivalent block diagram of the Tn synchronization and edge detector logic. The registers are
clocked at the positive edge of the internal system clock (clkI/O). The latch is transparent in the
high period of the internal system clock.
The edge detector generates one clkTn pulse for each positive (CSn2:0 = 7) or negative (CSn2:0
= 6) edge it detects.
Figure 13-1. Tn/T0 pin sampling.
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the Tn pin to the counter is updated.
Enabling and disabling of the clock input must be done when Tn has been stable for at least one
system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Tn_sync
(To clock
select logic)
Synchronization Edge detector
D Q D Q
LE
Tn D Q
clkI/O97
7593L–AVR–09/12
AT90USB64/128
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system
clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency
(Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 13-2. Prescaler for synchronous Timer/Counters
13.4 GTCCR – General Timer/Counter Control Register
• Bit 7 – TSM: Timer/Counter Synchronization Mode
Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the
value that is written to the PSRASY and PSRSYNC bits is kept, hence keeping the corresponding
prescaler reset signals asserted. This ensures that the corresponding Timer/Counters are
halted and can be configured to the same value without the risk of one of them advancing during
configuration. When the TSM bit is written to zero, the PSRASY and PSRSYNC bits are cleared
by hardware, and the Timer/Counters start counting simultaneously.
• Bit 0 – PSRSYNC: Prescaler Reset for Synchronous Timer/Counters
When this bit is one, Timer/Counter0 and Timer/Counter1 and Timer/Counter3 prescaler will be
Reset. This bit is normally cleared immediately by hardware, except if the TSM bit is set. Note
that Timer/Counter0, Timer/Counter1 and Timer/Counter3 share the same prescaler and a reset
of this prescaler will affect all timers.
PSR10
Clear
Tn
Tn
clkI/O
Synchronization
Synchronization
TIMER/COUNTERn CLOCK SOURCE
clkTn
TIMER/COUNTERn CLOCK SOURCE
clkTn
CSn0
CSn1
CSn2
CSn0
CSn1
CSn2
Bit 7 6 5 4 3 2 1 0
TSM – – – – – PSRASY PSRSYNC GTCCR
Read/write R/W R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 098
7593L–AVR–09/12
AT90USB64/128
14. 8-bit Timer/Counter0 with PWM
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output
Compare Units, and with PWM support. It allows accurate program execution timing (event management)
and wave generation. The main features are:
• Two independent output compare units
• Double buffered output compare registers
• Clear timer on compare match (auto reload)
• Glitch free, phase correct pulse width modulator (PWM)
• Variable PWM period
• Frequency generator
• Three independent interrupt sources (TOV0, OCF0A, and OCF0B)
14.1 Overview
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 14-1. For the actual
placement of I/O pins, refer to “Pinout Atmel AT90USB64/128-TQFP.” on page 3. CPU accessible
I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O
Register and bit locations are listed in the “8-bit Timer/Counter register description” on page 108.
Figure 14-1. 8-bit Timer/Counter block diagram.
14.1.1 Registers
The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit
registers. Interrupt request (abbreviated to Int.Req. in the figure) signals are all visible in the
Timer Interrupt Flag Register (TIFR0). All interrupts are individually masked with the Timer Interrupt
Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0).
Clock select
Timer/Counter
DATA BUS
OCRnA
OCRnB
=
=
TCNTn
Waveform
generation
Waveform
generation
OCnA
OCnB
=
Fixed
TOP
value
Control logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(int.req.)
OCnA
(int.req.)
OCnB
(Int.Req.)
TCCRnA TCCRnB
Tn Edge
detector
(From prescaler)
clkTn99
7593L–AVR–09/12
AT90USB64/128
The double buffered Output Compare Registers (OCR0A and OCR0B) are compared with the
Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator
to generate a PWM or variable frequency output on the Output Compare pins (OC0A and
OC0B). See “Output compare unit” on page 100. for details. The Compare Match event will also
set the Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare
interrupt request.
14.1.2 Definitions
Many register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 0. A lower case “x” replaces the Output Compare
Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or
bit defines in a program, the precise form must be used, that is, TCNT0 for accessing
Timer/Counter0 counter value and so on.
The definitions in the table below are also used extensively throughout the document.
14.2 Timer/Counter clock sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source
is selected by the Clock Select logic which is controlled by the Clock Select (CS02:0) bits
located in the Timer/Counter Control Register (TCCR0B). For details on clock sources and prescaler,
see “Timer/Counter0, Timer/Counter1, and Timer/Counter3 prescalers” on page 96.
14.3 Counter unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
14-2 shows a block diagram of the counter and its surroundings.
Figure 14-2. Counter unit block diagram.
BOTTOM The counter reaches the BOTTOM when it becomes 0x00.
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR0A Register. The assignment is dependent
on the mode of operation.
DATA BUS
TCNTn Control logic
count
TOVn
(int.req.)
Clock select
top
Tn Edge
detector
(From prescaler)
clkTn
bottom
direction
clear100
7593L–AVR–09/12
AT90USB64/128
Signal description (internal signals):
count Increment or decrement TCNT0 by 1.
direction Select between increment and decrement.
clear Clear TCNT0 (set all bits to zero).
clkTn Timer/Counter clock, referred to as clkT0 in the following.
top Signalize that TCNT0 has reached maximum value.
bottom Signalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source,
selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the
timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of
whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in
the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter
Control Register B (TCCR0B). There are close connections between how the counter behaves
(counts) and how waveforms are generated on the Output Compare outputs OC0A and OC0B.
For more details about advanced counting sequences and waveform generation, see “Modes of
operation” on page 103.
The Timer/Counter Overflow Flag (TOV0) is set according to the mode of operation selected by
the WGM02:0 bits. TOV0 can be used for generating a CPU interrupt.
14.4 Output compare unit
The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers
(OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a
match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock
cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output
Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed.
Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit
location. The Waveform Generator uses the match signal to generate an output according to
operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The
maximum and bottom signals are used by the Waveform Generator for handling the special
cases of the extreme values in some modes of operation (“Modes of operation” on page 103).
Figure 14-3 on page 101 shows a block diagram of the Output Compare unit. 101
7593L–AVR–09/12
AT90USB64/128
Figure 14-3. Output Compare Unit, block diagram.
The OCR0x Registers are double buffered when using any of the Pulse Width Modulation
(PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double
buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare
Registers to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR0x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is disabled
the CPU will access the OCR0x directly.
14.4.1 Force output compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC0x) bit. Forcing Compare Match will not set the
OCF0x Flag or reload/clear the timer, but the OC0x pin will be updated as if a real Compare
Match had occurred (the COM0x1:0 bits settings define whether the OC0x pin is set, cleared or
toggled).
14.4.2 Compare match blocking by TCNT0 write
All CPU write operations to the TCNT0 Register will block any Compare Match that occur in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR0x to be initialized
to the same value as TCNT0 without triggering an interrupt when the Timer/Counter clock is
enabled.
14.4.3 Using the output compare unit
Since writing TCNT0 in any mode of operation will block all Compare Matches for one timer
clock cycle, there are risks involved when changing TCNT0 when using the Output Compare
Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNT0
equals the OCR0x value, the Compare Match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is
down-counting.
OCFnx (int.req.)
= (8-bit comparator)
OCRnx
OCnx
DATA BUS
TCNTn
WGMn1:0
Waveform generator
top
FOCn
COMnX1:0
bottom102
7593L–AVR–09/12
AT90USB64/128
The setup of the OC0x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC0x value is to use the Force Output Compare
(FOC0x) strobe bits in Normal mode. The OC0x Registers keep their values even when
changing between Waveform Generation modes.
Be aware that the COM0x1:0 bits are not double buffered together with the compare value.
Changing the COM0x1:0 bits will take effect immediately.
14.5 Compare Match Output Unit
The Compare Output mode (COM0x1:0) bits have two functions. The Waveform Generator uses
the COM0x1:0 bits for defining the Output Compare (OC0x) state at the next Compare Match.
Also, the COM0x1:0 bits control the OC0x pin output source. Figure 14-4 shows a simplified
schematic of the logic affected by the COM0x1:0 bit setting. The I/O Registers, I/O bits, and I/O
pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COM0x1:0 bits are shown. When referring to the
OC0x state, the reference is for the internal OC0x Register, not the OC0x pin. If a system reset
occur, the OC0x Register is reset to “0”.
Figure 14-4. Compare Match Output Unit, schematic.
The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform
Generator if either of the COM0x1:0 bits are set. However, the OC0x pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x value is visible
on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC0x state before the output
is enabled. Note that some COM0x1:0 bit settings are reserved for certain modes of
operation. See “8-bit Timer/Counter register description” on page 108.
14.5.1 Compare output mode and waveform generation
The Waveform Generator uses the COM0x1:0 bits differently in Normal, CTC, and PWM modes.
For all modes, setting the COM0x1:0 = 0 tells the Waveform Generator that no action on the
OC0x Register is to be performed on the next Compare Match. For compare output actions in
PORT
DDR
D Q
D Q
OCnx
OCnx Pin
D Q Waveform
generator
COMnx1
COMnx0
0
1
DATA BUS
FOCn
clkI/O103
7593L–AVR–09/12
AT90USB64/128
the non-PWM modes refer to Table 14-1 on page 109. For fast PWM mode, refer to Table 14-2
on page 109, and for phase correct PWM refer to Table 14-3 on page 109.
A change of the COM0x1:0 bits state will have effect at the first Compare Match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC0x strobe bits.
14.6 Modes of operation
The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins,
is defined by the combination of the Waveform Generation mode (WGM02:0) and Compare Output
mode (COM0x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM0x1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM0x1:0 bits control whether the output should be set, cleared, or toggled at a Compare
Match (See “Compare Match Output Unit” on page 102.).
For detailed timing information see “Timer/Counter timing diagrams” on page 107.
14.6.1 Normal mode
The simplest mode of operation is the Normal mode (WGM02:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same
timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV0 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare Unit can be used to generate interrupts at some given time. Using the Output
Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
14.6.2 Clear Timer on Compare Match (CTC) mode
In Clear Timer on Compare or CTC mode (WGM02:0 = 2), the OCR0A Register is used to
manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter
value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence
also its resolution. This mode allows greater control of the Compare Match output frequency. It
also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 14-5 on page 104. The counter value
(TCNT0) increases until a Compare Match occurs between TCNT0 and OCR0A, and then counter
(TCNT0) is cleared.104
7593L–AVR–09/12
AT90USB64/128
Figure 14-5. CTC mode, timing diagram.
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running
with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR0A is lower than the current
value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can
occur.
For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical
level on each Compare Match by setting the Compare Output mode bits to toggle mode
(COM0A1:0 = 1). The OC0A value will not be visible on the port pin unless the data direction for
the pin is set to output. The waveform generated will have a maximum frequency of fOC0 =
fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following
equation:
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
14.6.3 Fast PWM mode
The fast Pulse Width Modulation or fast PWM mode (WGM02:0 = 3 or 7) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by
its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM.
TOP is defined as 0xFF when WGM2:0 = 3, and OCR0A when WGM2:0 = 7. In noninverting
Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match
between TCNT0 and OCR0x, and set at BOTTOM. In inverting Compare Output mode, the output
is set on Compare Match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the TOP value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
TCNTn
OCn
(Toggle)
OCnx Interrupt Flag Set
Period 1 2 3 4
(COMnx1:0 = 1)
f
OCnx
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnx = -------------------------------------------------105
7593L–AVR–09/12
AT90USB64/128
PWM mode is shown in Figure 14-6. The TCNT0 value is in the timing diagram shown as a histogram
for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare
Matches between OCR0x and TCNT0.
Figure 14-6. Fast PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the interrupt
is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins.
Setting the COM0x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM0x1:0 to three: Setting the COM0A1:0 bits to one allows
the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available
for the OC0B pin (see Table 14-2 on page 109). The actual OC0x value will only be visible on
the port pin if the data direction for the port pin is set as output. The PWM waveform is generated
by setting (or clearing) the OC0x Register at the Compare Match between OCR0x and
TCNT0, and clearing (or setting) the OC0x Register at the timer clock cycle the counter is
cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM0A1:0
bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC0x to toggle its logical level on each Compare Match (COM0x1:0 = 1). The waveform
generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is set to zero. This
TCNTn
OCRnx update and
TOVn Interrupt Flag Set
Period 1 2 3
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Interrupt Flag Set
4 5 6 7
f
OCnxPWM
f
clk_I/O
N ⋅ 256 = ------------------106
7593L–AVR–09/12
AT90USB64/128
feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output
Compare unit is enabled in the fast PWM mode.
14.6.4 Phase correct PWM mode
The phase correct PWM mode (WGM02:0 = 1 or 5) provides a high resolution phase correct
PWM waveform generation option. The phase correct PWM mode is based on a dual-slope
operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM.
TOP is defined as 0xFF when WGM2:0 = 1, and OCR0A when WGM2:0 = 5. In noninverting
Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match
between TCNT0 and OCR0x while up-counting, and set on the Compare Match while downcounting.
In inverting Output Compare mode, the operation is inverted. The dual-slope operation
has lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
In phase correct PWM mode the counter is incremented until the counter value matches TOP.
When the counter reaches TOP, it changes the count direction. The TCNT0 value will be equal
to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown
on Figure 14-7. The TCNT0 value is in the timing diagram shown as a histogram for illustrating
the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The
small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0x
and TCNT0.
Figure 14-7. Phase correct PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC0x pins. Setting the COM0x1:0 bits to two will produce a non-inverted PWM. An inverted
PWM output can be generated by setting the COM0x1:0 to three: Setting the COM0A0 bits to
TOVn Interrupt Flag Set
OCnx Interrupt Flag Set
1 2 3
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx update107
7593L–AVR–09/12
AT90USB64/128
one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is
not available for the OC0B pin (see Table 14-3 on page 109). The actual OC0x value will only be
visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is
generated by clearing (or setting) the OC0x Register at the Compare Match between OCR0x
and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at Compare
Match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for
the output when using phase correct PWM can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR0A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 14-7 on page 106 OCnx has a transition from high to low
even though there is no Compare Match. The point of this transition is to guarantee symmetry
around BOTTOM. There are two cases that give a transition without Compare Match.
• OCR0A changes its value from MAX, like in Figure 14-7 on page 106. When the OCR0A
value is MAX the OCn pin value is the same as the result of a down-counting Compare
Match. To ensure symmetry around BOTTOM the OCn value at MAX must correspond to the
result of an up-counting Compare Match
• The timer starts counting from a value higher than the one in OCR0A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up
14.7 Timer/Counter timing diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a
clock enable signal in the following figures. The figures include information on when Interrupt
Flags are set. Figure 14-8 contains timing data for basic Timer/Counter operation. The figure
shows the count sequence close to the MAX value in all modes other than phase correct PWM
mode.
Figure 14-8. Timer/Counter timing diagram, no prescaling.
Figure 14-9 on page 108 shows the same timing data, but with the prescaler enabled.
f
OCnxPCPWM
f
clk_I/O
N ⋅ 510 = ------------------
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1108
7593L–AVR–09/12
AT90USB64/128
Figure 14-9. Timer/Counter timing diagram, with prescaler (fclk_I/O/8).
Figure 14-10 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC
mode and PWM mode, where OCR0A is TOP.
Figure 14-10. Timer/Counter timing diagram, setting of OCF0x, with prescaler (fclk_I/O/8).
Figure 14-11 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast
PWM mode where OCR0A is TOP.
Figure 14-11. Timer/Counter timing diagram, clear timer on Compare Match mode, with prescaler
(fclk_I/O/8)
14.8 8-bit Timer/Counter register description
14.8.1 TCCR0A – Timer/Counter Control Register A
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
OCRnx Value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
Bit 7 6 5 4 3 2 1 0
COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00 TCCR0A
Read/write R/W R/W R/W R/W R R R/W R/W
Initial value 0 0 0 0 0 0 0 0109
7593L–AVR–09/12
AT90USB64/128
• Bits 7:6 – COM01A:0: Compare Match Output A Mode
These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A1:0
bits are set, the OC0A output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0A pin
must be set in order to enable the output driver.
When OC0A is connected to the pin, the function of the COM0A1:0 bits depends on the
WGM02:0 bit setting. Table 14-1 shows the COM0A1:0 bit functionality when the WGM02:0 bits
are set to a normal or CTC mode (non-PWM).
Table 14-2 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Fast PWM mode” on page 104
for more details.
Table 14-3 shows the COM0A1:0 bit functionality when the WGM02:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 106 for more details.
Table 14-1. Compare Output mode, non-PWM mode.
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
0 1 Toggle OC0A on Compare Match
1 0 Clear OC0A on Compare Match
1 1 Set OC0A on Compare Match
Table 14-2. Compare Output mode, Fast PWM mode (1).
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
0 1 WGM02 = 0: Normal Port Operation, OC0A Disconnected.
WGM02 = 1: Toggle OC0A on Compare Match.
1 0 Clear OC0A on Compare Match, set OC0A at TOP
1 1 Set OC0A on Compare Match, clear OC0A at TOP
Table 14-3. Compare Output mode, phase correct PWM mode (1).
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0A disconnected.
0 1 WGM02 = 0: Normal Port Operation, OC0A Disconnected.
WGM02 = 1: Toggle OC0A on Compare Match.
1 0 Clear OC0A on Compare Match when up-counting. Set OC0A on Compare
Match when down-counting.
1 1 Set OC0A on Compare Match when up-counting. Clear OC0A on Compare
Match when down-counting.110
7593L–AVR–09/12
AT90USB64/128
• Bits 5:4 – COM0B1:0: Compare Match Output B mode
These bits control the Output Compare pin (OC0B) behavior. If one or both of the COM0B1:0
bits are set, the OC0B output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0B pin
must be set in order to enable the output driver.
When OC0B is connected to the pin, the function of the COM0B1:0 bits depends on the
WGM02:0 bit setting. Table 14-1 shows the COM0A1:0 bit functionality when the WGM02:0 bits
are set to a normal or CTC mode (non-PWM).
Table 14-2 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Fast PWM mode” on page 104
for more details.
Table 14-3 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 106 for more details.
• Bits 3, 2 – Res: Reserved bits
These bits are reserved bits in the Atmel AT90USB64/128 and will always read as zero.
Table 14-4. Compare Output mode, non-PWM mode.
COM01 COM00 Description
0 0 Normal port operation, OC0B disconnected.
0 1 Toggle OC0B on Compare Match
1 0 Clear OC0B on Compare Match
1 1 Set OC0B on Compare Match
Table 14-5. Compare Output mode, fast PWM mode (1).
COM01 COM00 Description
0 0 Normal port operation, OC0B disconnected.
0 1 Reserved.
1 0 Clear OC0B on Compare Match, set OC0B at TOP.
1 1 Set OC0B on Compare Match, clear OC0B at TOP.
Table 14-6. Compare Output mode, phase correct PWM mode (1).
COM0A1 COM0A0 Description
0 0 Normal port operation, OC0B disconnected.
0 1 Reserved.
1 0 Clear OC0B on Compare Match when up-counting. Set OC0B on Compare
Match when down-counting.
1 1 Set OC0B on Compare Match when up-counting. Clear OC0B on Compare
Match when down-counting.111
7593L–AVR–09/12
AT90USB64/128
• Bits 1:0 – WGM01:0: Waveform Generation Mode
Combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 14-7. Modes of operation supported by the Timer/Counter
unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of
Pulse Width Modulation (PWM) modes (see “Modes of operation” on page 103).
Notes: 1. MAX = 0xFF
2. BOTTOM = 0x00
14.8.2 TCCR0B – Timer/Counter Control Register B
• Bit 7 – FOC0A: Force Output Compare A
The FOC0A bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0A bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC0A output is
changed according to its COM0A1:0 bits setting. Note that the FOC0A bit is implemented as a
strobe. Therefore it is the value present in the COM0A1:0 bits that determines the effect of the
forced compare.
A FOC0A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR0A as TOP.
The FOC0A bit is always read as zero.
• Bit 6 – FOC0B: Force Output Compare B
The FOC0B bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0B bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC0B output is
changed according to its COM0B1:0 bits setting. Note that the FOC0B bit is implemented as a
Table 14-7. Waveform Generation Mode bit description.
Mode WGM2 WGM1 WGM0
Timer/Counter mode of
operation TOP
Update of
OCRx at
TOV flag
set on (1)(2)
0 0 0 0 Normal 0xFF Immediate MAX
1 0 0 1 PWM, phase correct 0xFF TOP BOTTOM
2 0 1 0 CTC OCRA Immediate MAX
3 0 1 1 Fast PWM 0xFF TOP MAX
4 1 0 0 Reserved – – –
5 1 0 1 PWM, phase correct OCRA TOP BOTTOM
6 1 1 0 Reserved – – –
7 1 1 1 Fast PWM OCRA TOP TOP
Bit 7 6 5 4 3 2 1 0
FOC0A FOC0B – – WGM02 CS02 CS01 CS00 TCCR0B
Read/write W W R R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0112
7593L–AVR–09/12
AT90USB64/128
strobe. Therefore it is the value present in the COM0B1:0 bits that determines the effect of the
forced compare.
A FOC0B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR0B as TOP.
The FOC0B bit is always read as zero.
• Bits 5:4 – Res: Reserved bits
These bits are reserved bits and will always read as zero.
• Bit 3 – WGM02: Waveform Generation Mode
See the description in the “TCCR0A – Timer/Counter Control Register A” on page 108.
• Bits 2:0 – CS02:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter.
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
14.8.3 TCNT0 – Timer/Counter Register
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare
Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running,
introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers.
14.8.4 OCR0A – Output Compare Register A
Table 14-8. Clock Select bit description.
CS02 CS01 CS00 Description
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clkI/O/(No prescaling)
0 1 0 clkI/O/8 (From prescaler)
0 1 1 clkI/O/64 (From prescaler)
1 0 0 clkI/O/256 (From prescaler)
1 0 1 clkI/O/1024 (From prescaler)
1 1 0 External clock source on T0 pin. Clock on falling edge.
1 1 1 External clock source on T0 pin. Clock on rising edge.
Bit 7 6 5 4 3 2 1 0
TCNT0[7:0] TCNT0
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR0A[7:0] OCR0A
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0113
7593L–AVR–09/12
AT90USB64/128
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0A pin.
14.8.5 OCR0B – Output Compare Register B
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC0B pin.
14.8.6 TIMSK0 – Timer/Counter Interrupt Mask Register
• Bits 7..3, 0 – Res: Reserved bits
These bits are reserved bits and will always read as zero.
• Bit 2 – OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable
When the OCIE0B bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter Compare Match B interrupt is enabled. The corresponding interrupt is executed if
a Compare Match in Timer/Counter occurs, that is, when the OCF0B bit is set in the
Timer/Counter Interrupt Flag Register – TIFR0.
• Bit 1 – OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable
When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter0 Compare Match A interrupt is enabled. The corresponding interrupt is executed
if a Compare Match in Timer/Counter0 occurs, that is, when the OCF0A bit is set in the
Timer/Counter 0 Interrupt Flag Register – TIFR0.
• Bit 0 – TOIE0: Timer/Counter0 Overflow Interrupt Enable
When the TOIE0 bit is written to one, and the I-bit in the Status Register is set, the
Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter0 occurs, that is, when the TOV0 bit is set in the Timer/Counter 0 Interrupt
Flag Register – TIFR0.
14.8.7 TIFR0 – Timer/Counter 0 Interrupt Flag Register
• Bits 7..3, 0 – Res: Reserved bits
These bits are reserved bits in the Atmel AT90USB64/128 and will always read as zero.
Bit 7 6 5 4 3 2 1 0
OCR0B[7:0] OCR0B
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – – – – OCIE0B OCIE0A TOIE0 TIMSK0
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – – – – OCF0B OCF0A TOV0 TIFR0
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0114
7593L–AVR–09/12
AT90USB64/128
• Bit 2 – OCF0B: Timer/Counter 0 Output Compare B Match Flag
The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in
OCR0B – Output Compare Register0 B. OCF0B is cleared by hardware when executing the corresponding
interrupt handling vector. Alternatively, OCF0B is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable),
and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed.
• Bit 1 – OCF0A: Timer/Counter 0 Output Compare A Match Flag
The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data
in OCR0A – Output Compare Register0. OCF0A is cleared by hardware when executing the corresponding
interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one to
the flag. When the I-bit in SREG, OCIE0A (Timer/Counter0 Compare Match Interrupt Enable),
and OCF0A are set, the Timer/Counter0 Compare Match Interrupt is executed.
• Bit 0 – TOV0: Timer/Counter0 Overflow Flag
The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by
writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt
Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed.
The setting of this flag is dependent of the WGM02:0 bit setting. Refer to Table 14-7, “Waveform
Generation Mode bit description.” on page 111.115
7593L–AVR–09/12
AT90USB64/128
15. 16-bit Timer/Counter (Timer/Counter1 and Timer/Counter3)
The 16-bit Timer/Counter unit allows accurate program execution timing (event management),
wave generation, and signal timing measurement. The main features are:
• True 16-bit design (that is, allows 16-bit PWM)
• Three independent output compare units
• Double buffered output compare registers
• One input capture unit
• Input capture noise canceler
• Clear timer on compare match (auto reload)
• Glitch-free, phase correct pulse width modulator (PWM)
• Variable PWM period
• Frequency generator
• External event counter
• Ten independent interrupt sources (TOV1, OCF1A, OCF1B, OCF1C, ICF1, TOV3, OCF3A, OCF3B,
OCF3C, and ICF3)
15.1 Overview
Most register and bit references in this section are written in general form. A lower case “n”
replaces the Timer/Counter number, and a lower case “x” replaces the Output Compare unit
channel. However, when using the register or bit defines in a program, the precise form must be
used, that is, TCNT1 for accessing Timer/Counter1 counter value and so on.
A simplified block diagram of the 16-bit Timer/Counter is shown in Figure 15-1 on page 116. For
the actual placement of I/O pins, see “Pinout Atmel AT90USB64/128-TQFP.” on page 3. CPU
accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific
I/O Register and bit locations are listed in the “16-bit Timer/Counter (Timer/Counter1 and
Timer/Counter3)” on page 115.
The Power Reduction Timer/Counter1 bit, PRTIM1, in “PRR0 – Power Reduction Register 0” on
page 54 must be written to zero to enable Timer/Counter1 module.
The Power Reduction Timer/Counter3 bit, PRTIM3, in “PRR1 – Power Reduction Register 1” on
page 55 must be written to zero to enable Timer/Counter3 module.116
7593L–AVR–09/12
AT90USB64/128
Figure 15-1. 16-bit Timer/Counter block diagram (1).
Note: 1. Refer to Figure 1-1 on page 3, Table 11-6 on page 79, and Table 11-9 on page 82 for
Timer/Counter1 and 3 and 3 pin placement and description.
15.1.1 Registers
The Timer/Counter (TCNTn), Output Compare Registers (OCRnA/B/C), and Input Capture Register
(ICRn) are all 16-bit registers. Special procedures must be followed when accessing the 16-
bit registers. These procedures are described in the section “Accessing 16-bit registers” on page
117. The Timer/Counter Control Registers (TCCRnA/B/C) are 8-bit registers and have no CPU
access restrictions. Interrupt requests (shorten as Int.Req.) signals are all visible in the Timer
Interrupt Flag Register (TIFRn). All interrupts are individually masked with the Timer Interrupt
Mask Register (TIMSKn). TIFRn and TIMSKn are not shown in the figure since these registers
are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on
the Tn pin. The Clock Select logic block controls which clock source and edge the Timer/Counter
uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source
is selected. The output from the clock select logic is referred to as the timer clock (clkTn).
The double buffered Output Compare Registers (OCRnA/B/C) are compared with the
Timer/Counter value at all time. The result of the compare can be used by the Waveform Generator
to generate a PWM or variable frequency output on the Output Compare pin (OCnA/B/C).
ICFn (Int.Req.)
TOVn
(int.req.)
Clock select
Timer/Counter
DATABUS
ICRn
=
=
=
TCNTn
Waveform
generation
Waveform
generation
Waveform
generation
OCnA
OCnB
OCnC
Noise
canceler
ICPn
=
Fixed
TOP
values
Edge
detector
Control logic
= 0
TOP BOTTOM
Count
Clear
Direction
OCFnA
(Int.Req.)
OCFnB
(Int.Req.)
OCFnC
(Int.Req.)
TCCRnA TCCRnB TCCRnC
( From Analog
Comparator Ouput )
Tn Edge
detector
(From prescaler)
TCLK
OCRnC
OCRnB
OCRnA117
7593L–AVR–09/12
AT90USB64/128
See “Output Compare units” on page 124.. The compare match event will also set the Compare
Match Flag (OCFnA/B/C) which can be used to generate an Output Compare interrupt request.
The Input Capture Register can capture the Timer/Counter value at a given external (edge triggered)
event on either the Input Capture pin (ICPn) or on the Analog Comparator pins (see
“Analog Comparator” on page 304) The Input Capture unit includes a digital filtering unit (Noise
Canceler) for reducing the chance of capturing noise spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined
by either the OCRnA Register, the ICRn Register, or by a set of fixed values. When using
OCRnA as TOP value in a PWM mode, the OCRnA Register can not be used for generating a
PWM output. However, the TOP value will in this case be double buffered allowing the TOP
value to be changed in run time. If a fixed TOP value is required, the ICRn Register can be used
as an alternative, freeing the OCRnA to be used as PWM output.
15.1.2 Definitions
The following definitions are used extensively throughout the document:
15.2 Accessing 16-bit registers
The TCNTn, OCRnA/B/C, and ICRn are 16-bit registers that can be accessed by the AVR CPU
via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations.
Each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-
bit access. The same Temporary Register is shared between all 16-bit registers within each 16-
bit timer. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of
a 16-bit register is written by the CPU, the high byte stored in the Temporary Register, and the
low byte written are both copied into the 16-bit register in the same clock cycle. When the low
byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the
Temporary Register in the same clock cycle as the low byte is read.
Not all 16-bit accesses uses the Temporary Register for the high byte. Reading the OCRnA/B/C
16-bit registers does not involve using the Temporary Register.
To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low
byte must be read before the high byte.
The following code examples show how to access the 16-bit timer registers assuming that no
interrupts updates the temporary register. The same principle can be used directly for accessing
the OCRnA/B/C and ICRn Registers. Note that when using “C”, the compiler handles the 16-bit
access.
BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.
MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).
TOP
The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be one of the fixed values:
0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCRnA or ICRn
Register. The assignment is dependent of the mode of operation.118
7593L–AVR–09/12
AT90USB64/128
Note: 1. See “About code examples” on page 10.
The assembly code example returns the TCNTn value in the r17:r16 register pair.
It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt
occurs between the two instructions accessing the 16-bit register, and the interrupt code
updates the temporary register by accessing the same or any other of the 16-bit Timer Registers,
then the result of the access outside the interrupt will be corrupted. Therefore, when both
the main code and the interrupt code update the temporary register, the main code must disable
the interrupts during the 16-bit access.
Assembly code examples (1)
...
; Set TCNTn to 0x01FF
ldi r17,0x01
ldi r16,0xFF
out TCNTnH,r17
out TCNTnL,r16
; Read TCNTn into r17:r16
in r16,TCNTnL
in r17,TCNTnH
...
C code examples (1)
unsigned int i;
...
/* Set TCNTn to 0x01FF */
TCNTn = 0x1FF;
/* Read TCNTn into i */
i = TCNTn;
...119
7593L–AVR–09/12
AT90USB64/128
The following code examples show how to do an atomic read of the TCNTn Register contents.
Reading any of the OCRnA/B/C or ICRn Registers can be done by using the same principle.
Note: 1. See “About code examples” on page 10.
The assembly code example returns the TCNTn value in the r17:r16 register pair.
Assembly code example (1)
TIM16_ReadTCNTn:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Read TCNTn into r17:r16
in r16,TCNTnL
in r17,TCNTnH
; Restore global interrupt flag
out SREG,r18
ret
C code example (1)
unsigned int TIM16_ReadTCNTn( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
__disable_interrupt();
/* Read TCNTn into i */
i = TCNTn;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}120
7593L–AVR–09/12
AT90USB64/128
The following code examples show how to do an atomic write of the TCNTn Register contents.
Writing any of the OCRnA/B/C or ICRn Registers can be done by using the same principle.
Note: 1. See “About code examples” on page 10.
The assembly code example requires that the r17:r16 register pair contains the value to be written
to TCNTn.
15.2.1 Reusing the Temporary High Byte register
If writing to more than one 16-bit register where the high byte is the same for all registers written,
then the high byte only needs to be written once. However, note that the same rule of atomic
operation described previously also applies in this case.
15.3 Timer/Counter clock sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source
is selected by the Clock Select logic which is controlled by the Clock Select (CSn2:0) bits
located in the Timer/Counter control Register B (TCCRnB). For details on clock sources and
prescaler, see Section “Timer/Counter0, Timer/Counter1, and Timer/Counter3 prescalers” on
page 96.
Assembly code example (1)
TIM16_WriteTCNTn:
; Save global interrupt flag
in r18,SREG
; Disable interrupts
cli
; Set TCNTn to r17:r16
out TCNTnH,r17
out TCNTnL,r16
; Restore global interrupt flag
out SREG,r18
ret
C code example (1)
void TIM16_WriteTCNTn( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
__disable_interrupt();
/* Set TCNTn to i */
TCNTn = i;
/* Restore global interrupt flag */
SREG = sreg;
}121
7593L–AVR–09/12
AT90USB64/128
15.4 Counter unit
The main part of the 16-bit Timer/Counter is the programmable 16-bit bi-directional counter unit.
Figure 15-2 shows a block diagram of the counter and its surroundings.
Figure 15-2. Counter unit block diagram.
Signal description (internal signals):
Count Increment or decrement TCNTn by 1.
Direction Select between increment and decrement.
Clear Clear TCNTn (set all bits to zero).
clkTn Timer/Counter clock.
TOP Signalize that TCNTn has reached maximum value.
BOTTOM Signalize that TCNTn has reached minimum value (zero).
The 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNTnH) containing
the upper eight bits of the counter, and Counter Low (TCNTnL) containing the lower eight
bits. The TCNTnH Register can only be indirectly accessed by the CPU. When the CPU does an
access to the TCNTnH I/O location, the CPU accesses the high byte temporary register (TEMP).
The temporary register is updated with the TCNTnH value when the TCNTnL is read, and
TCNTnH is updated with the temporary register value when TCNTnL is written. This allows the
CPU to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus.
It is important to notice that there are special cases of writing to the TCNTn Register when the
counter is counting that will give unpredictable results. The special cases are described in the
sections where they are of importance.
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkTn). The clkTn can be generated from an external or internal clock source,
selected by the Clock Select bits (CSn2:0). When no clock source is selected (CSn2:0 = 0) the
timer is stopped. However, the TCNTn value can be accessed by the CPU, independent of
whether clkTn is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the Waveform Generation mode bits
(WGMn3:0) located in the Timer/Counter Control Registers A and B (TCCRnA and TCCRnB).
There are close connections between how the counter behaves (counts) and how waveforms
are generated on the Output Compare outputs OCnx. For more details about advanced counting
sequences and waveform generation, see Section “Modes of operation” on page 127.
TEMP (8-bit)
DATA BUS (8-bit)
TCNTn (16-bit counter)
TCNTnH (8-bit) TCNTnL (8-bit) Control logic
Count
Clear
Direction
TOVn
(Int.Req.)
Clock select
TOP BOTTOM
Tn Edge
detector
(From prescaler)
clkTn122
7593L–AVR–09/12
AT90USB64/128
The Timer/Counter Overflow Flag (TOVn) is set according to the mode of operation selected by
the WGMn3:0 bits. TOVn can be used for generating a CPU interrupt.
15.5 Input Capture unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give
them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple
events, can be applied via the ICPn pin or alternatively, for the Timer/Counter1 only, via the
Analog Comparator unit. The time-stamps can then be used to calculate frequency, duty-cycle,
and other features of the signal applied. Alternatively the time-stamps can be used for creating a
log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 15-3. The elements of
the block diagram that are not directly a part of the input capture unit are gray shaded. The small
“n” in register and bit names indicates the Timer/Counter number.
Figure 15-3. Input Capture Unit block diagram.
Note: The Analog Comparator Output (ACO) can only trigger the Timer/Counter1 ICP – not
Timer/Counter3, 4, or 5.
When a change of the logic level (an event) occurs on the Input Capture Pin (ICPn), alternatively
on the analog Comparator output (ACO), and this change confirms to the setting of the edge
detector, a capture will be triggered. When a capture is triggered, the 16-bit value of the counter
(TCNTn) is written to the Input Capture Register (ICRn). The Input Capture Flag (ICFn) is set at
the same system clock as the TCNTn value is copied into ICRn Register. If enabled (TICIEn =
1), the input capture flag generates an input capture interrupt. The ICFn flag is automatically
cleared when the interrupt is executed. Alternatively the ICFn flag can be cleared by software by
writing a logical one to its I/O bit location.
ICFn (int.req.)
Analog
comparator
WRITE ICRn (16-bit register)
ICRnH (8-bit)
Noise
canceler
ICPn
Edge
detector
TEMP (8-bit)
DATA BUS (8-bit)
ICRnL (8-bit)
TCNTn (16-bit counter)
TCNTnH (8-bit) TCNTnL (8-bit)
ACO* ACIC* ICNC ICES123
7593L–AVR–09/12
AT90USB64/128
Reading the 16-bit value in the Input Capture Register (ICRn) is done by first reading the low
byte (ICRnL) and then the high byte (ICRnH). When the low byte is read the high byte is copied
into the high byte Temporary Register (TEMP). When the CPU reads the ICRnH I/O location it
will access the TEMP Register.
The ICRn Register can only be written when using a Waveform Generation mode that utilizes
the ICRn Register for defining the counter’s TOP value. In these cases the Waveform Generation
mode (WGMn3:0) bits must be set before the TOP value can be written to the ICRn
Register. When writing the ICRn Register the high byte must be written to the ICRnH I/O location
before the low byte is written to ICRnL.
For more information on how to access the 16-bit registers refer to Section “Accessing 16-bit
registers” on page 117.
15.5.1 Input Capture Trigger Source
The main trigger source for the input capture unit is the Input Capture Pin (ICPn).
Timer/Counter1 can alternatively use the analog comparator output as trigger source for the
input capture unit. The Analog Comparator is selected as trigger source by setting the analog
Comparator Input Capture (ACIC) bit in the Analog Comparator Control and Status Register
(ACSR). Be aware that changing trigger source can trigger a capture. The input capture flag
must therefore be cleared after the change.
Both the Input Capture Pin (ICPn) and the Analog Comparator output (ACO) inputs are sampled
using the same technique as for the Tn pin (Figure 13-1 on page 96). The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four system clock cycles. Note that the input of the
noise canceler and edge detector is always enabled unless the Timer/Counter is set in a Waveform
Generation mode that uses ICRn to define TOP.
An input capture can be triggered by software by controlling the port of the ICPn pin.
15.5.2 Noise Canceler
The Noise Canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNCn) bit in
Timer/Counter Control Register B (TCCRnB). When enabled the noise canceler introduces additional
four system clock cycles of delay from a change applied to the input, to the update of the
ICRn Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.
15.5.3 Using the Input Capture unit
The main challenge when using the Input Capture unit is to assign enough processor capacity
for handling the incoming events. The time between two events is critical. If the processor has
not read the captured value in the ICRn Register before the next event occurs, the ICRn will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture interrupt, the ICRn Register should be read as early in the interrupt
handler routine as possible. Even though the Input Capture interrupt has relatively high
priority, the maximum interrupt response time is dependent on the maximum number of clock
cycles it takes to handle any of the other interrupt requests.124
7593L–AVR–09/12
AT90USB64/128
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is
actively changed during operation, is not recommended.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensing must be done as early as possible after the ICRn
Register has been read. After a change of the edge, the Input Capture Flag (ICFn) must be
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the clearing of the ICFn Flag is not required (if an interrupt handler is used).
15.6 Output Compare units
The 16-bit comparator continuously compares TCNTn with the Output Compare Register
(OCRnx). If TCNT equals OCRnx the comparator signals a match. A match will set the Output
Compare Flag (OCFnx) at the next timer clock cycle. If enabled (OCIEnx = 1), the Output Compare
Flag generates an Output Compare interrupt. The OCFnx Flag is automatically cleared
when the interrupt is executed. Alternatively the OCFnx Flag can be cleared by software by writing
a logical one to its I/O bit location. The Waveform Generator uses the match signal to
generate an output according to operating mode set by the Waveform Generation mode
(WGMn3:0) bits and Compare Output mode (COMnx1:0) bits. The TOP and BOTTOM signals
are used by the Waveform Generator for handling the special cases of the extreme values in
some modes of operation (see “Modes of operation” on page 127)
A special feature of Output Compare unit A allows it to define the Timer/Counter TOP value (that
is, counter resolution). In addition to the counter resolution, the TOP value defines the period
time for waveforms generated by the Waveform Generator.
Figure 15-4 shows a block diagram of the Output Compare unit. The small “n” in the register and
bit names indicates the device number (n = n for Timer/Counter n), and the “x” indicates Output
Compare unit (A/B/C). The elements of the block diagram that are not directly a part of the Output
Compare unit are gray shaded.
Figure 15-4. Output Compare Unit, block diagram.
OCFnx (int.req.)
= (16-bit comparator )
OCRnx buffer (16-bit register)
OCRnxH buf. (8-bit)
OCnx
TEMP (8-bit)
DATA BUS (8-bit)
OCRnxL buf. (8-bit)
TCNTn (16-bit counter)
TCNTnH (8-bit) TCNTnL (8-bit)
WGMn3:0 COMnx1:0
OCRnx (16-bit register)
OCRnxH (8-bit) OCRnxL (8-bit)
Waveform generator
TOP
BOTTOM125
7593L–AVR–09/12
AT90USB64/128
The OCRnx Register is double buffered when using any of the twelve Pulse Width Modulation
(PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the
double buffering is disabled. The double buffering synchronizes the update of the OCRnx Compare
Register to either TOP or BOTTOM of the counting sequence. The synchronization
prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output
glitch-free.
The OCRnx Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCRnx Buffer Register, and if double buffering is disabled
the CPU will access the OCRnx directly. The content of the OCR1x (Buffer or Compare)
Register is only changed by a write operation (the Timer/Counter does not update this register
automatically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the high byte
temporary register (TEMP). However, it is a good practice to read the low byte first as when
accessing other 16-bit registers. Writing the OCRnx Registers must be done via the TEMP Register
since the compare of all 16 bits is done continuously. The high byte (OCRnxH) has to be
written first. When the high byte I/O location is written by the CPU, the TEMP Register will be
updated by the value written. Then when the low byte (OCRnxL) is written to the lower eight bits,
the high byte will be copied into the upper 8-bits of either the OCRnx buffer or OCRnx Compare
Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to Section “Accessing 16-bit registers”
on page 117.
15.6.1 Force Output Compare
In non-PWM Waveform Generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOCnx) bit. Forcing compare match will not set the
OCFnx Flag or reload/clear the timer, but the OCnx pin will be updated as if a real compare
match had occurred (the COMn1:0 bits settings define whether the OCnx pin is set, cleared or
toggled).
15.6.2 Compare Match Blocking by TCNTn write
All CPU writes to the TCNTn Register will block any compare match that occurs in the next timer
clock cycle, even when the timer is stopped. This feature allows OCRnx to be initialized to the
same value as TCNTn without triggering an interrupt when the Timer/Counter clock is enabled.
15.6.3 Using the Output Compare unit
Since writing TCNTn in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNTn when using any of the Output Compare
channels, independent of whether the Timer/Counter is running or not. If the value written to
TCNTn equals the OCRnx value, the compare match will be missed, resulting in incorrect waveform
generation. Do not write the TCNTn equal to TOP in PWM modes with variable TOP
values. The compare match for the TOP will be ignored and the counter will continue to 0xFFFF.
Similarly, do not write the TCNTn value equal to BOTTOM when the counter is counting down.
The setup of the OCnx should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OCnx value is to use the Force Output Compare
(FOCnx) strobe bits in Normal mode. The OCnx Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COMnx1:0 bits are not double buffered together with the compare value.
Changing the COMnx1:0 bits will take effect immediately.126
7593L–AVR–09/12
AT90USB64/128
15.7 Compare Match Output unit
The Compare Output mode (COMnx1:0) bits have two functions. The Waveform Generator uses
the COMnx1:0 bits for defining the Output Compare (OCnx) state at the next compare match.
Secondly the COMnx1:0 bits control the OCnx pin output source. Figure 15-5 shows a simplified
schematic of the logic affected by the COMnx1:0 bit setting. The I/O Registers, I/O bits, and I/O
pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COMnx1:0 bits are shown. When referring to the
OCnx state, the reference is for the internal OCnx Register, not the OCnx pin. If a system reset
occur, the OCnx Register is reset to “0”.
Figure 15-5. Compare Match Output unit, schematic.
The general I/O port function is overridden by the Output Compare (OCnx) from the Waveform
Generator if either of the COMnx1:0 bits are set. However, the OCnx pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OCnx pin (DDR_OCnx) must be set as output before the OCnx value is visible
on the pin. The port override function is generally independent of the Waveform Generation
mode, but there are some exceptions. Refer to Table 15-1 on page 137, Table 15-2 on page
137, and Table 15-3 on page 138 for details.
The design of the Output Compare pin logic allows initialization of the OCnx state before the output
is enabled. Note that some COMnx1:0 bit settings are reserved for certain modes of
operation. See “16-bit Timer/Counter (Timer/Counter1 and Timer/Counter3)” on page 115.
The COMnx1:0 bits have no effect on the Input Capture unit.
15.7.1 Compare Output mode and Waveform generation
The Waveform Generator uses the COMnx1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COMnx1:0 = 0 tells the Waveform Generator that no action on the
OCnx Register is to be performed on the next compare match. For compare output actions in the
PORT
DDR
D Q
D Q
OCnx
OCnx pin
D Q Waveform
generator
COMnx1
COMnx0
0
1
DATA BUS
FOCnx
clkI/O127
7593L–AVR–09/12
AT90USB64/128
non-PWM modes refer to Table 15-1 on page 137. For fast PWM mode refer to Table 15-2 on
page 137, and for phase correct and phase and frequency correct PWM refer to Table 15-3 on
page 138.
A change of the COMnx1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOCnx strobe bits.
15.8 Modes of operation
The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins,
is defined by the combination of the Waveform Generation mode (WGMn3:0) and Compare Output
mode (COMnx1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COMnx1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COMnx1:0 bits control whether the output should be set, cleared or toggle at a compare
match (see “Compare Match Output unit” on page 126).
For detailed timing information refer to “Timer/Counter timing diagrams” on page 134.
15.8.1 Normal mode
The simplest mode of operation is the Normal mode (WGMn3:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the
BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOVn) will be set in
the same timer clock cycle as the TCNTn becomes zero. The TOVn Flag in this case behaves
like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow
interrupt that automatically clears the TOVn Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be
written anytime.
The Input Capture unit is easy to use in Normal mode. However, observe that the maximum
interval between the external events must not exceed the resolution of the counter. If the interval
between events are too long, the timer overflow interrupt or the prescaler must be used to
extend the resolution for the capture unit.
The Output Compare units can be used to generate interrupts at some given time. Using the
Output Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
15.8.2 Clear Timer on Compare Match (CTC) mode
In Clear Timer on Compare or CTC mode (WGMn3:0 = 4 or 12), the OCRnA or ICRn Register
are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when
the counter value (TCNTn) matches either the OCRnA (WGMn3:0 = 4) or the ICRn (WGMn3:0 =
12). The OCRnA or ICRn define the top value for the counter, hence also its resolution. This
mode allows greater control of the compare match output frequency. It also simplifies the operation
of counting external events.
The timing diagram for the CTC mode is shown in Figure 15-6 on page 128. The counter value
(TCNTn) increases until a compare match occurs with either OCRnA or ICRn, and then counter
(TCNTn) is cleared.128
7593L–AVR–09/12
AT90USB64/128
Figure 15-6. CTC mode, timing diagram.
An interrupt can be generated at each time the counter value reaches the TOP value by either
using the OCFnA or ICFn Flag according to the register used to define the TOP value. If the
interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However,
changing the TOP to a value close to BOTTOM when the counter is running with none or a
low prescaler value must be done with care since the CTC mode does not have the double buffering
feature. If the new value written to OCRnA or ICRn is lower than the current value of
TCNTn, the counter will miss the compare match. The counter will then have to count to its maximum
value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
In many cases this feature is not desirable. An alternative will then be to use the fast PWM mode
using OCRnA for defining TOP (WGMn3:0 = 15) since the OCRnA then will be double buffered.
For generating a waveform output in CTC mode, the OCnA output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COMnA1:0 = 1). The OCnA value will not be visible on the port pin unless the data direction for
the pin is set to output (DDR_OCnA = 1). The waveform generated will have a maximum frequency
of fOCnA = fclk_I/O/2 when OCRnA is set to zero (0x0000). The waveform frequency is
defined by the following equation:
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOVn Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x0000.
15.8.3 Fast PWM mode
The fast Pulse Width Modulation or fast PWM mode (WGMn3:0 = 5, 6, 7, 14, or 15) provides a
high frequency PWM waveform generation option. The fast PWM differs from the other PWM
options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts
from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OCnx) is set on
the compare match between TCNTn and OCRnx, and cleared at TOP. In inverting Compare
Output mode output is cleared on compare match and set at TOP. Due to the single-slope operation,
the operating frequency of the fast PWM mode can be twice as high as the phase correct
and phase and frequency correct PWM modes that use dual-slope operation. This high frequency
makes the fast PWM mode well suited for power regulation, rectification, and DAC
applications. High frequency allows physically small sized external components (coils, capacitors),
hence reduces total system cost.
TCNTn
OCnA
(Toggle)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(interrupt on TOP)
Period 1 2 3 4
(COMnA1:0 = 1)
f
OCnA
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnA = --------------------------------------------------129
7593L–AVR–09/12
AT90USB64/128
The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICRn or
OCRnA. The minimum resolution allowed is 2-bit (ICRn or OCRnA set to 0x0003), and the maximum
resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolution in bits can be
calculated by using the following equation:
In fast PWM mode the counter is incremented until the counter value matches either one of the
fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 5, 6, or 7), the value in ICRn (WGMn3:0 =
14), or the value in OCRnA (WGMn3:0 = 15). The counter is then cleared at the following timer
clock cycle. The timing diagram for the fast PWM mode is shown in Figure 15-7. The figure
shows fast PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn value is in the
timing diagram shown as a histogram for illustrating the single-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNTn
slopes represent compare matches between OCRnx and TCNTn. The OCnx Interrupt Flag will
be set when a compare match occurs.
Figure 15-7. Fast PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOVn) is set each time the counter reaches TOP. In addition
the OCnA or ICFn Flag is set at the same timer clock cycle as TOVn is set when either OCRnA
or ICRn is used for defining the TOP value. If one of the interrupts are enabled, the interrupt handler
routine can be used for updating the TOP and compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCRnx Registers are written.
The procedure for updating ICRn differs from updating OCRnA when used for defining the TOP
value. The ICRn Register is not double buffered. This means that if ICRn is changed to a low
value when the counter is running with none or a low prescaler value, there is a risk that the new
ICRn value written is lower than the current value of TCNTn. The result will then be that the
counter will miss the compare match at the TOP value. The counter will then have to count to the
MAX value (0xFFFF) and wrap around starting at 0x0000 before the compare match can occur.
The OCRnA Register however, is double buffered. This feature allows the OCRnA I/O location
RFPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
TCNTn
OCRnx / TOP Update
and TOVn Interrupt Flag
Set and OCnA Interrupt
Flag Set or ICFn
Interrupt Flag Set
(Interrupt on TOP)
Period 1 2 3 4 5 6 7 8
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)130
7593L–AVR–09/12
AT90USB64/128
to be written anytime. When the OCRnA I/O location is written the value written will be put into
the OCRnA Buffer Register. The OCRnA Compare Register will then be updated with the value
in the Buffer Register at the next timer clock cycle the TCNTn matches TOP. The update is done
at the same timer clock cycle as the TCNTn is cleared and the TOVn Flag is set.
Using the ICRn Register for defining TOP works well when using fixed TOP values. By using
ICRn, the OCRnA Register is free to be used for generating a PWM output on OCnA. However,
if the base PWM frequency is actively changed (by changing the TOP value), using the OCRnA
as TOP is clearly a better choice due to its double buffer feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OCnx pins.
Setting the COMnx1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COMnx1:0 to three (see Table on page 137). The actual OCnx
value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OCnx). The PWM waveform is generated by setting (or clearing) the OCnx Register at
the compare match between OCRnx and TCNTn, and clearing (or setting) the OCnx Register at
the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCRnx is set equal to BOTTOM (0x0000) the output
will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCRnx equal to TOP
will result in a constant high or low output (depending on the polarity of the output set by the
COMnx1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OCnA to toggle its logical level on each compare match (COMnA1:0 = 1). This applies only
if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have
a maximum frequency of fOCnA = fclk_I/O/2 when OCRnA is set to zero (0x0000). This feature is
similar to the OCnA toggle in CTC mode, except the double buffer feature of the Output Compare
unit is enabled in the fast PWM mode.
15.8.4 Phase correct PWM mode
The phase correct Pulse Width Modulation or phase correct PWM mode (WGMn3:0 = 1, 2, 3,
10, or 11) provides a high resolution phase correct PWM waveform generation option. The
phase correct PWM mode is, like the phase and frequency correct PWM mode, based on a dualslope
operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from
TOP to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OCnx) is
cleared on the compare match between TCNTn and OCRnx while upcounting, and set on the
compare match while downcounting. In inverting Output Compare mode, the operation is
inverted. The dual-slope operation has lower maximum operation frequency than single slope
operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes
are preferred for motor control applications.
The PWM resolution for the phase correct PWM mode can be fixed to 8-, 9-, or 10-bit, or defined
by either ICRn or OCRnA. The minimum resolution allowed is 2-bit (ICRn or OCRnA set to
f
OCnxPWM
f
clk_I/O
N ⋅ ( ) 1 + TOP = -----------------------------------131
7593L–AVR–09/12
AT90USB64/128
0x0003), and the maximum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolution
in bits can be calculated by using the following equation:
In phase correct PWM mode the counter is incremented until the counter value matches either
one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 1, 2, or 3), the value in ICRn
(WGMn3:0 = 10), or the value in OCRnA (WGMn3:0 = 11). The counter has then reached the
TOP and changes the count direction. The TCNTn value will be equal to TOP for one timer clock
cycle. The timing diagram for the phase correct PWM mode is shown on Figure 15-8. The figure
shows phase correct PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn
value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The
diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on
the TCNTn slopes represent compare matches between OCRnx and TCNTn. The OCnx Interrupt
Flag will be set when a compare match occurs.
Figure 15-8. Phase correct PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOVn) is set each time the counter reaches BOTTOM. When
either OCRnA or ICRn is used for defining the TOP value, the OCnA or ICFn Flag is set accordingly
at the same timer clock cycle as the OCRnx Registers are updated with the double buffer
value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the counter
reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
Note that when using fixed TOP values, the unused bits are masked to zero when any of the
OCRnx Registers are written. As the third period shown in Figure 15-8 illustrates, changing the
TOP actively while the Timer/Counter is running in the phase correct mode can result in an
unsymmetrical output. The reason for this can be found in the time of update of the OCRnx RegRPCPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
OCRnx/TOP Update and
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(interrupt on TOP)
1 2 3 4
TOVn Interrupt Flag Set
(interrupt on Bottom)
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)132
7593L–AVR–09/12
AT90USB64/128
ister. Since the OCRnx update occurs at TOP, the PWM period starts and ends at TOP. This
implies that the length of the falling slope is determined by the previous TOP value, while the
length of the rising slope is determined by the new TOP value. When these two values differ the
two slopes of the period will differ in length. The difference in length gives the unsymmetrical
result on the output.
It is recommended to use the phase and frequency correct mode instead of the phase correct
mode when changing the TOP value while the Timer/Counter is running. When using a static
TOP value there are practically no differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the
OCnx pins. Setting the COMnx1:0 bits to two will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COMnx1:0 to three (see Table 15-3 on page 138).
The actual OCnx value will only be visible on the port pin if the data direction for the port pin is
set as output (DDR_OCnx). The PWM waveform is generated by setting (or clearing) the OCnx
Register at the compare match between OCRnx and TCNTn when the counter increments, and
clearing (or setting) the OCnx Register at compare match between OCRnx and TCNTn when
the counter decrements. The PWM frequency for the output when using phase correct PWM can
be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCRnx is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If
OCR1A is used to define the TOP value (WGM13:0 = 11) and COM1A1:0 = 1, the OC1A output
will toggle with a 50% duty cycle.
15.8.5 Phase and frequency correct PWM mode
The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM
mode (WGMn3:0 = 8 or 9) provides a high resolution phase and frequency correct PWM waveform
generation option. The phase and frequency correct PWM mode is, like the phase correct
PWM mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM
(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the
Output Compare (OCnx) is cleared on the compare match between TCNTn and OCRnx while
upcounting, and set on the compare match while downcounting. In inverting Compare Output
mode, the operation is inverted. The dual-slope operation gives a lower maximum operation frequency
compared to the single-slope operation. However, due to the symmetric feature of the
dual-slope PWM modes, these modes are preferred for motor control applications.
The main difference between the phase correct, and the phase and frequency correct PWM
mode is the time the OCRnx Register is updated by the OCRnx Buffer Register, (see Figure 15-
8 on page 131 and Figure 15-9 on page 133).
The PWM resolution for the phase and frequency correct PWM mode can be defined by either
ICRn or OCRnA. The minimum resolution allowed is 2-bit (ICRn or OCRnA set to 0x0003), and
f
OCnxPCPWM
f
clk_I/O
2 ⋅ ⋅ N TOP = ----------------------------133
7593L–AVR–09/12
AT90USB64/128
the maximum resolution is 16-bit (ICRn or OCRnA set to MAX). The PWM resolution in bits can
be calculated using the following equation:
In phase and frequency correct PWM mode the counter is incremented until the counter value
matches either the value in ICRn (WGMn3:0 = 8), or the value in OCRnA (WGMn3:0 = 9). The
counter has then reached the TOP and changes the count direction. The TCNTn value will be
equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency
correct PWM mode is shown on Figure 15-9. The figure shows phase and frequency correct
PWM mode when OCRnA or ICRn is used to define TOP. The TCNTn value is in the timing diagram
shown as a histogram for illustrating the dual-slope operation. The diagram includes noninverted
and inverted PWM outputs. The small horizontal line marks on the TCNTn slopes represent
compare matches between OCRnx and TCNTn. The OCnx Interrupt Flag will be set when a
compare match occurs.
Figure 15-9. Phase and frequency correct PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOVn) is set at the same timer clock cycle as the OCRnx
Registers are updated with the double buffer value (at BOTTOM). When either OCRnA or ICRn
is used for defining the TOP value, the OCnA or ICFn Flag set when TCNTn has reached TOP.
The Interrupt Flags can then be used to generate an interrupt each time the counter reaches the
TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNTn and the OCRnx.
As Figure 15-9 shows the output generated is, in contrast to the phase correct mode, symmetrical
in all periods. Since the OCRnx Registers are updated at BOTTOM, the length of the rising
and the falling slopes will always be equal. This gives symmetrical output pulses and is therefore
frequency correct.
RPFCPWM
log( ) TOP + 1
log( ) 2 = -----------------------------------
OCRnx/TOP Updateand
TOVn Interrupt Flag Set
(interrupt on Bottom)
OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(interrupt on TOP)
1 2 3 4
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)134
7593L–AVR–09/12
AT90USB64/128
Using the ICRn Register for defining TOP works well when using fixed TOP values. By using
ICRn, the OCRnA Register is free to be used for generating a PWM output on OCnA. However,
if the base PWM frequency is actively changed by changing the TOP value, using the OCRnA as
TOP is clearly a better choice due to its double buffer feature.
In phase and frequency correct PWM mode, the compare units allow generation of PWM waveforms
on the OCnx pins. Setting the COMnx1:0 bits to two will produce a non-inverted PWM and
an inverted PWM output can be generated by setting the COMnx1:0 to three (see Table 15-3 on
page 138). The actual OCnx value will only be visible on the port pin if the data direction for the
port pin is set as output (DDR_OCnx). The PWM waveform is generated by setting (or clearing)
the OCnx Register at the compare match between OCRnx and TCNTn when the counter increments,
and clearing (or setting) the OCnx Register at compare match between OCRnx and
TCNTn when the counter decrements. The PWM frequency for the output when using phase
and frequency correct PWM can be calculated by the following equation:
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCRnx Register represents special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCRnx is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be set to high for noninverted
PWM mode. For inverted PWM the output will have the opposite logic values. If OCR1A
is used to define the TOP value (WGM13:0 = 9) and COM1A1:0 = 1, the OC1A output will toggle
with a 50% duty cycle.
15.9 Timer/Counter timing diagrams
The Timer/Counter is a synchronous design and the timer clock (clkTn) is therefore shown as a
clock enable signal in the following figures. The figures include information on when Interrupt
Flags are set, and when the OCRnx Register is updated with the OCRnx buffer value (only for
modes utilizing double buffering). Figure 15-10 shows a timing diagram for the setting of OCFnx.
Figure 15-10. Timer/Counter timing diagram, setting of OCFnx, no prescaling.
Figure 15-11 on page 135 shows the same timing data, but with the prescaler enabled.
f
OCnxPFCPWM
f
clk_I/O
2 ⋅ ⋅ N TOP = ----------------------------
clkTn
(clkI/O/1)
OCFnx
clkI/O
OCRnx
TCNTn
OCRnx value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2135
7593L–AVR–09/12
AT90USB64/128
Figure 15-11. Timer/Counter timing diagram, setting of OCFnx, with prescaler (fclk_I/O/8).
Figure 15-12 shows the count sequence close to TOP in various modes. When using phase and
frequency correct PWM mode the OCRnx Register is updated at BOTTOM. The timing diagrams
will be the same, but TOP should be replaced by BOTTOM, TOP-1 by BOTTOM+1 and so on.
The same renaming applies for modes that set the TOVn Flag at BOTTOM.
Figure 15-12. Timer/Counter timing diagram, no prescaling.
Figure 15-13 on page 136 shows the same timing data, but with the prescaler enabled.
OCFnx
OCRnx
TCNTn
OCRnx value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM) TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx value New OCRnx value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkTn
(clkI/O/1)
clkI/O136
7593L–AVR–09/12
AT90USB64/128
Figure 15-13. Timer/Counter timing diagram, with prescaler (fclk_I/O/8).
15.10 16-bit Timer/Counter register description
15.10.1 TCCR1A – Timer/Counter1 Control Register A
15.10.2 TCCR3A – Timer/Counter3 Control Register A
• Bit 7:6 – COMnA1:0: Compare Output Mode for Channel A
• Bit 5:4 – COMnB1:0: Compare Output Mode for Channel B
• Bit 3:2 – COMnC1:0: Compare Output Mode for Channel C
The COMnA1:0, COMnB1:0, and COMnC1:0 control the output compare pins (OCnA, OCnB,
and OCnC respectively) behavior. If one or both of the COMnA1:0 bits are written to one, the
OCnA output overrides the normal port functionality of the I/O pin it is connected to. If one or
both of the COMnB1:0 bits are written to one, the OCnB output overrides the normal port functionality
of the I/O pin it is connected to. If one or both of the COMnC1:0 bits are written to one,
the OCnC output overrides the normal port functionality of the I/O pin it is connected to. However,
note that the Data Direction Register (DDR) bit corresponding to the OCnA, OCnB or
OCnC pin must be set in order to enable the output driver.
TOVn (FPWM)
and ICFn (if used
as TOP)
OCRnx
(update at TOP)
TCNTn
(CTC and FPWM)
TCNTn
(PC and PFC PWM)
TOP - 1 TOP TOP - 1 TOP - 2
Old OCRnx value New OCRnx value
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clk Tn
(clkI/O /8)
Bit 7 6 5 4 3 2 1 0
COM1A1 COM1A0 COM1B1 COM1B0 COM1C1 COM1C0 WGM11 WGM10 TCCR1A
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
COM3A1 COM3A0 COM3B1 COM3B0 COM3C1 COM3C0 WGM31 WGM30 TCCR3A
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0137
7593L–AVR–09/12
AT90USB64/128
When the OCnA, OCnB or OCnC is connected to the pin, the function of the COMnx1:0 bits is
dependent of the WGMn3:0 bits setting. Table 15-1 shows the COMnx1:0 bit functionality when
the WGMn3:0 bits are set to a normal or a CTC mode (non-PWM).
Table 15-2 shows the COMnx1:0 bit functionality when the WGMn3:0 bits are set to the fast
PWM mode.
Note: A special case occurs when OCRnA/OCRnB/OCRnC equals TOP and
COMnA1/COMnB1/COMnC1 is set. In this case the compare match is ignored, but the set or clear
is done at TOP. See “Fast PWM mode” on page 104. for more details.
Table 15-3 on page 138 shows the COMnx1:0 bit functionality when the WGMn3:0 bits are set to
the phase correct and frequency correct PWM mode.
Table 15-1. Compare Output mode, non-PWM.
COMnA1/COMnB1/
COMnC1
COMnA0/COMnB0/
COMnC0 Description
0 0 Normal port operation, OCnA/OCnB/OCnC
disconnected.
0 1 Toggle OCnA/OCnB/OCnC on compare match.
1 0 Clear OCnA/OCnB/OCnC on compare match (set
output to low level).
1 1 Set OCnA/OCnB/OCnC on compare match (set
output to high level).
Table 15-2. Compare Output mode, fast PWM.
COMnA1/COMnB1/
COMnC0
COMnA0/COMnB0/
COMnC0 Description
0 0 Normal port operation, OCnA/OCnB/OCnC
disconnected.
0 1
WGM13:0 = 14 or 15: Toggle OC1A on Compare
Match, OC1B and OC1C disconnected (normal port
operation). For all other WGM1 settings, normal port
operation, OC1A/OC1B/OC1C disconnected.
1 0 Clear OCnA/OCnB/OCnC on compare match, set
OCnA/OCnB/OCnC at TOP
1 1 Set OCnA/OCnB/OCnC on compare match, clear
OCnA/OCnB/OCnC at TOP138
7593L–AVR–09/12
AT90USB64/128
Note: A special case occurs when OCRnA/OCRnB/OCRnC equals TOP and
COMnA1/COMnB1//COMnC1 is set. See “Phase correct PWM mode” on page 106. for more
details.
• Bit 1:0 – WGMn1:0: Waveform Generation mode
Combined with the WGMn3:2 bits found in the TCCRnB Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 15-4 on page 138. Modes of operation supported by the
Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare match (CTC) mode,
and three types of Pulse Width Modulation (PWM) modes. (See “Modes of operation” on page
103.).
Table 15-3. Compare Output mode, phase correct and phase and frequency correct PWM.
COMnA1/COMnB/
COMnC1
COMnA0/COMnB0/
COMnC0 Description
0 0 Normal port operation, OCnA/OCnB/OCnC
disconnected.
0 1
WGM13:0 = 8, 9 10 or 11: Toggle OC1A on
Compare Match, OC1B and OC1C
disconnected (normal port operation). For all
other WGM1 settings, normal port operation,
OC1A/OC1B/OC1C disconnected.
1 0
Clear OCnA/OCnB/OCnC on compare
match when up-counting. Set
OCnA/OCnB/OCnC on compare match
when counting down.
1 1
Set OCnA/OCnB/OCnC on compare match
when up-counting. Clear
OCnA/OCnB/OCnC on compare match
when counting down.
Table 15-4. Waveform Generation mode bit description (1).
Mode WGMn3
WGMn2
(CTCn)
WGMn1
(PWMn1)
WGMn0
(PWMn0)
Timer/Counter mode of
operation TOP
Update of
OCRnx at
TOVn flag
set on
0 0 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, phase correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, phase correct, 9-bit 0x01FF TOP BOTTOM
3 0 0 1 1 PWM, phase correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCRnA Immediate MAX
5 0 1 0 1 Fast PWM, 8-bit 0x00FF TOP TOP
6 0 1 1 0 Fast PWM, 9-bit 0x01FF TOP TOP
7 0 1 1 1 Fast PWM, 10-bit 0x03FF TOP TOP
81 0 0 0 PWM, phase and frequency
Correct ICRn BOTTOM BOTTOM
91 0 0 1 PWM, phase and frequency
Correct OCRnA BOTTOM BOTTOM
10 1 0 1 0 PWM, phase correct ICRn TOP BOTTOM139
7593L–AVR–09/12
AT90USB64/128
Note: 1. The CTCn and PWMn1:0 bit definition names are obsolete. Use the WGMn2:0 definitions. However, the functionality and
location of these bits are compatible with previous versions of the timer.
15.10.3 TCCR1B – Timer/Counter1 Control Register B
15.10.4 TCCR3B – Timer/Counter3 Control Register B
• Bit 7 – ICNCn: Input Capture Noise Canceler
Setting this bit (to one) activates the Input Capture Noise Canceler. When the Noise Canceler is
activated, the input from the Input Capture Pin (ICPn) is filtered. The filter function requires four
successive equal valued samples of the ICPn pin for changing its output. The input capture is
therefore delayed by four Oscillator cycles when the noise canceler is enabled.
• Bit 6 – ICESn: Input Capture Edge Select
This bit selects which edge on the Input Capture Pin (ICPn) that is used to trigger a capture
event. When the ICESn bit is written to zero, a falling (negative) edge is used as trigger, and
when the ICESn bit is written to one, a rising (positive) edge will trigger the capture.
When a capture is triggered according to the ICESn setting, the counter value is copied into the
Input Capture Register (ICRn). The event will also set the Input Capture Flag (ICFn), and this
can be used to cause an Input Capture Interrupt, if this interrupt is enabled.
When the ICRn is used as TOP value (see description of the WGMn3:0 bits located in the
TCCRnA and the TCCRnB Register), the ICPn is disconnected and consequently the input capture
function is disabled.
• Bit 5 – Reserved bit
This bit is reserved for future use. For ensuring compatibility with future devices, this bit must be
written to zero when TCCRnB is written.
• Bit 4:3 – WGMn3:2: Waveform Generation mode
See TCCRnA Register description.
11 1 0 1 1 PWM, phase correct OCRnA TOP BOTTOM
12 1 1 0 0 CTC ICRn Immediate MAX
13 1 1 0 1 (Reserved) – – –
14 1 1 1 0 Fast PWM ICRn TOP TOP
15 1 1 1 1 Fast PWM OCRnA TOP TOP
Table 15-4. Waveform Generation mode bit description (1). (Continued)
Mode WGMn3
WGMn2
(CTCn)
WGMn1
(PWMn1)
WGMn0
(PWMn0)
Timer/Counter mode of
operation TOP
Update of
OCRnx at
TOVn flag
set on
Bit 7 6 5 4 3 2 1 0
ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 TCCR1B
Read/write R/W R/W R R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
ICNC3 ICES3 – WGM33 WGM32 CS32 CS31 CS30 TCCR3B
Read/write R/W R/W R R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0140
7593L–AVR–09/12
AT90USB64/128
• Bit 2:0 – CSn2:0: Clock Select
The three clock select bits select the clock source to be used by the Timer/Counter, see Figure
14-8 on page 107 and Figure 14-9 on page 108.
If external pin modes are used for the Timer/Countern, transitions on the Tn pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
15.10.5 TCCR1C – Timer/Counter1 Control Register C
15.10.6 TCCR3C – Timer/Counter3 Control Register C
• Bit 7 – FOCnA: Force Output Compare for Channel A
• Bit 6 – FOCnB: Force Output Compare for Channel B
• Bit 5 – FOCnC: Force Output Compare for Channel C
The FOCnA/FOCnB/FOCnC bits are only active when the WGMn3:0 bits specifies a non-PWM
mode. When writing a logical one to the FOCnA/FOCnB/FOCnC bit, an immediate compare
match is forced on the waveform generation unit. The OCnA/OCnB/OCnC output is changed
according to its COMnx1:0 bits setting. Note that the FOCnA/FOCnB/FOCnC bits are implemented
as strobes. Therefore it is the value present in the COMnx1:0 bits that determine the
effect of the forced compare.
A FOCnA/FOCnB/FOCnC strobe will not generate any interrupt nor will it clear the timer in Clear
Timer on Compare Match (CTC) mode using OCRnA as TOP.
The FOCnA/FOCnB/FOCnB bits are always read as zero.
• Bit 4:0 – Reserved bits
These bits are reserved for future use. For ensuring compatibility with future devices, these bits
must be written to zero when TCCRnC is written.
Table 15-5. Clock Select bit description.
CSn2 CSn1 CSn0 Description
0 0 0 No clock source. (Timer/Counter stopped)
0 0 1 clkI/O/1 (no prescaling
0 1 0 clkI/O/8 (from prescaler)
0 1 1 clkI/O/64 (from prescaler)
1 0 0 clkI/O/256 (from prescaler)
1 0 1 clkI/O/1024 (from prescaler)
1 1 0 External clock source on Tn pin. Clock on falling edge
1 1 1 External clock source on Tn pin. Clock on rising edge
Bit 7 6 5 4 3 2 1 0
FOC1A FOC1B FOC1C – – – – – TCCR1C
Read/write W W W R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
FOC3A FOC3B FOC3C – – – – – TCCR3C
Read/write W W W R R R R R
Initial value 0 0 0 0 0 0 0 0141
7593L–AVR–09/12
AT90USB64/128
15.10.7 TCNT1H and TCNT1L – Timer/Counter1
15.10.8 TCNT3H and TCNT3L – Timer/Counter3
The two Timer/Counter I/O locations (TCNTnH and TCNTnL, combined TCNTn) give direct
access, both for read and for write operations, to the Timer/Counter unit 16-bit counter. To
ensure that both the high and low bytes are read and written simultaneously when the CPU
accesses these registers, the access is performed using an 8-bit temporary High Byte Register
(TEMP). This temporary register is shared by all the other 16-bit registers. See “Accessing 16-bit
registers” on page 117.
Modifying the counter (TCNTn) while the counter is running introduces a risk of missing a compare
match between TCNTn and one of the OCRnx Registers.
Writing to the TCNTn Register blocks (removes) the compare match on the following timer clock
for all compare units.
15.10.9 OCR1AH and OCR1AL – Output Compare Register 1 A
15.10.10 OCR1BH and OCR1BL – Output Compare Register 1 B
15.10.11 OCR1CH and OCR1CL – Output Compare Register 1 C
Bit 7 6 5 4 3 2 1 0
TCNT1[15:8] TCNT1H
TCNT1[7:0] TCNT1L
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
TCNT3[15:8] TCNT3H
TCNT3[7:0] TCNT3L
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1A[15:8] OCR1AH
OCR1A[7:0] OCR1AL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1B[15:8] OCR1BH
OCR1B[7:0] OCR1BL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR1C[15:8] OCR1CH
OCR1C[7:0] OCR1CL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0142
7593L–AVR–09/12
AT90USB64/128
15.10.12 OCR3AH and OCR3AL – Output Compare Register 3 A
15.10.13 OCR3BH and OCR3BL – Output Compare Register 3 B
15.10.14 OCR3CH and OCR3CL – Output Compare Register 3 C
The Output Compare Registers contain a 16-bit value that is continuously compared with the
counter value (TCNTn). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OCnx pin.
The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are
written simultaneously when the CPU writes to these registers, the access is performed using an
8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other
16-bit registers. See “Accessing 16-bit registers” on page 117.
15.10.15 ICR1H and ICR1L – Input Capture Register 1
15.10.16 ICR3H and ICR3L – Input Capture Register 3
The Input Capture is updated with the counter (TCNTn) value each time an event occurs on the
ICPn pin (or optionally on the Analog Comparator output for Timer/Counter1). The Input Capture
can be used for defining the counter TOP value.
The Input Capture Register is 16-bit in size. To ensure that both the high and low bytes are read
simultaneously when the CPU accesses these registers, the access is performed using an 8-bit
temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit
registers. See “Accessing 16-bit registers” on page 117.
Bit 7 6 5 4 3 2 1 0
OCR3A[15:8] OCR3AH
OCR3A[7:0] OCR3AL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR3B[15:8] OCR3BH
OCR3B[7:0] OCR3BL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR3C[15:8] OCR3CH
OCR3C[7:0] OCR3CL
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
ICR1[15:8] ICR1H
ICR1[7:0] ICR1L
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
ICR3[15:8] ICR3H
ICR3[7:0] ICR3L
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0143
7593L–AVR–09/12
AT90USB64/128
15.10.17 TIMSK1 – Timer/Counter1 Interrupt Mask Register
15.10.18 TIMSK3 – Timer/Counter3 Interrupt Mask Register
• Bit 5 – ICIEn: Timer/Countern, Input Capture Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Countern Input Capture interrupt is enabled. The corresponding Interrupt
Vector (see “Interrupts” on page 68) is executed when the ICFn Flag, located in TIFRn, is set.
• Bit 3 – OCIEnC: Timer/Countern, Output Compare C Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Countern Output Compare C Match interrupt is enabled. The corresponding
Interrupt Vector (see “Interrupts” on page 68) is executed when the OCFnC Flag, located in
TIFRn, is set.
• Bit 2 – OCIEnB: Timer/Countern, Output Compare B Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Countern Output Compare B Match interrupt is enabled. The corresponding
Interrupt Vector (see “Interrupts” on page 68) is executed when the OCFnB Flag, located in
TIFRn, is set.
• Bit 1 – OCIEnA: Timer/Countern, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Countern Output Compare A Match interrupt is enabled. The corresponding
Interrupt Vector (see “Interrupts” on page 68) is executed when the OCFnA Flag, located in
TIFRn, is set.
• Bit 0 – TOIEn: Timer/Countern, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally
enabled), the Timer/Countern Overflow interrupt is enabled. The corresponding Interrupt Vector
(see “Interrupts” on page 68) is executed when the TOVn Flag, located in TIFRn, is set.
15.10.19 TIFR1 – Timer/Counter1 Interrupt Flag Register
15.10.20 TIFR3 – Timer/Counter3 Interrupt Flag Register
Bit 7 6 5 4 3 2 1 0
– – ICIE1 – OCIE1C OCIE1B OCIE1A TOIE1 TIMSK1
Read/write R R R/W R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – ICIE3 – OCIE3C OCIE3B OCIE3A TOIE3 TIMSK3
Read/write R R R/W R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – ICF1 – OCF1C OCF1B OCF1A TOV1 TIFR1
Read/write R R R/W R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
– – ICF3 – OCF3C OCF3B OCF3A TOV3 TIFR3
Read/write R R R/W R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0144
7593L–AVR–09/12
AT90USB64/128
• Bit 5 – ICFn: Timer/Countern, Input Capture Flag
This flag is set when a capture event occurs on the ICPn pin. When the Input Capture Register
(ICRn) is set by the WGMn3:0 to be used as the TOP value, the ICFn Flag is set when the counter
reaches the TOP value.
ICFn is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively,
ICFn can be cleared by writing a logic one to its bit location.
• Bit 3– OCFnC: Timer/Countern, Output Compare C Match Flag
This flag is set in the timer clock cycle after the counter (TCNTn) value matches the Output
Compare Register C (OCRnC).
Note that a Forced Output Compare (FOCnC) strobe will not set the OCFnC Flag.
OCFnC is automatically cleared when the Output Compare Match C Interrupt Vector is executed.
Alternatively, OCFnC can be cleared by writing a logic one to its bit location.
• Bit 2 – OCFnB: Timer/Counter1, Output Compare B Match Flag
This flag is set in the timer clock cycle after the counter (TCNTn) value matches the Output
Compare Register B (OCRnB).
Note that a Forced Output Compare (FOCnB) strobe will not set the OCFnB Flag.
OCFnB is automatically cleared when the Output Compare Match B Interrupt Vector is executed.
Alternatively, OCFnB can be cleared by writing a logic one to its bit location.
• Bit 1 – OCF1A: Timer/Counter1, Output Compare A Match Flag
This flag is set in the timer clock cycle after the counter (TCNTn value matches the Output Compare
Register A (OCRnA).
Note that a Forced Output Compare (FOCnA) strobe will not set the OCFnA Flag.
OCFnA is automatically cleared when the Output Compare Match A Interrupt Vector is executed.
Alternatively, OCFnA can be cleared by writing a logic one to its bit location.
• Bit 0 – TOVn: Timer/Countern, Overflow Flag
The setting of this flag is dependent of the WGMn3:0 bits setting. In Normal and CTC modes,
the TOVn Flag is set when the timer overflows. Refer to Table 15-4 on page 138 for the TOVn
Flag behavior when using another WGMn3:0 bit setting.
TOVn is automatically cleared when the Timer/Countern Overflow Interrupt Vector is executed.
Alternatively, TOVn can be cleared by writing a logic one to its bit location.145
7593L–AVR–09/12
AT90USB64/128
16. 8-bit Timer/Counter2 with PWM and asynchronous operation
Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. The main
features are:
• Single channel counter
• Clear timer on compare match (auto reload)
• Glitch-free, phase correct pulse width modulator (PWM)
• Frequency generator
• 10-bit clock prescaler
• Overflow and compare match interrupt sources (TOV2, OCF2A and OCF2B)
• Allows clocking from external 32kHz watch crystal independent of the I/O clock
16.1 Overview
A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 16-1. For the actual
placement of I/O pins, see “Pin configurations” on page 3. CPU accessible I/O Registers, including
I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations
are listed in the “8-bit Timer/Counter register description” on page 156.
The Power Reduction Timer/Counter2 bit, PRTIM2, in “PRR0 – Power Reduction Register 0” on
page 54 must be written to zero to enable Timer/Counter2 module.
Figure 16-1. 8-bit Timer/Counter, block diagram.
Timer/counter
DATA BUS
OCRnA
OCRnB
=
=
TCNTn
Waveform
generation
Waveform
generation
OCnA
OCnB
=
Fixed
TOP
value
Control logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(int.req.)
OCnA
(int.req.)
OCnB
(int.req.)
TCCRnA TCCRnB
clkTn
ASSRn
Synchronization unit
Prescaler
T/C oscillator
clkI/O
clkASY
asynchronous mode
select (ASn)
Synchronized status flags
TOSC1
TOSC2
Status flags
clkI/O146
7593L–AVR–09/12
AT90USB64/128
16.1.1 Registers
The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit registers.
Interrupt request (abbreviated to Int.Req.) signals are all visible in the Timer Interrupt Flag
Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register
(TIMSK2). TIFR2 and TIMSK2 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from
the TOSC1/2 pins, as detailed later in this section. The asynchronous operation is controlled by
the Asynchronous Status Register (ASSR). The Clock Select logic block controls which clock
source the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive
when no clock source is selected. The output from the Clock Select logic is referred to as the
timer clock (clkT2).
The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the
Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator
to generate a PWM or variable frequency output on the Output Compare pins (OC2A and
OC2B). See “Output Compare unit” on page 147. for details. The compare match event will also
set the Compare Flag (OCF2A or OCF2B) which can be used to generate an Output Compare
interrupt request.
16.1.2 Definitions
Many register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 2. However, when using the register or bit
defines in a program, the precise form must be used, that is, TCNT2 for accessing
Timer/Counter2 counter value and so on.
The definitions in the table below are also used extensively throughout the section.
16.2 Timer/Counter clock sources
The Timer/Counter can be clocked by an internal synchronous or an external asynchronous
clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2
bit in the ASSR Register is written to logic one, the clock source is taken from the Timer/Counter
Oscillator connected to TOSC1 and TOSC2. For details on asynchronous operation, see “ASSR
– Asynchronous Status Register” on page 161. For details on clock sources and prescaler, see
“Timer/Counter prescaler” on page 164.
16.3 Counter unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
16-2 on page 147 shows a block diagram of the counter and its surrounding environment.
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00).
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR2A Register. The assignment is dependent
on the mode of operation.147
7593L–AVR–09/12
AT90USB64/128
Figure 16-2. Counter unit block diagram.
Signal description (internal signals):
count Increment or decrement TCNT2 by 1.
direction Selects between increment and decrement.
clear Clear TCNT2 (set all bits to zero).
clkTn Timer/Counter clock, referred to as clkT2 in the following.
top Signalizes that TCNT2 has reached maximum value.
bottom Signalizes that TCNT2 has reached minimum value (zero).
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source,
selected by the Clock Select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the
timer is stopped. However, the TCNT2 value can be accessed by the CPU, regardless of
whether clkT2 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in
the Timer/Counter Control Register (TCCR2A) and the WGM22 located in the Timer/Counter
Control Register B (TCCR2B). There are close connections between how the counter behaves
(counts) and how waveforms are generated on the Output Compare outputs OC2A and OC2B.
For more details about advanced counting sequences and waveform generation, see “Modes of
operation” on page 150.
The Timer/Counter Overflow Flag (TOV2) is set according to the mode of operation selected by
the WGM22:0 bits. TOV2 can be used for generating a CPU interrupt.
16.4 Output Compare unit
The 8-bit comparator continuously compares TCNT2 with the Output Compare Register
(OCR2A and OCR2B). Whenever TCNT2 equals OCR2A or OCR2B, the comparator signals a
match. A match will set the Output Compare Flag (OCF2A or OCF2B) at the next timer clock
cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output
Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed.
Alternatively, the Output Compare Flag can be cleared by software by writing a logical
one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
according to operating mode set by the WGM22:0 bits and Compare Output mode (COM2x1:0)
bits. The max and bottom signals are used by the Waveform Generator for handling the special
cases of the extreme values in some modes of operation (“Modes of operation” on page 150).
Figure 15-10 on page 134 shows a block diagram of the Output Compare unit.
DATA BUS
TCNTn Control logic
count
TOVn
(int.req.)
bottom top
direction
clear
TOSC1
T/C
oscillator
TOSC2
Prescaler
clkI/O
clk Tn148
7593L–AVR–09/12
AT90USB64/128
Figure 16-3. Output Compare unit, block diagram.
The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM)
modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double
buffering is disabled. The double buffering synchronizes the update of the OCR2x Compare
Register to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR2x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR2x Buffer Register, and if double buffering is disabled
the CPU will access the OCR2x directly.
16.4.1 Force output compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC2x) bit. Forcing compare match will not set the
OCF2x Flag or reload/clear the timer, but the OC2x pin will be updated as if a real compare
match had occurred (the COM2x1:0 bits settings define whether the OC2x pin is set, cleared or
toggled).
16.4.2 Compare Match Blocking by TCNT2 Write
All CPU write operations to the TCNT2 Register will block any compare match that occurs in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR2x to be initialized
to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is
enabled.
16.4.3 Using the Output Compare unit
Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT2 when using the Output Compare channel,
independently of whether the Timer/Counter is running or not. If the value written to TCNT2
equals the OCR2x value, the compare match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is
downcounting.
OCFnx (int.req.)
= (8-bit comparator)
OCRnx
OCnx
DATA BUS
TCNTn
WGMn1:0
Waveform generator
top
FOCn
COMnX1:0
bottom149
7593L–AVR–09/12
AT90USB64/128
The setup of the OC2x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC2x value is to use the Force Output Compare
(FOC2x) strobe bit in Normal mode. The OC2x Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COM2x1:0 bits are not double buffered together with the compare value.
Changing the COM2x1:0 bits will take effect immediately.
16.5 Compare Match Output unit
The Compare Output mode (COM2x1:0) bits have two functions. The Waveform Generator uses
the COM2x1:0 bits for defining the Output Compare (OC2x) state at the next compare match.
Also, the COM2x1:0 bits control the OC2x pin output source. Figure 16-4 shows a simplified
schematic of the logic affected by the COM2x1:0 bit setting. The I/O Registers, I/O bits, and I/O
pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COM2x1:0 bits are shown. When referring to the
OC2x state, the reference is for the internal OC2x Register, not the OC2x pin.
Figure 16-4. Compare Match Output unit, schematic.
The general I/O port function is overridden by the Output Compare (OC2x) from the Waveform
Generator if either of the COM2x1:0 bits are set. However, the OC2x pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC2x pin (DDR_OC2x) must be set as output before the OC2x value is visible
on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC2x state before the output
is enabled. Note that some COM2x1:0 bit settings are reserved for certain modes of
operation. See “8-bit Timer/Counter register description” on page 156.
PORT
DDR
D Q
D Q
OCnx
OCnx pin
D Q Waveform
generator
COMnx1
COMnx0
0
1
DATA BU
S
FOCnx
clkI/O150
7593L–AVR–09/12
AT90USB64/128
16.5.1 Compare Output mode and Waveform generating
The Waveform Generator uses the COM2x1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM2x1:0 = 0 tells the Waveform Generator that no action on the
OC2x Register is to be performed on the next compare match. For compare output actions in the
non-PWM modes refer to Table 16-4 on page 157. For fast PWM mode, refer to Table 16-5 on
page 158, and for phase correct PWM refer to Table 16-6 on page 158.
A change of the COM2x1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC2x strobe bits.
16.6 Modes of operation
The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins,
is defined by the combination of the Waveform Generation mode (WGM22:0) and Compare Output
mode (COM2x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM2x1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM2x1:0 bits control whether the output should be set, cleared, or toggled at a compare
match (see “Compare Match Output unit” on page 149).
For detailed timing information refer to Section “Timer/Counter timing diagrams” on page 154.
16.6.1 Normal mode
The simplest mode of operation is the Normal mode (WGM22:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same
timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV2 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare unit can be used to generate interrupts at some given time. Using the Output
Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
16.6.2 Clear Timer on Compare Match (CTC) mode
In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to
manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter
value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence
also its resolution. This mode allows greater control of the compare match output frequency. It
also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Table 16-5 on page 151. The counter value
(TCNT2) increases until a compare match occurs between TCNT2 and OCR2A, and then counter
(TCNT2) is cleared.151
7593L–AVR–09/12
AT90USB64/128
Figure 16-5. CTC mode, timing diagram.
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running
with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR2A is lower than the current
value of TCNT2, the counter will miss the compare match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can
occur.
For generating a waveform output in CTC mode, the OC2A output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COM2A1:0 = 1). The OC2A value will not be visible on the port pin unless the data direction for
the pin is set to output. The waveform generated will have a maximum frequency of fOC2A =
fclk_I/O/2 when OCR2A is set to zero (0x00). The waveform frequency is defined by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
As for the Normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
16.6.3 Fast PWM mode
The fast Pulse Width Modulation or fast PWM mode (WGM22:0 = 3 or 7) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by
its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM.
TOP is defined as 0xFF when WGM22:0 = 3, and OCR2A when MGM22:0 = 7. In noninverting
Compare Output mode, the Output Compare (OC2x) is cleared on the compare match
between TCNT2 and OCR2x, and set at BOTTOM. In inverting Compare Output mode, the output
is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that uses dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
TCNTn
OCnx
(Toggle)
OCnx Interrupt Flag Set
Period 1 2 3 4
(COMnx1:0 = 1)
f
OCnx
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnx = -------------------------------------------------152
7593L–AVR–09/12
AT90USB64/128
In fast PWM mode, the counter is incremented until the counter value matches the TOP value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
PWM mode is shown in Figure 16-6. The TCNT2 value is in the timing diagram shown as a histogram
for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare
matches between OCR2x and TCNT2.
Figure 16-6. Fast PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches TOP. If the interrupt
is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin.
Setting the COM2x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when WGM2:0 = 3,
and OCR2A when WGM2:0 = 7 (See Table 16-2 on page 157). The actual OC2x value will only
be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform
is generated by setting (or clearing) the OC2x Register at the compare match between
OCR2x and TCNT2, and clearing (or setting) the OC2x Register at the timer clock cycle the
counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR2A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR2A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM2A1:0
bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC2x to toggle its logical level on each compare match (COM2x1:0 = 1). The waveform
TCNTn
OCRnx Update and
TOVn Interrupt Flag Set
Period 1 2 3
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx Interrupt Flag Set
4 5 6 7
f
OCnxPWM
f
clk_I/O
N ⋅ 256 = ------------------153
7593L–AVR–09/12
AT90USB64/128
generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2A is set to zero. This feature
is similar to the OC2A toggle in CTC mode, except the double buffer feature of the Output
Compare unit is enabled in the fast PWM mode.
16.6.4 Phase correct PWM mode
The phase correct PWM mode (WGM22:0 = 1 or 5) provides a high resolution phase correct
PWM waveform generation option. The phase correct PWM mode is based on a dual-slope
operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM.
TOP is defined as 0xFF when WGM22:0 = 1, and OCR2A when MGM22:0 = 5. In noninverting
Compare Output mode, the Output Compare (OC2x) is cleared on the compare match
between TCNT2 and OCR2x while upcounting, and set on the compare match while downcounting.
In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
In phase correct PWM mode the counter is incremented until the counter value matches TOP.
When the counter reaches TOP, it changes the count direction. The TCNT2 value will be equal
to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown
on Figure 16-7. The TCNT2 value is in the timing diagram shown as a histogram for illustrating
the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The
small horizontal line marks on the TCNT2 slopes represent compare matches between OCR2x
and TCNT2.
Figure 16-7. Phase correct PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC2x pin. Setting the COM2x1:0 bits to two will produce a non-inverted PWM. An inverted PWM
TOVn Interrupt Flag Set
OCnx Interrupt Flag Set
1 2 3
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx update154
7593L–AVR–09/12
AT90USB64/128
output can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when
WGM2:0 = 3, and OCR2A when MGM2:0 = 7 (see Table 16-3 on page 157). The actual OC2x
value will only be visible on the port pin if the data direction for the port pin is set as output. The
PWM waveform is generated by clearing (or setting) the OC2x Register at the compare match
between OCR2x and TCNT2 when the counter increments, and setting (or clearing) the OC2x
Register at compare match between OCR2x and TCNT2 when the counter decrements. The
PWM frequency for the output when using phase correct PWM can be calculated by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR2A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 16-7 on page 153 OCnx has a transition from high to low
even though there is no Compare Match. The point of this transition is to guarantee symmetry
around BOTTOM. There are two cases that give a transition without Compare Match.
• OCR2A changes its value from MAX, like in Figure 16-7 on page 153. When the OCR2A
value is MAX the OCn pin value is the same as the result of a down-counting compare match.
To ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result
of an up-counting Compare Match
• The timer starts counting from a value higher than the one in OCR2A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up
16.7 Timer/Counter timing diagrams
The following figures show the Timer/Counter in synchronous mode, and the timer clock (clkT2)
is therefore shown as a clock enable signal. In asynchronous mode, clkI/O should be replaced by
the Timer/Counter Oscillator clock. The figures include information on when Interrupt Flags are
set. Figure 16-8 contains timing data for basic Timer/Counter operation. The figure shows the
count sequence close to the MAX value in all modes other than phase correct PWM mode.
Figure 16-8. Timer/Counter timing diagram, no prescaling.
f
OCnxPCPWM
f
clk_I/O
N ⋅ 510 = ------------------
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1155
7593L–AVR–09/12
AT90USB64/128
Figure 16-9 shows the same timing data, but with the prescaler enabled.
Figure 16-9. Timer/Counter timing diagram, with prescaler (fclk_I/O/8).
Figure 16-10 shows the setting of OCF2A in all modes except CTC mode.
Figure 16-10. Timer/Counter timing diagram, setting of OCF2A, with prescaler (fclk_I/O/8).
Figure 16-11 on page 156 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode.
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
OCRnx value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)156
7593L–AVR–09/12
AT90USB64/128
Figure 16-11. Timer/Counter timing diagram, clear timer on compare match mode, with prescaler
(fclk_I/O/8).
16.8 8-bit Timer/Counter register description
16.8.1 TCCR2A – Timer/Counter Control Register A
• Bits 7:6 – COM2A1:0: Compare Match Output A mode
These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0
bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2A pin
must be set in order to enable the output driver.
When OC2A is connected to the pin, the function of the COM2A1:0 bits depends on the
WGM22:0 bit setting. Table 16-1 shows the COM2A1:0 bit functionality when the WGM22:0 bits
are set to a normal or CTC mode (non-PWM).
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
Bit 7 6 5 4 3 2 1 0
COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 TCCR2A
Read/write R/W R/W R/W R/W R R R/W R/W
Initial value 0 0 0 0 0 0 0 0
Table 16-1. Compare output mode, non-PWM mode.
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 Toggle OC2A on Compare Match
1 0 Clear OC2A on Compare Match
1 1 Set OC2A on Compare Match157
7593L–AVR–09/12
AT90USB64/128
Table 16-2 shows the COM2A1:0 bit functionality when the WGM21:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Fast PWM mode” on page 151
for more details.
Table 16-3 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 153 for more details.
• Bits 5:4 – COM2B1:0: Compare Match Output B mode
These bits control the Output Compare pin (OC2B) behavior. If one or both of the COM2B1:0
bits are set, the OC2B output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2B pin
must be set in order to enable the output driver.
When OC2B is connected to the pin, the function of the COM2B1:0 bits depends on the
WGM22:0 bit setting. Table 16-4 shows the COM2B1:0 bit functionality when the WGM22:0 bits
are set to a normal or CTC mode (non-PWM).
Table 16-2. Compare Output mode, fast PWM mode (1).
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 WGM22 = 0: Normal Port Operation, OC0A Disconnected.
WGM22 = 1: Toggle OC2A on Compare Match.
1 0 Clear OC2A on Compare Match, set OC2A at TOP
1 1 Set OC2A on Compare Match, clear OC2A at TOP
Table 16-3. Compare Output mode, phase correct PWM mode (1).
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 WGM22 = 0: Normal Port Operation, OC2A Disconnected.
WGM22 = 1: Toggle OC2A on Compare Match.
1 0 Clear OC2A on Compare Match when up-counting. Set OC2A on Compare
Match when down-counting.
1 1 Set OC2A on Compare Match when up-counting. Clear OC2A on Compare
Match when down-counting.
Table 16-4. Compare Output mode, non-PWM mode.
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected
0 1 Toggle OC2B on Compare Match
1 0 Clear OC2B on Compare Match
1 1 Set OC2B on Compare Match158
7593L–AVR–09/12
AT90USB64/128
Table 16-5 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Fast PWM mode” on page 151
for more details.
Table 16-6 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 153 for more details.
• Bits 3, 2 – Res: Reserved bits
These bits are reserved bits in the Atmel AT90USB64/128 and will always read as zero.
• Bits 1:0 – WGM21:0: Waveform Generation mode
Combined with the WGM22 bit found in the TCCR2B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 16-7. Modes of operation supported by the Timer/Counter
unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of
Pulse Width Modulation (PWM) modes (see “Modes of operation” on page 150).
Table 16-5. Compare Output mode, fast PWM mode (1).
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected.
0 1 Reserved
1 0 Clear OC2B on Compare Match, set OC2B at TOP
1 1 Set OC2B on Compare Match, clear OC2B at TOP
Table 16-6. Compare Output mode, phase correct PWM mode (1).
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected
0 1 Reserved
1 0 Clear OC2B on Compare Match when up-counting. Set OC2B on Compare
Match when down-counting
1 1 Set OC2B on Compare Match when up-counting. Clear OC2B on Compare
Match when down-counting
Table 16-7. Waveform Generation mode bit description.
Mode WGM2 WGM1 WGM0
Timer/Counter
mode of operation TOP
Update of
OCRx at
TOV flag
set on (1)(2)
0 0 0 0 Normal 0xFF Immediate MAX
1 0 0 1 PWM, phase correct 0xFF TOP BOTTOM
2 0 1 0 CTC OCRA Immediate MAX
3 0 1 1 Fast PWM 0xFF TOP MAX
4 1 0 0 Reserved – – –159
7593L–AVR–09/12
AT90USB64/128
Notes: 1. MAX= 0xFF
2. BOTTOM= 0x00
16.8.2 TCCR2B – Timer/Counter Control Register B
• Bit 7 – FOC2A: Force Output Compare A
The FOC2A bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2A bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC2A output is
changed according to its COM2A1:0 bits setting. Note that the FOC2A bit is implemented as a
strobe. Therefore it is the value present in the COM2A1:0 bits that determines the effect of the
forced compare.
A FOC2A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2A as TOP.
The FOC2A bit is always read as zero.
• Bit 6 – FOC2B: Force Output Compare B
The FOC2B bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2B bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC2B output is
changed according to its COM2B1:0 bits setting. Note that the FOC2B bit is implemented as a
strobe. Therefore it is the value present in the COM2B1:0 bits that determines the effect of the
forced compare.
A FOC2B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2B as TOP.
The FOC2B bit is always read as zero.
• Bits 5:4 – Res: Reserved bits
These bits are reserved bits in the AT90USB64/128 and will always read as zero.
• Bit 3 – WGM22: Waveform Generation mode
See the description in the “TCCR2A – Timer/Counter Control Register A” on page 156.
5 1 0 1 PWM, phase correct OCRA TOP BOTTOM
6 1 1 0 Reserved – – –
7 1 1 1 Fast PWM OCRA TOP TOP
Table 16-7. Waveform Generation mode bit description. (Continued)
Mode WGM2 WGM1 WGM0
Timer/Counter
mode of operation TOP
Update of
OCRx at
TOV flag
set on (1)(2)
Bit 7 6 5 4 3 2 1 0
FOC2A FOC2B – – WGM22 CS22 CS21 CS20 TCCR2B
Read/write W W R R R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0160
7593L–AVR–09/12
AT90USB64/128
• Bit 2:0 – CS22:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter, see Table
16-8.
16.8.3 TCNT2 – Timer/Counter Register
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes) the Compare
Match on the following timer clock. Modifying the counter (TCNT2) while the counter is running,
introduces a risk of missing a Compare Match between TCNT2 and the OCR2x Registers.
16.8.4 OCR2A – Output Compare Register A
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2A pin.
16.8.5 OCR2B – Output Compare Register B
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2B pin.
Table 16-8. Clock Select bit description.
CS22 CS21 CS20 Description
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clkT2S/(no prescaling)
0 1 0 clkT2S/8 (from prescaler)
0 1 1 clkT2S/32 (from prescaler)
1 0 0 clkT2S/64 (from prescaler)
1 0 1 clkT2S/128 (from prescaler)
1 1 0 clkT2S/256 (from prescaler)
1 1 1 clkT2S/1024 (from prescaler)
Bit 7 6 5 4 3 2 1 0
TCNT2[7:0] TCNT2
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR2A[7:0] OCR2A
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
OCR2B[7:0] OCR2B
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0161
7593L–AVR–09/12
AT90USB64/128
16.9 Asynchronous operation of the Timer/Counter
16.9.1 ASSR – Asynchronous Status Register
• Bit 6 – EXCLK: Enable External Clock Input
When EXCLK is written to one, and asynchronous clock is selected, the external clock input buffer
is enabled and an external clock can be input on Timer Oscillator 1 (TOSC1) pin instead of a
32 kHz crystal. Writing to EXCLK should be done before asynchronous operation is selected.
Note that the crystal Oscillator will only run when this bit is zero.
• Bit 5 – AS2: Asynchronous Timer/Counter2
When AS2 is written to zero, Timer/Counter2 is clocked from the I/O clock, clkI/O. When AS2 is
written to one, Timer/Counter2 is clocked from a crystal Oscillator connected to the Timer Oscillator
1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2A,
OCR2B, TCCR2A and TCCR2B might be corrupted.
• Bit 4 – TCN2UB: Timer/Counter2 Update Busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set.
When TCNT2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value.
• Bit 3 – OCR2AUB: Output Compare Register2 Update Busy
When Timer/Counter2 operates asynchronously and OCR2A is written, this bit becomes set.
When OCR2A has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2A is ready to be updated with a new value.
• Bit 2 – OCR2BUB: Output Compare Register2 Update Busy
When Timer/Counter2 operates asynchronously and OCR2B is written, this bit becomes set.
When OCR2B has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2B is ready to be updated with a new value.
• Bit 1 – TCR2AUB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2A is written, this bit becomes set.
When TCCR2A has been updated from the temporary storage register, this bit is cleared by
hardware. A logical zero in this bit indicates that TCCR2A is ready to be updated with a new
value.
• Bit 0 – TCR2BUB: Timer/Counter Control Register2 Update Busy
When Timer/Counter2 operates asynchronously and TCCR2B is written, this bit becomes set.
When TCCR2B has been updated from the temporary storage register, this bit is cleared by
hardware. A logical zero in this bit indicates that TCCR2B is ready to be updated with a new
value.
If a write is performed to any of the five Timer/Counter2 Registers while its update busy flag is
set, the updated value might get corrupted and cause an unintentional interrupt to occur.
Bit 7 6 5 4 3 2 1 0
– EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB ASSR
Read/write R R/W R/W R R R R R
Initial value 0 0 0 0 0 0 0 0162
7593L–AVR–09/12
AT90USB64/128
The mechanisms for reading TCNT2, OCR2A, OCR2B, TCCR2A and TCCR2B are different.
When reading TCNT2, the actual timer value is read. When reading OCR2A, OCR2B, TCCR2A
and TCCR2B the value in the temporary storage register is read.
16.9.2 Asynchronous operation of Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken.
• Warning: When switching between asynchronous and synchronous clocking of
Timer/Counter2, the Timer Registers TCNT2, OCR2x, and TCCR2x might be corrupted. A
safe procedure for switching clock source is:
a. Disable the Timer/Counter2 interrupts by clearing OCIE2x and TOIE2.
b. Select clock source by setting AS2 as appropriate.
c. Write new values to TCNT2, OCR2x, and TCCR2x.
d. To switch to asynchronous operation: Wait for TCN2UB, OCR2xUB, and TCR2xUB.
e. Clear the Timer/Counter2 Interrupt Flags.
f. Enable interrupts, if needed.
• The CPU main clock frequency must be more than four times the Oscillator frequency
• When writing to one of the registers TCNT2, OCR2x, or TCCR2x, the value is transferred to a
temporary register, and latched after two positive edges on TOSC1. The user should not
write a new value before the contents of the temporary register have been transferred to its
destination. Each of the five mentioned registers have their individual temporary register,
which means that, for example, writing to TCNT2 does not disturb an OCR2x write in
progress. To detect that a transfer to the destination register has taken place, the
Asynchronous Status Register – ASSR has been implemented
• When entering Power-save or ADC Noise Reduction mode after having written to TCNT2,
OCR2x, or TCCR2x, the user must wait until the written register has been updated if
Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode
before the changes are effective. This is particularly important if any of the Output Compare2
interrupt is used to wake up the device, since the Output Compare function is disabled during
writing to OCR2x or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode
before the corresponding OCR2xUB bit returns to zero, the device will never receive a
compare match interrupt, and the MCU will not wake up
• If Timer/Counter2 is used to wake the device up from Power-save or ADC Noise Reduction
mode, precautions must be taken if the user wants to re-enter one of these modes: The
interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and reentering
sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the
device will fail to wake up. If the user is in doubt whether the time before re-entering Powersave
or ADC Noise Reduction mode is sufficient, the following algorithm can be used to
ensure that one TOSC1 cycle has elapsed:
a. Write a value to TCCR2x, TCNT2, or OCR2x.
b. Wait until the corresponding Update Busy Flag in ASSR returns to zero.
c. Enter Power-save or ADC Noise Reduction mode.
• When the asynchronous operation is selected, the 32.768kHz Oscillator for Timer/Counter2
is always running, except in Power-down and Standby modes. After a Power-up Reset or
wake-up from Power-down or Standby mode, the user should be aware of the fact that this
Oscillator might take as long as one second to stabilize. The user is advised to wait for at
least one second before using Timer/Counter2 after power-up or wake-up from Power-down
or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost after 163
7593L–AVR–09/12
AT90USB64/128
a wake-up from Power-down or Standby mode due to unstable clock signal upon start-up, no
matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin
• Description of wake up from Power-save or ADC Noise Reduction mode when the timer is
clocked asynchronously: When the interrupt condition is met, the wake up process is started
on the following cycle of the timer clock, that is, the timer is always advanced by at least one
before the processor can read the counter value. After wake-up, the MCU is halted for four
cycles, it executes the interrupt routine, and resumes execution from the instruction following
SLEEP
• Reading of the TCNT2 Register shortly after wake-up from Power-save may give an incorrect
result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be
done through a register synchronized to the internal I/O clock domain. Synchronization takes
place for every rising TOSC1 edge. When waking up from Power-save mode, and the I/O
clock (clkI/O) again becomes active, TCNT2 will read as the previous value (before entering
sleep) until the next rising TOSC1 edge. The phase of the TOSC clock after waking up from
Power-save mode is essentially unpredictable, as it depends on the wake-up time. The
recommended procedure for reading TCNT2 is thus as follows:
a. Write any value to either of the registers OCR2x or TCCR2x.
b. Wait for the corresponding Update Busy Flag to be cleared.
c. Read TCNT2.
• During asynchronous operation, the synchronization of the Interrupt Flags for the
asynchronous timer takes 3 processor cycles plus one timer cycle. The timer is therefore
advanced by at least one before the processor can read the timer value causing the setting of
the Interrupt Flag. The Output Compare pin is changed on the timer clock and is not
synchronized to the processor clock
16.9.3 TIMSK2 – Timer/Counter2 Interrupt Mask Register
• Bit 2 – OCIE2B: Timer/Counter2 Output Compare Match B Interrupt Enable
When the OCIE2B bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match B interrupt is enabled. The corresponding interrupt is executed
if a compare match in Timer/Counter2 occurs, that is, when the OCF2B bit is set in the
Timer/Counter2 Interrupt Flag Register – TIFR2.
• Bit 1 – OCIE2A: Timer/Counter2 Output Compare Match A Interrupt Enable
When the OCIE2A bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match A interrupt is enabled. The corresponding interrupt is executed
if a compare match in Timer/Counter2 occurs, that is, when the OCF2A bit is set in the
Timer/Counter2 Interrupt Flag Register – TIFR2.
• Bit 0 – TOIE2: Timer/Counter2 Overflow Interrupt Enable
When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter2 occurs, that is, when the TOV2 bit is set in the Timer/Counter2 Interrupt
Flag Register – TIFR2.
Bit 7 6 5 4 3 2 1 0
– – – – – OCIE2B OCIE2A TOIE2 TIMSK2
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0164
7593L–AVR–09/12
AT90USB64/128
16.9.4 TIFR2 – Timer/Counter2 Interrupt Flag Register
• Bit 2 – OCF2B: Output Compare Flag 2 B
The OCF2B bit is set (one) when a compare match occurs between the Timer/Counter2 and the
data in OCR2B – Output Compare Register2. OCF2B is cleared by hardware when executing
the corresponding interrupt handling vector. Alternatively, OCF2B is cleared by writing a logic
one to the flag. When the I-bit in SREG, OCIE2B (Timer/Counter2 Compare match Interrupt
Enable), and OCF2B are set (one), the Timer/Counter2 Compare match Interrupt is executed.
• Bit 1 – OCF2A: Output Compare Flag 2 A
The OCF2A bit is set (one) when a compare match occurs between the Timer/Counter2 and the
data in OCR2A – Output Compare Register2. OCF2A is cleared by hardware when executing
the corresponding interrupt handling vector. Alternatively, OCF2A is cleared by writing a logic
one to the flag. When the I-bit in SREG, OCIE2A (Timer/Counter2 Compare match Interrupt
Enable), and OCF2A are set (one), the Timer/Counter2 Compare match Interrupt is executed.
• Bit 0 – TOV2: Timer/Counter2 Overflow Flag
The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV2 is cleared
by writing a logic one to the flag. When the SREG I-bit, TOIE2A (Timer/Counter2 Overflow Interrupt
Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In
PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00.
16.10 Timer/Counter prescaler
Figure 16-12. Prescaler for Timer/Counter2.
Bit 7 6 5 4 3 2 1 0
– – – – – OCF2B OCF2A TOV2 TIFR2
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
10-BIT T/C PRESCALER
TIMER/COUNTER2 CLOCK SOURCE
clkI/O clkT2S
TOSC1
AS2
CS20
CS21
CS22
clkT2S/8
clkT2S/64
clkT2S/128
clkT2S/1024
clkT2S/256
clkT2S/32
0 PSRASY
Clear
clkT2165
7593L–AVR–09/12
AT90USB64/128
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main
system I/O clock clkIO. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously
clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter
(RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port C. A crystal can
then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock
source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal. Applying
an external clock source to TOSC1 is not recommended.
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64,
clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected.
Setting the PSRASY bit in GTCCR resets the prescaler. This allows the user to operate with a
predictable prescaler.
16.10.1 GTCCR – General Timer/Counter Control Register
• Bit 1 – PSRASY: Prescaler Reset Timer/Counter2
When this bit is one, the Timer/Counter2 prescaler will be reset. This bit is normally cleared
immediately by hardware. If the bit is written when Timer/Counter2 is operating in asynchronous
mode, the bit will remain one until the prescaler has been reset. The bit will not be cleared by
hardware if the TSM bit is set. Refer to the description of the Section “GTCCR – General
Timer/Counter Control Register” on page 97 for a description of the Timer/Counter Synchronization
mode.
Bit 7 6 5 4 3 2 1 0
TSM – – – – – PSRASY
PSRSY
NC
GTCCR
Read/write R/W R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0166
7593L–AVR–09/12
AT90USB64/128
17. Output Compare Modulator (OCM1C0A)
17.1 Overview
The Output Compare Modulator (OCM) allows generation of waveforms modulated with a carrier
frequency. The modulator uses the outputs from the Output Compare Unit C of the 16-bit
Timer/Counter1 and the Output Compare Unit of the 8-bit Timer/Counter0. For more details
about these Timer/Counters see “Timer/Counter0, Timer/Counter1, and Timer/Counter3 prescalers”
on page 96 and “8-bit Timer/Counter2 with PWM and asynchronous operation” on page
145.
Figure 17-1. Output Compare Modulator, block diagram.
When the modulator is enabled, the two output compare channels are modulated together as
shown in the block diagram (Figure 17-1).
17.2 Description
The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The
outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register
when one of them is enabled (that is, when COMnx1:0 is not equal to zero). When both OC1C
and OC0A are enabled at the same time, the modulator is automatically enabled.
The functional equivalent schematic of the modulator is shown on Figure 17-2. The schematic
includes part of the Timer/Counter units and the port B pin 7 output driver circuit.
Figure 17-2. Output Compare Modulator, schematic.
OC1C
Pin
OC1C /
OC0A / PB7
Timer/Counter 1
Timer/Counter 0 OC0A
PORTB7 DDRB7
D Q D Q
Pin
COMA01
COMA00
DATABUS
OC1C /
OC0A/ PB7
COM1C1
COM1C0
Modulator
1
0
OC1C
D Q
OC0A
D Q
(From Waveform generator)
(From Waveform generator)
0
1
Vcc167
7593L–AVR–09/12
AT90USB64/128
When the modulator is enabled the type of modulation (logical AND or OR) can be selected by
the PORTB7 Register. Note that the DDRB7 controls the direction of the port independent of the
COMnx1:0 bit setting.
17.2.1 Timing example
Figure 17-3 illustrates the modulator in action. In this example the Timer/Counter1 is set to operate
in fast PWM mode (non-inverted) and Timer/Counter0 uses CTC waveform mode with toggle
Compare Output mode (COMnx1:0 = 1).
Figure 17-3. Output Compare Modulator, timing diagram.
In this example, Timer/Counter2 provides the carrier, while the modulating signal is generated
by the Output Compare unit C of the Timer/Counter1.
The resolution of the PWM signal (OC1C) is reduced by the modulation. The reduction factor is
equal to the number of system clock cycles of one period of the carrier (OC0A). In this example
the resolution is reduced by a factor of two. The reason for the reduction is illustrated in Figure
17-3 at the second and third period of the PB7 output when PORTB7 equals zero. The period 2
high time is one cycle longer than the period 3 high time, but the result on the PB7 output is
equal in both periods.
1 2
OC0A
(CTC mode)
OC1C
(FPWM mode)
PB7
(PORTB7 = 0)
PB7
(PORTB7 = 1)
(Period) 3
clk I/O168
7593L–AVR–09/12
AT90USB64/128
18. SPI – Serial Peripheral Interface
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
Atmel AT90USB64/128 and peripheral devices or between several AVR devices. The
AT90USB64/128 SPI includes the following features:
• Full-duplex, three-wire synchronous data transfer
• Master or slave operation
• LSB first or MSB first data transfer
• Seven programmable bit rates
• End of transmission interrupt flag
• Write collision flag protection
• Wake-up from Idle mode
• Double speed (CK/2) Master SPI mode
USART can also be used in Master SPI mode, see “USART in SPI mode” on page 202.
The Power Reduction SPI bit, PRSPI, in “PRR0 – Power Reduction Register 0” on page 54 must
be written to zero to enable SPI module.
Figure 18-1. SPI block diagram (1).
Note: 1. Refer to Figure 1-1 on page 3, and Table 11-6 on page 79 for SPI pin placement.
The interconnection between Master and Slave CPUs with SPI is shown in Figure 18-2 on page
169. The system consists of two shift Registers, and a Master clock generator. The SPI Master
initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave. SPI2X SPI2X
DIVIDER
/2/4/8/16/32/64/128169
7593L–AVR–09/12
AT90USB64/128
Master and Slave prepare the data to be sent in their respective shift Registers, and the Master
generates the required clock pulses on the SCK line to interchange data. Data is always shifted
from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the
Master In – Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave
by pulling high the Slave Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This
must be handled by user software before communication can start. When this is done, writing a
byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight
bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of
Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an
interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be
kept in the Buffer Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin
until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission
Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt
is requested. The Slave may continue to place new data to be sent into SPDR before reading
the incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 18-2. SPI Master-slave interconnection.
The system is single buffered in the transmit direction and double buffered in the receive direction.
This means that bytes to be transmitted cannot be written to the SPI Data Register before
the entire shift cycle is completed. When receiving data, however, a received character must be
read from the SPI Data Register before the next character has been completely shifted in. Otherwise,
the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure
correct sampling of the clock signal, the frequency of the SPI clock should never exceed fosc/4.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 18-1 on page 170. For more details on automatic port overrides, refer to
“Alternate port functions” on page 76.
SHIFT
ENABLE170
7593L–AVR–09/12
AT90USB64/128
Note: 1. See “Alternate functions of Port B” on page 79 for a detailed description of how to define the
direction of the user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a
simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction
Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the
actual data direction bits for these pins. For example, if MOSI is placed on pin PB5, replace
DD_MOSI with DDB5 and DDR_SPI with DDRB.
Table 18-1. SPI pin overrides (1).
Pin Direction, master SPI Direction, slave SPI
MOSI User defined Input
MISO Input User defined
SCK User defined Input
SS User defined Input171
7593L–AVR–09/12
AT90USB64/128
Note: 1. See “About code examples” on page 10.
Assembly code example (1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi r17,(1<>8);
UBRRLn = (unsigned char)baud;
/* Enable receiver and transmitter */
UCSRnB = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}188
7593L–AVR–09/12
AT90USB64/128
The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive buffer.
This flag is one when unread data exist in the receive buffer, and zero when the receive
buffer is empty (that is, does not contain any unread data). If the Receiver is disabled (RXENn =
0), the receive buffer will be flushed and consequently the RXCn bit will become zero.
When the Receive Complete Interrupt Enable (RXCIEn) in UCSRnB is set, the USART Receive
Complete interrupt will be executed as long as the RXCn Flag is set (provided that global interrupts
are enabled). When interrupt-driven data reception is used, the receive complete routine
must read the received data from UDRn in order to clear the RXCn Flag, otherwise a new interrupt
will occur once the interrupt routine terminates.
19.6.4 Receiver error flags
The USART Receiver has three error flags: Frame Error (FEn), Data OverRun (DORn) and Parity
Error (UPEn). All can be accessed by reading UCSRnA. Common for the Error Flags is that
they are located in the receive buffer together with the frame for which they indicate the error
status. Due to the buffering of the Error Flags, the UCSRnA must be read before the receive buffer
(UDRn), since reading the UDRn I/O location changes the buffer read location. Another
equality for the Error Flags is that they can not be altered by software doing a write to the flag
location. However, all flags must be set to zero when the UCSRnA is written for upward compatibility
of future USART implementations. None of the Error Flags can generate interrupts.
The Frame Error (FEn) Flag indicates the state of the first stop bit of the next readable frame
stored in the receive buffer. The FEn Flag is zero when the stop bit was correctly read (as one),
and the FEn Flag will be one when the stop bit was incorrect (zero). This flag can be used for
detecting out-of-sync conditions, detecting break conditions and protocol handling. The FEn
Flag is not affected by the setting of the USBSn bit in UCSRnC since the Receiver ignores all,
except for the first, stop bits. For compatibility with future devices, always set this bit to zero
when writing to UCSRnA.
The Data OverRun (DORn) Flag indicates data loss due to a receiver buffer full condition. A
Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting
in the Receive Shift Register, and a new start bit is detected. If the DORn Flag is set there
was one or more serial frame lost between the frame last read from UDRn, and the next frame
read from UDRn. For compatibility with future devices, always write this bit to zero when writing
to UCSRnA. The DORn Flag is cleared when the frame received was successfully moved from
the Shift Register to the receive buffer.
The Parity Error (UPEn) Flag indicates that the next frame in the receive buffer had a Parity
Error when received. If Parity Check is not enabled the UPEn bit will always be read zero. For
compatibility with future devices, always set this bit to zero when writing to UCSRnA. For more
details see “Parity bit calculation” on page 181 and “Parity Checker” on page 188.
19.6.5 Parity Checker
The Parity Checker is active when the high USART Parity mode (UPMn1) bit is set. Type of Parity
Check to be performed (odd or even) is selected by the UPMn0 bit. When enabled, the Parity
Checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. The result of the check is stored in the receive buffer together
with the received data and stop bits. The Parity Error (UPEn) Flag can then be read by software
to check if the frame had a Parity Error.189
7593L–AVR–09/12
AT90USB64/128
The UPEn bit is set if the next character that can be read from the receive buffer had a Parity
Error when received and the Parity Checking was enabled at that point (UPMn1 = 1). This bit is
valid until the receive buffer (UDRn) is read.
19.6.6 Disabling the Receiver
In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing
receptions will therefore be lost. When disabled (that is, the RXENn is set to zero) the Receiver
will no longer override the normal function of the RxDn port pin. The Receiver buffer FIFO will be
flushed when the Receiver is disabled. Remaining data in the buffer will be lost
19.6.7 Flushing the receive buffer
The receiver buffer FIFO will be flushed when the Receiver is disabled, that is, the buffer will be
emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal
operation, due to for instance an error condition, read the UDRn I/O location until the RXCn Flag
is cleared. The following code example shows how to flush the receive buffer.
Note: 1. See “About code examples” on page 10.
19.7 Asynchronous data reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data
reception. The clock recovery logic is used for synchronizing the internally generated baud rate
clock to the incoming asynchronous serial frames at the RxDn pin. The data recovery logic samples
and low pass filters each incoming bit, thereby improving the noise immunity of the
Receiver. The asynchronous reception operational range depends on the accuracy of the internal
baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
19.7.1 Asynchronous clock recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 19-5
on page 190 illustrates the sampling process of the start bit of an incoming frame. The sample
rate is 16 times the baud rate for Normal mode, and eight times the baud rate for Double Speed
mode. The horizontal arrows illustrate the synchronization variation due to the sampling process.
Note the larger time variation when using the Double Speed mode (U2Xn = 1) of
operation. Samples denoted zero are samples done when the RxDn line is idle (that is, no communication
activity).
Assembly code example (1)
USART_Flush:
sbis UCSRnA, RXCn
ret
in r16, UDRn
rjmp USART_Flush
C code example (1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRnA & (1<
USBE=1
ID=1
Clock stopped
FRZCLK=1
Macro off
USBE=0
USBE=0
Host
USBE=0
HW
RESET
USBE=1
ID=0
AT90USB647/1287 only
AT90USB646/1286 forced mode247
7593L–AVR–09/12
AT90USB64/128
22.4.3 Interrupts
Two interrupts vectors are assigned to USB interface.
Figure 22-10. USB interrupt system.
See Section 23.17, page 272 and Section 24.15, page 291 for more details on the Host and
Device interrupts.
USB general
& OTG interrupt
USB device
interrupt
USB host
interrupt
USB general
interrupt vector
Endpoint
interrupt
Pipe
interrupt
USB endpoint/pipe
interrupt vector248
7593L–AVR–09/12
AT90USB64/128
Figure 22-11. USB general interrupt vector sources.
IDTE
USBCON.1
IDTI
USBINT.1
VBUSTI
USBINT.0 VBUSTE
USBCON.0
STOI
OTGINT.5 STOE
OTGIEN.5
HNPERRI
OTGINT.4 HNPERRE
OTGIEN.4
ROLEEXI
OTGINT.3 ROLEEXE
OTGIEN.3
BCERRI
OTGINT.2 BCERRE
OTGIEN.2
VBERRI
OTGINT.1 VBERRE
OTGIEN.1
SRPI
OTGINT.0 SRPE
OTGIEN.0
USB general
interrupt vector
UPRSMI
UDINT.6 UPRSME
UDIEN.6
EORSMI
UDINT.5 EORSME
UDIEN.5
WAKEUPI
UDINT.4 WAKEUPE
UDIEN.4
EORSTI
UDINT.3 EORSTE
UDIEN.3
SOFI
UDINT.2 SOFE
UDIEN.2
SUSPI
UDINT.0 SUSPE
UDIEN.0
HWUPE
UHIEN.6
HWUPI
UHINT.6
HSOFI
UHINT.5 HSOFE
UHIEN.5
RXRSMI
UHINT.4 RXRSME
UHIEN.4
RSMEDI
UHINT.3 RSMEDE
UHIEN.3
RSTI
UHINT.2 RSTE
UHIEN.2
DDISCI
UHINT.1 DDISCE
UHIEN.1
DCONNI
UHINT.0 DCONNE
UHIEN.0
USB device
interrupt
USB host
interrupt
USB general
interrupt vector
Asynchronous interrupt source
(allows the CPU to wake up from power down mode)249
7593L–AVR–09/12
AT90USB64/128
Figure 22-12. USB endpoint/pipe Interrupt vector sources.
FLERRE
UEIENX.7
OVERFI
UESTAX.6
UNDERFI
UESTAX.5
NAKINI
UEINTX.6 NAKINE
UEIENX.6
NAKOUTI
UEINTX.4 TXSTPE
UEIENX.4
RXSTPI
UEINTX.3 RXSTPE
UEIENX.3
RXOUTI
UEINTX.2 RXOUTE
UEIENX.2
STALLEDI
UEINTX.1 STALLEDE
UEIENX.1
EPINT
UEINT.X
Endpoint 0
Endpoint 1
Endpoint 2
Endpoint 3
Endpoint 4
Endpoint 5
Endpoint interrupt
TXINI
UEINTX.0 TXINE
UEIENX.0
FLERRE
UPIEN.7
UNDERFI
UPSTAX.5
OVERFI
UPSTAX.6
NAKEDI
UPINTX.6 NAKEDE
UPIEN.6
PERRI
UPINTX.4 PERRE
UPIEN.4
TXSTPI
UPINTX.3 TXSTPE
UPIEN.3
TXOUTI
UPINTX.2 TXOUTE
UPIEN.2
RXSTALLI
UPINTX.1 RXSTALLE
UPIEN.1
RXINI
UPINTX.0 RXINE
UPIEN.0
FLERRE
UPIEN.X
PIPE 0
PIPE 1
PIPE 2
PIPE 3
PIPE 4
PIPE 5
Pipe interrupt
USB endpoint/pipe
interrupt vector
Endpoint 6
PIPE 6250
7593L–AVR–09/12
AT90USB64/128
Figure 22-13. USB general and OTG controller interrupt system.
There are two kinds of interrupts: processing (that is, their generation are part of the normal processing)
and exception (errors).
Processing interrupts are generated when such events occur:
• USB ID Pad change detection (insert, remove)(IDTI)
• VBUS plug-in detection (insert, remove) (VBUSTI)
• SRP detected(SRPI)
• Role Exchanged(ROLEEXI)
Exception Interrupts are generated with the following events:
• Drop on VBus Detected(VBERRI)
• Error during the B-Connection(BCERRI)
• HNP Error(HNPERRI)
• Time-out detected during Suspend mode(STOII)
22.5 Power modes
22.5.1 Idle mode
In this mode, the CPU core is halted (CPU clock stopped). The Idle mode is taken wether the
USB controller is running or not. The CPU “wakes up” on any USB interrupts.
22.5.2 Power down
In this mode, the oscillator is stopped and halts all the clocks (CPU and peripherals). The USB
controller “wakes up” when:
• the WAKEUPI interrupt is triggered in the Peripheral mode (HOST cleared)
IDTE
USBCON.1
IDTI
USBINT.1
VBUSTI
USBINT.0 VBUSTE
USBCON.0
STOI
OTGINT.5 STOE
OTGIEN.5
HNPERRI
OTGINT.4 HNPERRE
OTGIEN.4
ROLEEXI
OTGINT.3 ROLEEXE
OTGIEN.3
BCERRI
OTGINT.2 BCERRE
OTGIEN.2
VBERRI
OTGINT.1 VBERRE
OTGIEN.1
SRPI
OTGINT.0 SRPE
OTGIEN.0
USB general & OTG
interrupt vector
Asynchronous interrupt source
(allows the CPU to wake up from power down mode251
7593L–AVR–09/12
AT90USB64/128
• the HWUPI interrupt is triggered in the Host mode (HOST set)
• the IDTI interrupt is triggered
• the VBUSTI interrupt is triggered
22.5.3 Freeze clock
The firmware has the ability to reduce the power consumption by setting the FRZCLK bit, which
freeze the clock of USB controller. When FRZCLK is set, it is still possible to access to the following
registers:
• USBCON, USBSTA, USBINT
• UDCON (detach, ...)
• UDINT
• UDIEN
• UHCON
• UHINT
• UHIEN
Moreover, when FRZCLK is set, only the following interrupts may be triggered:
• WAKEUPI
• IDTI
• VBUSTI
• HWUPI
22.6 Speed control
22.6.1 Device mode
When the USB interface is configured in device mode, the speed selection (Full Speed or Low
Speed) depends on the UDP/UDM pull-up. The LSM bit in UDCON register allows to select an
internal pull up on UDM (Low Speed mode) or UDP (Full Speed mode) data lines.
Figure 22-14. Device mode speed selection.
RPU
DETACH
UDCON.0
UDP
UDM
RPU
LSM
UDCON.2
UCAP USB
regulator252
7593L–AVR–09/12
AT90USB64/128
22.6.2 Host mode
When the USB interface is configured in host mode, internal Pull Down resistors are activated on
both UDP UDM lines and the interface detects the type of connected device.
22.7 Memory management
The controller does only support the following memory allocation management.
The reservation of a Pipe or an Endpoint can only be made in the increasing order (Pipe/Endpoint
0 to the last Pipe/Endpoint). The firmware shall thus configure them in the same order.
The reservation of a Pipe or an Endpoint “ki
” is done when its ALLOC bit is set. Then, the hardware
allocates the memory and inserts it between the Pipe/Endpoints “ki-1” and “ki+1”. The “ki+1”
Pipe/Endpoint memory “slides” up and its data is lost. Note that the “ki+2” and upper Pipe/Endpoint
memory does not slide.
Clearing a Pipe enable (PEN) or an Endpoint enable (EPEN) does not clear either its ALLOC bit,
or its configuration (EPSIZE/PSIZE, EPBK/PBK). To free its memory, the firmware should clear
ALLOC. Then, the “ki+1” Pipe/Endpoint memory automatically “slides” down. Note that the “ki+2”
and upper Pipe/Endpoint memory does not slide.
The following figure illustrates the allocation and reorganization of the USB memory in a typical
example:
Table 22-1. Allocation and reorganization USB memory flow.
• First, Pipe/Endpoint 0 to Pipe/Endpoint 5 are configured, in the growing order. The memory
of each is reserved in the DPRAM
• Then, the Pipe/Endpoint 3 is disabled (EPEN=0), but its memory reservation is internally kept
by the controller
• Its ALLOC bit is cleared: the Pipe/Endpoint 4 “slides” down, but the Pipe/Endpoint 5 does not
“slide”
• Finally, if the firmware chooses to reconfigure the Pipe/Endpoint 3, with a bigger size. The
controller reserved the memory after the endpoint 2 memory and automatically “slide” the
Pipe/Endpoint 4. The Pipe/Endpoint 5 does not move and a memory conflict appear, in that
Free memory
0
1
2
3
4
5
EPEN=1
ALLOC=1
Free memory
0
1
2
4
5
EPEN=0
(ALLOC=1)
Free memory
0
1
2
4
5
Pipe/Endpoints
activation
Pipe/Endpoint
Disable
Free its memory
(ALLOC=0)
Free memory
0
1
2
3 (bigger size)
5
Pipe/Endpoint
Activatation
Lost memory
4 Conflict253
7593L–AVR–09/12
AT90USB64/128
both Pipe/Endpoint 4 and 5 use a common area. The data of those endpoints are potentially
lost
Note that:
• the data of Pipe/Endpoint 0 are never lost whatever the activation or deactivation of the
higher Pipe/Endpoint. Its data is lost if it is deactivated
• Deactivate and reactivate the same Pipe/Endpoint with the same parameters does not lead
to a “slide” of the higher endpoints. For those endpoints, the data are preserved
• CFGOK is set by hardware even in the case where there is a “conflict” in the memory
allocation
22.8 PAD suspend
The next figures illustrates the pad behaviour:
• In the “idle” mode, the pad is put in low power consumption mode
• In the “active” mode, the pad is working
Figure 22-15. Pad behaviour.
The SUSPI flag indicated that a suspend state has been detected on the USB bus. This flag
automatically put the USB pad in Idle. The detection of a non-idle event sets the WAKEUPI flag
and wakes-up the USB pad.
Moreover, the pad can also be put in the “idle” mode if the DETACH bit is set. It come back in
the active mode when the DETACH bit is cleared.
Idle mode
Active mode
USBE=1
& DETACH=0
& suspend
USBE=0
| DETACH=1
| suspend
SUSPI Suspend detected = USB pad power down Clear suspend by software
Resume = USB pad wake-up
WAKEUPI Clear resume by software
PAD status
Active Power Down Active254
7593L–AVR–09/12
AT90USB64/128
22.9 OTG timers customizing
It is possible to refine some OTG timers thanks to the OTGTCON register that contains the
PAGE bits to select the timer and the VALUE bits to adjust the value. User should refer to lastest
releases of the OTG specification to select compliant timings.
• PAGE=00b: AWaitVrise time-out. [OTG]. In Host mode, once VBUSREQ has been set to “1”,
if no VBUS is detected on VBUS pin after this AWaitVrise delay then the VBERRI error flag is
set.
– VALUE=00bTime-out is set to 20ms
– VALUE=01bTime-out is set to 50ms
– VALUE=10bTime-out is set to 70ms
– VALUE=11bTime-out is set to 100ms
• PAGE=01b: VbBusPulsing. [OTG]. In Device mode, this delay corresponds to the pulse
duration on Vbus during a SRP.
– VALUE=00bTime-out is set to 15ms
– VALUE=01bTime-out is set to 23ms
– VALUE=10bTime-out is set to 31ms
– VALUE=11bTime-out is set to 40ms
• PAGE=10b: PdTmOutCnt. [OTG]. In Device mode, when a SRP has been requested to be
sent by the firmware, this delay is waited by the hardware after VBUS has gone below the
“session_valid” threshold voltage and before initiating the first pulse. This delay should be
considered as an approximation of USB lines discharge (pull-down resistors vs. line
capacitance) in order to wait that VBUS has gone below the “b_session_end” threshold
voltae, as defined in the OTG specification.
– VALUE=00bTime-out is set to 93ms
– VALUE=01bTime-out is set to 105ms
– VALUE=10bTime-out is set to 118ms
– VALUE=11bTime-out is set to 131ms
• PAGE=11b: SRPDetTmOut. [OTG]. In Host mode, this delay is the minimum pulse duration
required to detect and accept a valid SRP from a Device.
– VALUE=00bTime-out is set to 1µs
– VALUE=01bTime-out is set to 100µs
– VALUE=10bTime-out is set to 1ms
– VALUE=11bTime-out is set to 11ms255
7593L–AVR–09/12
AT90USB64/128
22.10 Plug-in detection
The USB connection is detected by the VBUS pad, thanks to the following architecture:
Figure 22-16. Plug-in detection input block diagram.
The control logic of the VBUS pad outputs a signal regarding the VBUS voltage level:
• The “Session_valid” signal is active high when the voltage on the VBUS pad is higher or
equal to 1.4V. If lower than 1.4V, the signal is not active
• The “Vbus_valid” signal is active high when the voltage on the VBUS pad is higher or equal to
4.4V. If lower than 4.4V, the signal is not active
• The VBUS status bit is set when VBUS is greater than “Vbus_valid”. The VBUS status bit is
cleared when VBUS falls below “Session_valid” (hysteresis behavior)
• The VBUSTI flag is set each time the VBUS bit state changes
22.10.1 Peripheral mode
The USB peripheral cannot attach to the bus while VBUS bit is not set.
22.10.2 Host mode
The Host must use the UVCON pin to drive an external power switch or regulator that powers
the Vbus line. The UVCON pin is automatically asserted and set high by hardware when
UVCONE and VBUSREQ bits are set by firmware.
If a device connects (pull-up on DP or DM) within 300ms of Vbus delivery, the DCONNI flag will
rise. But, once VBUSREQ bit has been set, if no peripheral connection is detected within 300ms,
the BCERRI flag (and interrupt) will rise and Vbus delivery will be stopped (UVCON cleared).
If that behavior represents a limitation for the Host application, the following work-around may be
used :
1. UVCONE and VBUSREQ must be cleared.
2. VBUSHWC must be set (to disable hardware control of UVCON pin).
3. PORTE,7 pin (alternate function of UVCON pin) must be set by firmware.
4. a device connection will be detected thanks to the SRPI flag (that may usually be used
to detect a DP/DM pulse sent by an OTG B-Device that requests a new session).
VBUSTI
USBINT.0
VBUS VBUS
USBSTA.0
VSS
VDD
Pad logic
Logic
Session_valid RPU RPU
VBus_pulsing
VBus_discharge
Vbus_valid256
7593L–AVR–09/12
AT90USB64/128
22.11 ID detection
The ID pin transition is detected thanks to the following architecture:
Figure 22-17. ID detection input block diagram.
The ID pin can be used to detect the USB mode (Peripheral or Host) or software selected. This
allows the UID pin to be used has general purpose I/O even when USB interface is enable.
When the UID pin is selected, by default, (no A-plug or B-plug), the macro is in the Peripheral
mode (internal pull-up). The IDTI interrupt is triggered when a A-plug (Host) is plugged or
unplugged. The interrupt is not triggered when a B-plug (Periph) is plugged or unplugged.
ID detection is independent of USB global interface enable.
22.12 Registers description
22.12.1 USB general registers
• 7 – UIMOD: USB Mode bit
This bit has no effect when the UIDE bit is set (external UID pin activated). Set to enable the
USB device mode. Clear to enable the USB host mode
• 6 – UIDE: UID pin Enable
Set to enable the USB mode selection (peripheral/host) through the UID pin. Clear to enable the
USB mode selection (peripheral/host) with UIMOD bit register.
UIDE should be modified only when the USB interface is disabled (USBE bit cleared).
• 5 – Reserved
The value read from this bit is always 0. Do not set this bit.
• 4 – UVCONE: UVCON pin Enable
Set to enable the UVCON pin control. Clear to disable the UVCON pin control. This bit should be
set only when the USB interface is enable.
RPU
UIMOD
UHWCON.7
UID
ID
USBSTA.1
Internal pull up
VDD
UIDE
UHWCON.6
1
0
Bit 7 6 5 4 3 2 1 0
UIMOD UIDE UVCONE UVREGE UHWCON
Read/write R/W R/W R R/W R R R R/W
Initial value 1 0 0 0 0 0 0 0257
7593L–AVR–09/12
AT90USB64/128
• 3-1 – Reserved
The value read from these bits is always 0. Do not set these bits.
• 0 – UVREGE: USB pad regulator Enable
Set to enable the USB pad regulator. Clear to disable the USB pad regulator.
• 7 – USBE: USB macro Enable bit
Set to enable the USB controller. Clear to disable and reset the USB controller, to disable the
USB transceiver and to disable the USB controller clock inputs.
• 6 – HOST: HOST bit
Set to enable the Host mode. Clear to enable the device mode.
• 5 – FRZCLK: Freeze USB Clock bit
Set to disable the clock inputs (the ”Resume Detection” is still active). This reduces the power
consumption. Clear to enable the clock inputs.
• 4 – OTGPADE: OTG Pad Enable
Set to enable the OTG pad. Clear to disable the OTG pad. The OTG pad is actually the VBUS
pad.
Note that this bit can be set/cleared even if USBE=0. That allows the VBUS detection even if the
USB macro is disabled. This pad must be enabled in both Host and Device modes in order to
allow USB operation (attaching, transmitting...).
• 3-2 – Reserved
The value read from these bits is always 0. Do not set these bits.
• 1 – IDTE: ID Transition Interrupt Enable bit
Set this bit to enable the ID Transition interrupt generation. Clear this bit to disable the ID Transition
interrupt generation.
• 0 – VBUSTE: VBUS Transition Interrupt Enable bit
Set this bit to enable the VBUS Transition interrupt generation.
Clear this bit to disable the VBUS Transition interrupt generation.
• 7-4 - Reserved
The value read from these bits is always 0. Do not set these bits.
Bit 7 6 5 4 3 2 1 0
USBE HOST FRZCLK OTGPADE - - IDTE VBUSTE USBCON
Read/write R/W R/W R/W R/W R R R/W R/W
Initial value 0 0 1 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - - - SPEED ID VBUS USBSTA
Read/write R R R R R R R R
Initial value 0 0 0 0 1 0 1 0258
7593L–AVR–09/12
AT90USB64/128
• 3 – SPEED: Speed Status Flag
This should be read only when the USB controller operates in host mode, in device mode the
value read from this bit is undeterminated.
Set by hardware when the controller is in FULL-SPEED mode. Cleared by hardware when the
controller is in LOW-SPEED mode.
• 2 – Reserved
The value read from this bit is always 0. Do not set this bit.
• 1 – ID: IUD pin flag
The value read from this bit indicates the state of the UID pin.
• 0 – VBUS: VBus flag
The value read from this bit indicates the state of the VBUS pin. This bit can be used in device
mode to monitor the USB bus connection state of the application. See Section 22.10, page 255
for more details.
7-2 - Reserved
The value read from these bits is always 0. Do not set these bits.
1 – IDTI: D Transition Interrupt flag
Set by hardware when a transition (high to low, low to high) has been detected on the UID pin.
Shall be cleared by software.
• 0 – VBUSTI: IVBUS Transition Interrupt flag
Set by hardware when a transition (high to low, low to high) has been detected on the VBUS
pad.
Shall be cleared by software.
• 7-6 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 5 – HNPREQ: HNP Request bit
Set to initiate the HNP when the controller is in the Device mode (B). Set to accept the HNP
when the controller is in the Host mode (A).
Clear otherwise.
Bit 7 6 5 4 3 2 1 0
- - - - - - IDTI VBUSTI USBINT
Read/write R R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - HNPREQ SRPREQ SRPSEL VBUSHWC VBUSREQ VBUSRQC OTGCON
Read/write R R R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0259
7593L–AVR–09/12
AT90USB64/128
• 4 – SRPREQ: SRP Request bit
Set to initiate the SRP when the controller is in Device mode. Cleared by hardware when the
controller is initiating a SRP.
• 3 – SRPSEL: SRP Selection bit
Set to choose VBUS pulsing as SRP method.
Clear to choose data line pulsing as SRP method.
• 2 – VBUSHWC: VBus Hardware Control bit
Set to disable the hardware control over the UVCON pin.
Clear to enable the hardware control over the UVCON pin.
See for more details
• 1 – VBUSREQ: VBUS Request bit
Set to assert the UVCON pin in order to enable the VBUS power supply generation. This bit
shall be used when the controller is in the Host mode.
Cleared by hardware when VBUSRQC is set.
• 0 – VBUSRQC: VBUS Request Clear bit
Set to deassert the UVCON pin in order to enable the VBUS power supply generation. This bit
shall be used when the controller is in the Host mode.
Cleared by hardware immediately after the set.
• 7 – Reserved
This bit is reserved and always set.
• 6-5 – PAGE: Timer page access bit
Set/clear to access a special timer register. See Section 22.9, page 254 for more details.
• 4-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 1-0 – VALUE: Value bit
Set to initialize the new value of the timer. See Section 22.9, page 254 for more details.
Bit 7 6 5 4 3 2 1 0
- PAGE - - - VALUE OTGTCON
Read/write R R/W R/W R R R/W R/W R/W
Initial value 1 0 0 0 0 0 0 0260
7593L–AVR–09/12
AT90USB64/128
• 7-6 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 5 – STOE: Suspend Time-out Error Interrupt Enable bit
Set to enable the STOI interrupt. Clear to disable the STOI interrupt.
• 4 – HNPERRE: HNP Error Interrupt Enable bit
Set to enable the HNPERRI interrupt. Clear to disable the HNPERRI interrupt.
• 3 – ROLEEXE: Role Exchange Interrupt Enable bit
Set to enable the ROLEEXI interrupt. Clear to disable the ROLEEXI interrupt.
• 2 – BCERRE: B-Connection Error Interrupt Enable bit
Set to enable the BCERRI interrupt. Clear to disable the BCERRI interrupt.
• 1 – VBERRE: VBus Error Interrupt Enable bit
Set to enable the VBERRI interrupt. Clear to disable the VBERRI interrupt.
• 0 – SRPE: SRP Interrupt Enable bit
Set to enable the SRPI interrupt. Clear to disable the SRPI interrupt.
• 7-6 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 5 – STOI: Suspend Time-out Error Interrupt flag
Set by hardware when a time-out error (more than 150ms) has been detected after a suspend.
Shall be cleared by software.
• 4 – HNPERRI: HNP Error Interrupt flag
Set by hardware when an error has been detected during the protocol. Shall be cleared by
software.
• 3 – ROLEEXI: Role Exchange Interrupt flag
Set by hardware when the USB controller has successfully swapped its mode, due to an HNP
negotiation: Host to Device or Device to Host. However the mode selection bit (Host/Device) is
unchanged and must be changed by firmware in order to reach the correct RAM locations and
events bits. Shall be cleared by software.
Bit 7 6 5 4 3 2 1 0
- - STOE HNPERRE ROLEEXE BCERRE VBERRE SRPE OTGIEN
Read/write R R R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - STOI HNPERRI ROLEEXI BCERRI VBERRI SRPI OTGINT
Read/write R R R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0261
7593L–AVR–09/12
AT90USB64/128
• 2 – BCERRI: B-Connection Error Interrupt flag
Set by hardware when an error occur during the B-Connection (that is, if Peripheral has not connected
after 300ms of Vbus delivery request). Shall be cleared by software.
• 1 – VBERRI: V-Bus Error Interrupt flag
Set by hardware when a drop on VBus has been detected. Shall be cleared by software.
• 0 – SRPI: SRP Interrupt flag
Set by hardware when a SRP has been detected. Shall be used in the Host mode only. Shall be
cleared by software.
22.13 USB Software Operating modes
Depending on the USB operating mode, the software should perform some the following
operations:
Power On the USB interface
• Power-On USB pads regulator
• Configure PLL interface
• Enable PLL and wait PLL lock
• Enable USB interface
• Configure USB interface (USB speed, Endpoints configuration...)
• Wait for USB VBUS information connection
• Attach USB device
Power Off the USB interface
• Detach USB interface
• Disable USB interface
• Disable PLL
• Disable USB pad regulator
Suspending the USB interface
• Clear Suspend Bit
• Freeze USB clock
• Disable PLL
• Be sure to have interrupts enable to exit sleep mode
• Make the MCU enter sleep mode
Resuming the USB interface
• Enable PLL
• Wait PLL lock
• Unfreeze USB clock
• Clear Resume information262
7593L–AVR–09/12
AT90USB64/128
23. USB device operating modes
23.1 Introduction
The USB device controller supports full speed and low speed data transfers. In addition to the
default control endpoint, it provides six other endpoints, which can be configured in control, bulk,
interrupt or isochronous modes:
• Endpoint 0:programmable size FIFO up to 64 bytes, default control endpoint
• Endpoints 1 programmable size FIFO up to 256 bytes in ping-pong mode
• Endpoints 2 to 6: programmable size FIFO up to 64 bytes in ping-pong mode
The controller starts in the “idle” mode. In this mode, the pad consumption is reduced to the
minimum.
23.2 Power-on and reset
The next diagram explains the USB device controller main states on power-on:
Figure 23-1. USB device controller states after reset.
The reset state of the Device controller is:
• the macro clock is stopped in order to minimize the power consumption (FRZCLK set)
• the USB device controller internal state is reset (all the registers are reset to their default
value. Note that DETACH is set.)
• the endpoint banks are reset
• the D+ or D- pull up are not activated (mode Detach)
The D+ or D- pull-up will be activated as soon as the DETACH bit is cleared and VBUS is
present.
The macro is in the ‘Idle’ state after reset with a minimum power consumption and does not
need to have the PLL activated to enter in this state.
The USB device controller can at any time be reset by clearing USBE (disable USB interface).
23.3 Endpoint reset
An endpoint can be reset at any time by setting in the UERST register the bit corresponding to
the endpoint (EPRSTx). This resets:
• the internal state machine on that endpoint
• the Rx and Tx banks are cleared and their internal pointers are restored
Reset
Idle
HW
RESET
USBE=0
USBE=0
USBE=1
UID=1263
7593L–AVR–09/12
AT90USB64/128
• the UEINTX, UESTA0X and UESTA1X are restored to their reset value
The data toggle field remains unchanged.
The other registers remain unchanged.
The endpoint configuration remains active and the endpoint is still enabled.
The endpoint reset may be associated with a clear of the data toggle command (RSTDT bit) as
an answer to the CLEAR_FEATURE USB command.
23.4 USB reset
When an USB reset is detected on the USB line, the next operations are performed by the
controller:
• all the endpoints are disabled
• the default control endpoint remains configured (see Section 23.3, page 262 for more details)
23.5 Endpoint selection
Prior to any operation performed by the CPU, the endpoint must first be selected. This is done
by setting the EPNUM2:0 bits (UENUM register) with the endpoint number which will be managed
by the CPU.
The CPU can then access to the various endpoint registers and data.
23.6 Endpoint activation
The endpoint is maintained under reset as long as the EPEN bit is not set.
The following flow must be respected in order to activate an endpoint:264
7593L–AVR–09/12
AT90USB64/128
Figure 23-2. Endpoint activation flow.
As long as the endpoint is not correctly configured (CFGOK cleared), the hardware does not
acknowledge the packets sent by the host.
CFGOK is will not be sent if the Endpoint size parameter is bigger than the DPRAM size.
A clear of EPEN acts as an endpoint reset (see Section 23.3, page 262 for more details). It also
performs the next operation:
• The configuration of the endpoint is kept (EPSIZE, EPBK, ALLOC kept)
• It resets the data toggle field
• The DPRAM memory associated to the endpoint is still reserved
See Section 22.7, page 252 for more details about the memory allocation/reorganization.
23.7 Address setup
The USB device address is set up according to the USB protocol:
• the USB device, after power-up, responds at address 0
• the host sends a SETUP command (SET_ADDRESS(addr))
• the firmware records that address in UADD, but keep ADDEN cleared
• the USB device sends an IN command of 0 bytes (IN 0 Zero Length Packet)
• then, the firmware can enable the USB device address by setting ADDEN. The only accepted
address by the controller is the one stored in UADD
ADDEN and UADD shall not be written at the same time.
UADD contains the default address 00h after a power-up or USB reset.
Endpoint
Activation
CFGOK=1
ERROR
No
Yes
Endpoint activated
Activate the endpoint
Select the endpoint
EPEN=1
UENUM
EPNUM=x
Test the correct endpoint
configuration
UECFG1X ALLOC
EPSIZE
EPBK
Configure:
- the endpoint size
- the bank parametrization
Allocation and reorganization of
the memory is made on-the-fly
UECFG0X EPDIR
EPTYPE
...
Configure:
- the endpoint direction
- the endpoint type265
7593L–AVR–09/12
AT90USB64/128
ADDEN is cleared by hardware:
• after a power-up reset
• when an USB reset is received
• or when the macro is disabled (USBE cleared)
When this bit is cleared, the default device address 00h is used.
23.8 Suspend, wake-up and resume
After a period of 3ms during which the USB line was inactive, the controller switches to the fullspeed
mode and triggers (if enabled) the SUSPI (suspend) interrupt. The firmware may then set
the FRZCLK bit.
The CPU can also, depending on software architecture, enter in the idle mode to lower again the
power consumption.
There are two ways to recover from the “Suspend” mode:
• First one is to clear the FRZCLK bit. This is possible if the CPU is not in the Idle mode
• Second way, if the CPU is “idle”, is to enable the WAKEUPI interrupt (WAKEUPE set). Then,
as soon as an non-idle signal is seen by the controller, the WAKEUPI interrupt is triggered.
The firmware shall then clear the FRZCLK bit to restart the transfer
There are no relationship between the SUSPI interrupt and the WAKEUPI interrupt: the WAKEUPI
interrupt is triggered as soon as there are non-idle patterns on the data lines. Thus, the
WAKEUPI interrupt can occurs even if the controller is not in the “suspend” mode.
When the WAKEUPI interrupt is triggered, if the SUSPI interrupt bit was already set, it is cleared
by hardware.
When the SUSPI interrupt is triggered, if the WAKEUPI interrupt bit was already set, it is cleared
by hardware.
23.9 Detach
The reset value of the DETACH bit is 1.
It is possible to re-enumerate a device, simply by setting and clearing the DETACH bit.
• Setting DETACH will disconnect the pull-up on the D+ or D- pad (depending on full or low
speed mode selected). Then, clearing DETACH will connect the pull-up on the D+ or D- pad
Figure 23-3. Detach a device in full-speed.
EN=1
D +
UVREF
D -
Detach, then
Attach EN=1
D +
UVREF
D -266
7593L–AVR–09/12
AT90USB64/128
23.10 Remote Wake-up
The “Remote Wake-up” (or “upstream resume”) request is the only operation allowed to be sent
by the device on its own initiative. Anyway, to do that, the device should first have received a
DEVICE_REMOTE_WAKEUP request from the host.
• First, the USB controller must have detected the “suspend” state of the line: the remote wakeup
can only be sent when a SUSPI flag is set
• The firmware has then the ability to set RMWKUP to send the “upstream resume” stream.
This will automatically be done by the controller after 5ms of inactivity on the USB line
• When the controller starts to send the “upstream resume”, the UPRSMI interrupt is triggered
(if enabled). SUSPI is cleared by hardware
• RMWKUP is cleared by hardware at the end of the “upstream resume”
• If the controller detects a good “End Of Resume” signal from the host, an EORSMI interrupt
is triggered (if enabled)
23.11 STALL request
For each endpoint, the STALL management is performed using two bits:
– STALLRQ (enable stall request)
– STALLRQC (disable stall request)
– STALLEDI (stall sent interrupt)
To send a STALL handshake at the next request, the STALLRQ request bit has to be set. All following
requests will be handshak’ed with a STALL until the STALLRQC bit is set.
Setting STALLRQC automatically clears the STALLRQ bit. The STALLRQC bit is also immediately
cleared by hardware after being set by software. Thus, the firmware will never read this bit
as set.
Each time the STALL handshake is sent, the STALLEDI flag is set by the USB controller and the
EPINTx interrupt will be triggered (if enabled).
The incoming packets will be discarded (RXOUTI and RWAL will not be set).
The host will then send a command to reset the STALL: the firmware just has to set the STALLRQC
bit and to reset the endpoint.
23.11.1 Special consideration for control endpoints
A SETUP request is always ACK’ed.
If a STALL request is set for a Control Endpoint and if a SETUP request occurs, the SETUP
request has to be ACK’ed and the STALLRQ request and STALLEDI sent flags are automatically
reset (RXSETUPI set, TXIN cleared, STALLED cleared, TXINI cleared...).
This management simplifies the enumeration process management. If a command is not supported
or contains an error, the firmware set the STALL request flag and can return to the main
task, waiting for the next SETUP request.
This function is compliant with the Chapter 8 test that may send extra status for a
GET_DESCRIPTOR. The firmware sets the STALL request just after receiving the status. All
extra status will be automatically STALL’ed until the next SETUP request.267
7593L–AVR–09/12
AT90USB64/128
23.11.2 STALL handshake and retry mechanism
The Retry mechanism has priority over the STALL handshake. A STALL handshake is sent if the
STALLRQ request bit is set and if there is no retry required.
23.12 CONTROL endpoint management
A SETUP request is always ACK’ed. When a new setup packet is received, the RXSTPI interrupt
is triggered (if enabled). The RXOUTI interrupt is not triggered.
The FIFOCON and RWAL fields are irrelevant with CONTROL endpoints. The firmware shall
thus never use them on that endpoints. When read, their value is always 0.
CONTROL endpoints are managed by the following bits:
• RXSTPI is set when a new SETUP is received. It shall be cleared by firmware to
acknowledge the packet and to clear the endpoint bank
• RXOUTI is set when a new OUT data is received. It shall be cleared by firmware to
acknowledge the packet and to clear the endpoint bank
• TXINI is set when the bank is ready to accept a new IN packet. It shall be cleared by firmware
to send the packet and to clear the endpoint bank
23.12.1 Control write
Figure 23-4 shows a control write transaction. During the status stage, the controller will not necessary
send a NAK at the first IN token:
• If the firmware knows the exact number of descriptor bytes that must be read, it can then
anticipate on the status stage and send a ZLP for the next IN token
• or it can read the bytes and poll NAKINI, which tells that all the bytes have been sent by the
host, and the transaction is now in the status stage
Figure 23-4. Control write transaction.
23.12.2 Control read
Figure 23-5 on page 268 shows a control read transaction. The USB controller has to manage
the simultaneous write requests from the CPU and the USB host.
SETUP
RXSTPI
RXOUTI
TXINI
USB line
HW SW
OUT
HW SW
OUT
HW SW
IN IN
NAK
SW
SETUP STATUS DATA268
7593L–AVR–09/12
AT90USB64/128
Figure 23-5. Control read transaction.
A NAK handshake is always generated at the first status stage command.
When the controller detect the status stage, all the data writen by the CPU are erased, and
clearing TXINI has no effects.
The firmware checks if the transmission is complete or if the reception is complete.
The OUT retry is always ack’ed. This reception:
- set the RXOUTI flag (received OUT data)
- set the TXINI flag (data sent, ready to accept new data)
software algorithm:
set transmit ready
wait (transmit complete OR Receive complete)
if receive complete, clear flag and return
if transmit complete, continue
Once the OUT status stage has been received, the USB controller waits for a SETUP request.
The SETUP request have priority over any other request and has to be ACK’ed. This means that
any other flag should be cleared and the fifo reset when a SETUP is received.
WARNING: the byte counter is reset when the OUT Zero Length Packet is received. The firmware
has to take care of this.
23.13 OUT endpoint management
OUT packets are sent by the host. All the data can be read by the CPU, which acknowledges or
not the bank when it is empty.
23.13.1 Overview
The Endpoint must be configured first.
Each time the current bank is full, the RXOUTI and the FIFOCON bits are set. This triggers an
interrupt if the RXOUTE bit is set. The firmware can acknowledge the USB interrupt by clearing
the RXOUTI bit. The Firmware read the data and clear the FIFOCON bit in order to free the current
bank. If the OUT Endpoint is composed of multiple banks, clearing the FIFOCON bit will
switch to the next bank. The RXOUTI and FIFOCON bits are then updated by hardware in accordance
with the status of the new bank.
SETUP
RXSTPI
RXOUTI
TXINI
USB line
HW SW
IN
HW SW
IN OUT OUT
NAK
SW
SW
HW
Wr Enable
HOST
Wr Enable
CPU
SETUP STATUS DATA269
7593L–AVR–09/12
AT90USB64/128
RXOUTI shall always be cleared before clearing FIFOCON.
The RWAL bit always reflects the state of the current bank. This bit is set if the firmware can
read data from the bank, and cleared by hardware when the bank is empty.
Figure 23-6. Example with 1 and 2 OUT data bank.
23.13.2 Detailed description
The data are read by the CPU, following the next flow:
• When the bank is filled by the host, an endpoint interrupt (EPINTx) is triggered, if enabled
(RXOUTE set) and RXOUTI is set. The CPU can also poll RXOUTI or FIFOCON, depending
on the software architecture
• The CPU acknowledges the interrupt by clearing RXOUTI
• The CPU can read the number of byte (N) in the current bank (N=BYCT)
• The CPU can read the data from the current bank (“N” read of UEDATX)
• The CPU can free the bank by clearing FIFOCON when all the data is read, that is:
– after “N” read of UEDATX
– as soon as RWAL is cleared by hardware
If the endpoint uses two banks, the second one can be filled by the HOST while the current one
is being read by the CPU. Then, when the CPU clear FIFOCON, the next bank may be already
ready and RXOUTI is set immediately.
23.14 IN endpoint management
IN packets are sent by the USB device controller, upon an IN request from the host. All the data
can be written by the CPU, which acknowledge or not the bank when it is full.
OUT DATA
(to bank 0) ACK
RXOUTI
FIFOCON
HW
OUT DATA
(to bank 0) ACK
HW
SW
SW
SW
read data from CPU
BANK 0
OUT DATA
(to bank 0) ACK
RXOUTI
FIFOCON
HW
OUT DATA
(to bank 1) ACK
SW
SW
Example with 2 OUT data banks
read data from CPU
BANK 0
HW
SW
read data from CPU
BANK 0
read data from CPU
BANK 1
NAK270
7593L–AVR–09/12
AT90USB64/128
23.14.1 Overview
The Endpoint must be configured first.
The TXINI bit is set by hardware when the current bank becomes free. This triggers an interrupt
if the TXINE bit is set. The FIFOCON bit is set at the same time. The CPU writes into the FIFO
and clears the FIFOCON bit to allow the USB controller to send the data. If the IN Endpoint is
composed of multiple banks, this also switches to the next data bank. The TXINI and FIFOCON
bits are automatically updated by hardware regarding the status of the next bank.
TXINI shall always be cleared before clearing FIFOCON.
The RWAL bit always reflects the state of the current bank. This bit is set if the firmware can
write data to the bank, and cleared by hardware when the bank is full.
Figure 23-7. Example with 1 and 2 IN data bank.
23.14.2 Detailed description
The data are written by the CPU, following the next flow:
• When the bank is empty, an endpoint interrupt (EPINTx) is triggered, if enabled (TXINE set)
and TXINI is set. The CPU can also poll TXINI or FIFOCON, depending the software
architecture choice
• The CPU acknowledges the interrupt by clearing TXINI
• The CPU can write the data into the current bank (write in UEDATX)
• The CPU can free the bank by clearing FIFOCON when all the data are written, that is:
– after “N” write into UEDATX
– as soon as RWAL is cleared by hardware
IN DATA
(bank 0) ACK
TXINI
FIFOCON
HW
write data from CPU
BANK 0
Example with 2 IN data banks
SW
SW SW
SW
IN
IN DATA
(bank 0) ACK
TXINI
FIFOCON write data from CPU
BANK 0
SW
SW SW
SW
IN DATA
(bank 1) ACK
write data from CPU
BANK 0
write data from CPU
BANK 1
SW
HW
write data from CPU
BANK0
NAK271
7593L–AVR–09/12
AT90USB64/128
If the endpoint uses two banks, the second one can be read by the HOST while the current is
being written by the CPU. Then, when the CPU clears FIFOCON, the next bank may be already
ready (free) and TXINI is set immediately.
23.14.2.1 Abort
An “abort” stage can be produced by the host in some situations:
• In a control transaction: ZLP data OUT received during a IN stage
• In an isochronous IN transaction: ZLP data OUT received on the OUT endpoint during a IN
stage on the IN endpoint
• ...
The KILLBK bit is used to kill the last “written” bank. The best way to manage this abort is to perform
the following operations:
Table 23-1. Abort flow.
23.15 Isochronous mode
23.15.1 Underflow
An underflow can occur during IN stage if the host attempts to read a bank which is empty. In
this situation, the UNDERFI interrupt is triggered.
An underflow can also occur during OUT stage if the host send a packet while the banks are
already full. Typically, he CPU is not fast enough. The packet is lost.
It is not possible to have underflow error during OUT stage, in the CPU side, since the CPU
should read only if the bank is ready to give data (RXOUTI=1 or RWAL=1)
23.15.2 CRC error
A CRC error can occur during OUT stage if the USB controller detects a bad received packet. In
this situation, the STALLEDI interrupt is triggered. This does not prevent the RXOUTI interrupt
from being triggered.
Endpoint
Abort
Abort done
Abort is based on the fact
that no banks are busy,
meaning that nothing has to
be sent.
Disable the TXINI interrupt.
Endpoint
reset
NBUSYBK
=0
Yes
Clear
UEIENX.
TXINE
No
KILLBK=1
KILLBK=1 Yes
Kill the last written
bank.
Wait for the end of the
procedure.
No272
7593L–AVR–09/12
AT90USB64/128
23.16 Overflow
In Control, Isochronous, Bulk or Interrupt Endpoint, an overflow can occur during OUT stage, if
the host attempts to write in a bank that is too small for the packet. In this situation, the OVERFI
interrupt is triggered (if enabled). The packet is acknowledged and the RXOUTI interrupt is also
triggered (if enabled). The bank is filled with the first bytes of the packet.
It is not possible to have overflow error during IN stage, in the CPU side, since the CPU should
write only if the bank is ready to access data (TXINI=1 or RWAL=1).
23.17 Interrupts
Figure 23-8 shows all the interrupts sources.
Figure 23-8. USB device controller interrupt system.
There are two kinds of interrupts: processing (that is, their generation are part of the normal processing)
and exception (errors).
Processing interrupts are generated when:
• VBUS plug-in detection (insert, remove)(VBUSTI)
• Upstream resume(UPRSMI)
• End of resume(EORSMI)
• Wake up(WAKEUPI)
• End of reset (Speed Initialization)(EORSTI)
• Start of frame(SOFI, if FNCERR=0)
• Suspend detected after 3ms of inactivity(SUSPI)
Exception Interrupts are generated when:
• CRC error in frame number of SOF(SOFI, FNCERR=1)
UPRSMI
UDINT.6 UPRSME
UDIEN.6
EORSMI
UDINT.5 EORSME
UDIEN.5
WAKEUPI
UDINT.4 WAKEUPE
UDIEN.4
EORSTI
UDINT.3 EORSTE
UDIEN.3
SOFI
UDINT.2 SOFE
UDIEN.2
SUSPI
UDINT.0 SUSPE
UDIEN.0
USB device
interrupt273
7593L–AVR–09/12
AT90USB64/128
Figure 23-9. USB device controller endpoint interrupt system.
Processing interrupts are generated when:
• Ready to accept IN data(EPINTx, TXINI=1)
• Received OUT data(EPINTx, RXOUTI=1)
• Received SETUP(EPINTx, RXSTPI=1)
Exception Interrupts are generated when:
• Stalled packet(EPINTx, STALLEDI=1)
• CRC error on OUT in isochronous mode(EPINTx, STALLEDI=1)
• Overflow in isochronous mode(EPINTx, OVERFI=1)
• Underflow in isochronous mode(EPINTx, UNDERFI=1)
• NAK IN sent(EPINTx, NAKINI=1)
• NAK OUT sent(EPINTx, NAKOUTI=1)
23.18 Registers
23.18.1 USB device general registers
EPINT
UEINT.X
Endpoint 0
Endpoint 1
Endpoint 2
Endpoint 3
Endpoint 4
Endpoint 5
Endpoint interrupt
Endpoint 6
FLERRE
UEIENX.7
OVERFI
UESTAX.6
UNDERFI
UESTAX.5
NAKINI
UEINTX.6 NAKINE
UEIENX.6
NAKOUTI
UEINTX.4 TXSTPE
UEIENX.4
RXSTPI
UEINTX.3 TXOUTE
UEIENX.3
RXOUTI
UEINTX.2 RXOUTE
UEIENX.2
STALLEDI
UEINTX.1 STALLEDE
UEIENX.1
TXINI
UEINTX.0 TXINE
UEIENX.0
Bit 7 6 5 4 3 2 1 0
----- LSM RMWKUP DETACH UDCON
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 1274
7593L–AVR–09/12
AT90USB64/128
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2 - LSM - USB Device Low Speed Mode selection
When configured USB is configured in device mode, this bit allows to select the USB the USB
Low Speed or Full Speed Mod.
Clear to select full speed mode (D+ internal pull-up will be activate with the ATTACH bit will be
set) .
Set to select low speed mode (D- internal pull-up will be activate with the ATTACH bit will be
set). This bit has no effect when the USB interface is configured in HOST mode.
• 1- RMWKUP - Remote Wake-up bit
Set to send an “upstream-resume” to the host for a remote wake-up (the SUSPI bit must be set).
Cleared by hardware when signalling finished. Clearing by software has no effect.
See Section 23.10, page 266 for more details.
• 0 - DETACH - Detach bit
Set to physically detach de device (disconnect internal pull-up on D+ or D-).
Clear to reconnect the device. See Section 23.9, page 265 for more details.
• 7 - Reserved
The value read from this bits is always 0. Do not set this bit.
• 6 - UPRSMI - Upstream Resume Interrupt flag
Set by hardware when the USB controller is sending a resume signal called “Upstream
Resume”. This triggers an USB interrupt if UPRSME is set.
Shall be cleared by software (USB clocks must be enabled before). Setting by software has no
effect.
• 5 - EORSMI - End Of Resume Interrupt flag
Set by hardware when the USB controller detects a good “End Of Resume” signal initiated by
the host. This triggers an USB interrupt if EORSME is set.
Shall be cleared by software. Setting by software has no effect.
• 4 - WAKEUPI - Wake-up CPU Interrupt flag
Set by hardware when the USB controller is re-activated by a filtered non-idle signal from the
lines (not by an upstream resume). This triggers an interrupt if WAKEUPE is set. This interrupt
should be enable only to wake up the CPU core from power down mode.
Shall be cleared by software (USB clock inputs must be enabled before). Setting by software
has no effect.
See Section 23.8, page 265 for more details.
Bit 7 6 5 4 3 2 1 0
- UPRSMI EORSMI WAKEUPI EORSTI SOFI - SUSPI UDINT
Read/write
Initial value 0 0 0 0 0 0 0 0275
7593L–AVR–09/12
AT90USB64/128
• 3 - EORSTI - End Of Reset Interrupt flag
Set by hardware when an “End Of Reset” has been detected by the USB controller. This triggers
an USB interrupt if EORSTE is set.
Shall be cleared by software. Setting by software has no effect.
• 2 - SOFI - Start Of Frame Interrupt flag
Set by hardware when an USB “Start Of Frame” PID (SOF) has been detected (every 1ms). This
triggers an USB interrupt if SOFE is set.
• 1 - Reserved
The value read from this bits is always 0. Do not set this bit
• 0 - SUSPI - Suspend Interrupt flag
Set by hardware when an USB “Suspend” ‘idle bus for three frame periods: a J state for 3ms) is
detected. This triggers an USB interrupt if SUSPE is set.
Shall be cleared by software. Setting by software has no effect.
See Section 23.8, page 265 for more details.
The interrupt bits are set even if their corresponding ‘Enable’ bits is not set.
• 7 - Reserved
The value read from this bits is always 0. Do not set this bit.
• 6 - UPRSME - Upstream Resume Interrupt Enable bit
Set to enable the UPRSMI interrupt.
Clear to disable the UPRSMI interrupt.
• 5 - EORSME - End Of Resume Interrupt Enable bit
Set to enable the EORSMI interrupt.
Clear to disable the EORSMI interrupt.
• 4 - WAKEUPE - Wake-up CPU Interrupt Enable bit
Set to enable the WAKEUPI interrupt. For correct interrupt handle execution, this interrupt
should be enable only before entering power-down mode.
Clear to disable the WAKEUPI interrupt.
• 3 - EORSTE - End Of Reset Interrupt Enable bit
Set to enable the EORSTI interrupt. This bit is set after a reset.
Clear to disable the EORSTI interrupt.
• 2 - SOFE - Start Of Frame Interrupt Enable bit
Set to enable the SOFI interrupt.
Clear to disable the SOFI interrupt.
Bit 7 6 5 4 3 2 1 0
- UPRSME EORSME WAKEUPE EORSTE SOFE - SUSPE UDIEN
Read/write
Initial value 0 0 0 0 0 0 0 0276
7593L–AVR–09/12
AT90USB64/128
• 1 - Reserved
The value read from this bits is always 0. Do not set this bit
• 0 - SUSPE - Suspend Interrupt Enable Bit
Set to enable the SUSPI interrupt.
Clear to disable the SUSPI interrupt.
• 7 - ADDEN - Address Enable Bit
Set to activate the UADD (USB address).
Cleared by hardware. Clearing by software has no effect.
See Section 23.7, page 264 for more details.
• 6-0 - UADD6:0 - USB Address Bits
Load by software to configure the device address.
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2-0 - FNUM10:8 - Frame Number Upper Value
Set by hardware. These bits are the three MSB of the 11-bits Frame Number information. They
are provided in the last received SOF packet. FNUM is updated if a corrupted SOF is received.
• Frame Number Lower Value
Set by hardware. These bits are the eight LSB of the 11-bits Frame Number information.
• 7-5 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 4 - FNCERR -Frame Number CRC Error flag
Set by hardware when a corrupted Frame Number in start of frame packet is received.
This bit and the SOFI interrupt are updated at the same time.
Bit 7 6 5 4 3 2 1 0
ADDEN UADD6:0 UDADDR
Read/write W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - - - - FNUM10:8 UDFNUMH
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
FNUM7:0 UDFNUML
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - - FNCERR - - - - UDMFN
Read/write R
Initial value 0 0 0 0 0 0 0 0277
7593L–AVR–09/12
AT90USB64/128
• 3-0 - Reserved
The value read from these bits is always 0. Do not set these bits.
23.18.2 USB device endpoint registers
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2-0 - EPNUM2:0 Endpoint Number bits
Load by software to select the number of the endpoint which shall be accessed by the CPU. See
Section 23.5, page 263 for more details.
EPNUM = 111b is forbidden.
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-0 - EPRST6:0 - Endpoint FIFO Reset bits
Set to reset the selected endpoint FIFO prior to any other operation, upon hardware reset or
when an USB bus reset has been received. See Section 23.3, page 262 for more information
Then, clear by software to complete the reset operation and start using the endpoint.
• 7-6 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 5 - STALLRQ - STALL Request Handshake bit
Set to request a STALL answer to the host for the next handshake.
Cleared by hardware when a new SETUP is received. Clearing by software has no effect.
See Section 23.11, page 266 for more details.
• 4 - STALLRQC - STALL Request Clear Handshake bit
Set to disable the STALL handshake mechanism.
Cleared by hardware immediately after the set. Clearing by software has no effect.
See Section 23.11, page 266 for more details.
Bit 7 6 5 4 3 2 1 0
- - - - - EPNUM2:0 UENUM
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- EPRST6 EPRST5 EPRST4 EPRST3 EPRST2 EPRST1 EPRST0 UERST
Read/write R R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - STALLRQ STALLRQC RSTDT - - EPEN UECONX
Read/write R R W W W R R R/W
Initial value 0 0 0 0 0 0 0 0278
7593L–AVR–09/12
AT90USB64/128
• RSTDT - Reset Data Toggle bit
Set to automatically clear the data toggle sequence:
For OUT endpoint: the next received packet will have the data toggle 0.
For IN endpoint: the next packet to be sent will have the data toggle 0.
Cleared by hardware instantaneously. The firmware does not have to wait that the bit is cleared.
Clearing by software has no effect.
• 2 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 1 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 0 - EPEN - Endpoint Enable bit
Set to enable the endpoint according to the device configuration. Endpoint 0 shall always be
enabled after a hardware or USB reset and participate in the device configuration.
Clear this bit to disable the endpoint. See Section 23.6, page 263 for more details.
• 7-6 - EPTYPE1:0 - Endpoint Type bits
Set this bit according to the endpoint configuration:
00b: Control10b: Bulk
01b: Isochronous11b: Interrupt
• 5-4 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 3-2 - Reserved for test purpose
The value read from these bits is always 0. Do not set these bits.
• 1 - Reserved
The value read from this bits is always 0. Do not set this bit.
• 0 - EPDIR - Endpoint Direction bit
Set to configure an IN direction for bulk, interrupt or isochronous endpoints.
Clear to configure an OUT direction for bulk, interrupt, isochronous or control endpoints.
Bit 7 6 5 4 3 2 1 0
EPTYPE1:0 - - - - - EPDIR UECFG0X
Read/write R/W R/W R R R R R R/W
Initial value 0 0 0 0 0 0 0 0279
7593L–AVR–09/12
AT90USB64/128
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-4 - EPSIZE2:0 - Endpoint Size bits
Set this bit according to the endpoint size:
000b: 8 bytes 100b: 128 bytes (only for endpoint 1)
001b: 16 bytes 101b: 256 bytes (only for endpoint 1)
010b: 32 bytes 110b: Reserved. Do not use this configuration
011b: 64 bytes 111b: Reserved. Do not use this configuration
• 3-2 - EPBK1:0 - Endpoint Bank bits
Set this field according to the endpoint size:
00b: One bank
01b: Double bank
1xb: Reserved. Do not use this configuration
• 1 - ALLOC - Endpoint Allocation bit
Set this bit to allocate the endpoint memory.
Clear to free the endpoint memory.
See Section 23.6, page 263 for more details.
• 0 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 7 - CFGOK - Configuration Status flag
Set by hardware when the endpoint X size parameter (EPSIZE) and the bank parametrization
(EPBK) are correct compared to the max FIFO capacity and the max number of allowed bank.
This bit is updated when the bit ALLOC is set.
If this bit is cleared, the user should reprogram the UECFG1X register with correct EPSIZE and
EPBK values.
Bit 7 6 5 4 3 2 1 0
- EPSIZE2:0 EPBK1:0 ALLOC - UECFG1X
Read/write R R/W R/W R/W R/W R/W R/W R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
CFGOK OVERFI UNDERFI - DTSEQ1:0 NBUSYBK1:0 UESTA0X
Read/write R R/W R/W R/W R R R R
Initial value 0 0 0 0 0 0 0 0280
7593L–AVR–09/12
AT90USB64/128
• 6 - OVERFI - Overflow Error Interrupt flag
Set by hardware when an overflow error occurs in an isochronous endpoint. An interrupt
(EPINTx) is triggered (if enabled).
See Section 23.15, page 271 for more details.
Shall be cleared by software. Setting by software has no effect.
• 5 - UNDERFI - Flow Error Interrupt flag
Set by hardware when an underflow error occurs in an isochronous endpoint. An interrupt
(EPINTx) is triggered (if enabled).
See Section 23.15, page 271 for more details.
Shall be cleared by software. Setting by software has no effect.
• 4 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 3-2 - DTSEQ1:0 - Data Toggle Sequencing flag
Set by hardware to indicate the PID data of the current bank:
00b Data0
01b Data1
1xb Reserved
For OUT transfer, this value indicates the last data toggle received on the current bank.
For IN transfer, it indicates the Toggle that will be used for the next packet to be sent. This is not
relative to the current bank.
• 1-0 - NBUSYBK1:0 - Busy Bank flag
Set by hardware to indicate the number of busy bank.
For IN endpoint, it indicates the number of busy bank(s), filled by the user, ready for IN transfer.
For OUT endpoint, it indicates the number of busy bank(s) filled by OUT transaction from the
host.
00b All banks are free
01b One busy bank
10b Two busy banks
11b Reserved
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
Bit 7 6 5 4 3 2 1 0
- - - - - CTRLDIR CURRBK1:0 UESTA1X
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0281
7593L–AVR–09/12
AT90USB64/128
• 2 - CTRLDIR - Control Direction (flag, and bit for debug purpose)
Set by hardware after a SETUP packet, and gives the direction of the following packet:
- 1 for IN endpoint
- 0 for OUT endpoint
Can not be set or cleared by software.
• 1-0 - CURRBK1:0 - Current Bank (all endpoints except Control endpoint) flag
Set by hardware to indicate the number of the current bank:
00b Bank0
01b Bank1
1xb Reserved
Can not be set or cleared by software.
• 7 - FIFOCON - FIFO Control bit
For OUT and SETUP Endpoint:
Set by hardware when a new OUT message is stored in the current bank, at the same time than
RXOUT or RXSTP.
Clear to free the current bank and to switch to the following bank. Setting by software has no
effect.
For IN Endpoint:
Set by hardware when the current bank is free, at the same time than TXIN.
Clear to send the FIFO data and to switch the bank. Setting by software has no effect.
• 6 - NAKINI - NAK IN Received Interrupt flag
Set by hardware when a NAK handshake has been sent in response of a IN request from the
host. This triggers an USB interrupt if NAKINE is sent.
Shall be cleared by software. Setting by software has no effect.
• 5 - RWAL - Read/Write Allowed flag
Set by hardware to signal:
- for an IN endpoint: the current bank is not full, that is, the firmware can push data into the FIFO,
- for an OUT endpoint: the current bank is not empty, that is, the firmware can read data from the
FIFO.
The bit is never set if STALLRQ is set, or in case of error.
Cleared by hardware otherwise.
This bit shall not be used for the control endpoint.
Bit 7 6 5 4 3 2 1 0
FIFOCON NAKINI RWAL NAKOUTI RXSTPI RXOUTI STALLEDI TXINI UEINTX
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0282
7593L–AVR–09/12
AT90USB64/128
• 4 - NAKOUTI - NAK OUT Received Interrupt flag
Set by hardware when a NAK handshake has been sent in response of a OUT/PING request
from the host. This triggers an USB interrupt if NAKOUTE is sent.
Shall be cleared by software. Setting by software has no effect.
• 3 - RXSTPI - Received SETUP Interrupt flag
Set by hardware to signal that the current bank contains a new valid SETUP packet. An interrupt
(EPINTx) is triggered (if enabled).
Shall be cleared by software to handshake the interrupt. Setting by software has no effect.
This bit is inactive (cleared) if the endpoint is an IN endpoint.
• 2 - RXOUTI / KILLBK - Received OUT Data Interrupt flag
Set by hardware to signal that the current bank contains a new packet. An interrupt (EPINTx) is
triggered (if enabled).
Shall be cleared by software to handshake the interrupt. Setting by software has no effect.
Kill Bank IN bit
Set this bit to kill the last written bank.
Cleared by hardware when the bank is killed. Clearing by software has no effect.
See page 271 for more details on the Abort.
• 1 - STALLEDI - STALLEDI Interrupt flag
Set by hardware to signal that a STALL handshake has been sent, or that a CRC error has been
detected in a OUT isochronous endpoint.
Shall be cleared by software. Setting by software has no effect.
• 0 - TXINI - Transmitter Ready Interrupt flag
Set by hardware to signal that the current bank is free and can be filled. An interrupt (EPINTx) is
triggered (if enabled).
Shall be cleared by software to handshake the interrupt. Setting by software has no effect.
This bit is inactive (cleared) if the endpoint is an OUT endpoint.
• 7 - FLERRE - Flow Error Interrupt Enable flag
Set to enable an endpoint interrupt (EPINTx) when OVERFI or UNDERFI are sent.
Clear to disable an endpoint interrupt (EPINTx) when OVERFI or UNDERFI are sent.
• 6 - NAKINE - NAK IN Interrupt Enable bit
Set to enable an endpoint interrupt (EPINTx) when NAKINI is set.
Clear to disable an endpoint interrupt (EPINTx) when NAKINI is set.
Bit 7 6 5 4 3 2 1 0
FLERRE NAKINE - NAKOUTE RXSTPE RXOUTE STALLEDE TXINE UEIENX
Read/write R/W R/W R R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0283
7593L–AVR–09/12
AT90USB64/128
• 5 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 4 - NAKOUTE - NAK OUT Interrupt Enable bit
Set to enable an endpoint interrupt (EPINTx) when NAKOUTI is set.
Clear to disable an endpoint interrupt (EPINTx) when NAKOUTI is set.
• 3 - RXSTPE - Received SETUP Interrupt Enable flag
Set to enable an endpoint interrupt (EPINTx) when RXSTPI is sent.
Clear to disable an endpoint interrupt (EPINTx) when RXSTPI is sent.
• 2 - RXOUTE - Received OUT Data Interrupt Enable flag
Set to enable an endpoint interrupt (EPINTx) when RXOUTI is sent.
Clear to disable an endpoint interrupt (EPINTx) when RXOUTI is sent.
• 1 - STALLEDE - Stalled Interrupt Enable flag
Set to enable an endpoint interrupt (EPINTx) when STALLEDI is sent.
Clear to disable an endpoint interrupt (EPINTx) when STALLEDI is sent.
• 0 - TXINE - Transmitter Ready Interrupt Enable flag
Set to enable an endpoint interrupt (EPINTx) when TXINI is sent.
Clear to disable an endpoint interrupt (EPINTx) when TXINI is sent.
• 7-0 - DAT7:0 -Data bits
Set by the software to read/write a byte from/to the endpoint FIFO selected by EPNUM.
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2-0 - BYCT10:8 - Byte count (high) bits
Set by hardware. This field is the MSB of the byte count of the FIFO endpoint. The LSB part is
provided by the UEBCLX register.
Bit 7 6 5 4 3 2 1 0
DAT D7 DAT D6 DAT D5 DAT D4 DAT D3 DAT D2 DAT D1 DAT D0 UEDATX
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - - - - BYCT D10 BYCT D9 BYCT D8 UEBCHX
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0284
7593L–AVR–09/12
AT90USB64/128
• 7-0 - BYCT7:0 - Byte Count (low) bits
Set by the hardware. BYCT10:0 is:
- (for IN endpoint) increased after each writing into the endpoint and decremented after each
byte sent,
- (for OUT endpoint) increased after each byte sent by the host, and decremented after each
byte read by the software.
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-0 - EPINT6:0 - Endpoint Interrupts bits
Set by hardware when an interrupt is triggered by the UEINTX register and if the corresponding
endpoint interrupt enable bit is set.
Cleared by hardware when the interrupt source is served.
Bit 7 6 5 4 3 2 1 0
BYCT D7 BYCT D6 BYCT D5 BYCT D4 BYCT D3 BYCT D2 BYCT D1 BYCT D0 UEBCLX
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- EPINT D6 EPINT D5 EPINT D4 EPINT D3 EPINT D2 EPINT D1 EPINT D0 UEINT
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0285
7593L–AVR–09/12
AT90USB64/128
24. USB host operating modes
This mode is available only on Atmel AT90USB647/1287 products.
24.1 Pipe description
For the USB Host controller, the term of Pipe is used instead of Endpoint for the USB Device
controller. A Host Pipe corresponds to a Device Endpoint, as described in the USB specification.
Figure 24-1. Pipes and endpoints in a USB system.
In the USB Host controller, a Pipe will be associated to a Device Endpoint, considering the
Device Configuration Descriptors.
24.2 Detach
The reset value of the DETACH bit is 1. Thus, the firmware has the responsibility of clearing this
bit before switching to the Host mode (HOST set).
24.3 Power-on and reset
Figure 24-2 explains the USB host controller main states on power-on.
Figure 24-2. USB host controller states after reset.
Host
Ready
Host
Idle
Device
disconnection
Device
connection
Clock stopped
Macro off
Device
disconnection
Host
Suspend
SOFE=1
SOFE=0286
7593L–AVR–09/12
AT90USB64/128
USB host controller state after an hardware reset is ‘Reset’. When the USB controller is enabled
and the USB Host controller is selected, the USB controller is in ‘Idle’ state. In this state, the
USB Host controller waits for the Device connection, with a minimum power consumption.
The USB Pad should be in Idle mode. The macro does not need to have the PLL activated to
enter in ‘Host Ready’ state.
The Host controller enters in Suspend state when the USB bus is in Suspend state, that is, when
the Host controller doesn’t generate the Start of Frame. In this state, the USB consumption is
minimum. The Host controller exits to the Suspend state when starting to generate the SOF over
the USB line.
24.4 Device detection
A Device is detected by the USB controller when the USB bus if different from D+ and D- low. In
other words, when the USB Host Controller detects the Device pull-up on the D+ line. To enable
this detection, the Host Controller has to provide the Vbus power supply to the Device.
The Device Disconnection is detected by the USB Host controller when the USB Idle correspond
to D+ and D- low on the USB line.
24.5 Pipe selection
Prior to any operation performed by the CPU, the Pipe must first be selected. This is done by
setting PNUM2:0 bits (UPNUM register) with the Pipe number which will be managed by the
CPU.
The CPU can then access to the various Pipe registers and data.
24.6 Pipe configuration
The following flow (see Figure 24-3 on page 287) must be respected in order to activate a Pipe.287
7593L–AVR–09/12
AT90USB64/128
Figure 24-3. Pipe activation flow.
Once the Pipe is activated (EPEN set) and, the hardware is ready to send requests to the
Device.
When configured (CFGOK = 1), only the Pipe Token (PTOKEN) and the polling interval for Interrupt
pipe can be modified.
A Control type pipe supports only one bank. Any other value will lead to a configuration error
(CFGOK = 0).
A clear of PEN will reset the configuration of the Pipe. All the corresponding Pipe registers are
reset to there reset values. Please refer to “Memory management” on page 252 for more details.
Note: The firmware has to configure the Default Control Pipe with the following parameters:
• Type: Control
• Token: SETUP
• Data bank: 1
• Size: 64 Bytes
The firmware asks for eight bytes of the Device Descriptor sending a GET_DESCRIPTOR
request. These bytes contains the MaxPacketSize of the Device default control endpoint and the
firmware re-configures the size of the Default Control Pipe with this size parameter.
Pipe
Activ ation
UPCONX
PENABLE=1
UPCFG0X PTYPE
PTOKEN
PEPNUM
CFGOK=1
ERROR
No
Yes
UPCFG2X
INTFRQ
(interrupt only)
Pipe activ ated
and f reezed
UPCFG1X
PSIZE
PBK
CFGMEM
Enable the pipe
Select the Pipe type:
* Type (Control, Bulk, Interrupt)
* Token (IN, OUT, SETUP)
* Endpoint number
Configure the Pipe memory:
* Pipe size
* Number of banks
Configure the polling interval
for Interrupt pipe288
7593L–AVR–09/12
AT90USB64/128
24.7 USB reset
The USB controller sends a USB Reset when the firmware set the RESET bit. The RSTI bit is
set by hardware when the USB Reset has been sent. This triggers an interrupt if the RSTE has
been set.
When a USB Reset has been sent, all the Pipe configuration and the memory allocation are
reset. The General Host interrupt enable register is left unchanged.
If the bus was previously in suspend mode (SOFEN = 0), the USB controller automatically
switches to the resume mode (HWUPI is set) and the SOFEN bit is set by hardware in order to
generate SOF immediately after the USB Reset.
24.8 Address setup
Once the Device has answer to the first Host requests with the default address (0), the Host
assigns a new address to the device. The Host controller has to send a USB reset to the device
and perform a SET ADDRESS control request, with the new address to be used by the Device.
This control request ended, the firmware write the new address into the UHADDR register. All
following requests, on every Pipes, will be performed using this new address.
When the Host controller send a USB reset, the UHADDR register is reset by hardware and the
following Host requests will be performed using the default address (0).
24.9 Remote wake-up detection
The Host Controller enters in Suspend mode when clearing the SOFEN bit. No more Start Of
Frame is sent on the USB bus and the USB Device enters in Suspend mode 3ms later.
The Device awakes the Host Controller by sending an Upstream Resume (Remote Wake-Up
feature). The Host Controller detects a non-idle state on the USB bus and set the HWUPI bit. If
the non-Idle correspond to an Upstream Resume (K state), the RXRSMI bit is set by hardware.
The firmware has to generate a downstream resume within 1ms and for at least 20ms by setting
the RESUME bit.
Once the downstream Resume has been generated, the SOFEN bit is automatically set by hardware
in order to generate SOF immediately after the USB resume.
24.10 USB pipe reset
The firmware can reset a Pipe using the pipe reset register. The configuration of the pipe and
the data toggle remains unchanged. Only the bank management and the status bits are reset to
their initial values.
To completely reset a Pipe, the firmware has to disable and then enable the pipe.
24.11 Pipe data access
In order to read or to write into the Pipe Fifo, the CPU selects the Pipe number with the UPNUM
register and performs read or write action on the UPDATX register.
Host
Ready
Host
Suspend
SOFE=1
or HWUP=1
SOFE=0289
7593L–AVR–09/12
AT90USB64/128
24.12 Control pipe management
A Control transaction is composed of three phases:
• SETUP
• Data (IN or OUT)
• Status (OUT or IN)
The firmware has to change the Token for each phase.
The initial data toggle is set for the corresponding token (ONLY for Control Pipe):
• SETUP: Data0
• OUT: Data1
• IN: Data1 (expected data toggle)
24.13 OUT pipe management
The Pipe must be configured and not frozen first.
Note: if the firmware decides to switch to suspend mode (clear SOFEN) even if a bank is ready
to be sent, the USB controller will automatically exit from Suspend mode and the bank will be
sent.
The TXOUT bit is set by hardware when the current bank becomes free. This triggers an interrupt
if the TXOUTE bit is set. The FIFOCON bit is set at the same time. The CPU writes into the
FIFO and clears the FIFOCON bit to allow the USB controller to send the data.
If the OUT Pipe is composed of multiple banks, this also switches to the next data bank. The
TXOUT and FIFOCON bits are automatically updated by hardware regarding the status of the
next bank.290
7593L–AVR–09/12
AT90USB64/128
Figure 24-4. Example with OUT data banks.
24.14 IN Pipe management
The Pipe must be configured first.
When the Host requires data from the device, the firmware has to determine first the IN mode to
use using the INMODE bit:
• INMODE = 0. The INRQX register is taken in account. The Host controller will perform
(INRQX+1) IN requests on the selected Pipe before freezing the Pipe. This mode avoids to
have extra IN requests on a Pipe
• INMODE = 1. The USB controller will perform infinite IN request until the firmware freezes the
Pipe
The IN request generation will start when the firmware clear the PFREEZE bit.
Each time the current bank is full, the RXIN and the FIFOCON bits are set. This triggers an interrupt
if the RXINE bit is set. The firmware can acknowledge the USB interrupt by clearing the
RXIN bit. The Firmware read the data and clear the FIFOCON bit in order to free the current
OUT DATA
(bank 0) ACK
TXOUT
FIFOCON
HW
Example with 1 OUT data bank
write data from CPU
BANK 0
Example with 2 OUT data banks
SW
SW SW
SW
OUT
OUT DATA
(bank 0) ACK
TXOUT
FIFOCON
write data from CPU
BANK 0
SW
SW SW
SW
OUT DATA
(bank 1) ACK
write data from CPU
BANK 0
write data from CPU
BANK 1
SW
HW
write data from CPU
BANK0
Example with 2 OUT data banks
OUT DATA
(bank 0) ACK
TXOUT
FIFOCON
write data from CPU
BANK 0
SW
SW SW
write data from CPU SW
BANK 1
SW
HW
write data from CPU
BANK0
OUT DATA
(bank 1) ACK291
7593L–AVR–09/12
AT90USB64/128
bank. If the IN Pipe is composed of multiple banks, clearing the FIFOCON bit will switch to the
next bank. The RXIN and FIFOCON bits are then updated by hardware in accordance with the
status of the new bank.
Figure 24-5. Example with IN data banks.
24.14.1 CRC error (isochronous only)
A CRC error can occur during IN stage if the USB controller detects a bad received packet. In
this situation, the STALLEDI/CRCERRI interrupt is triggered. This does not prevent the RXINI
interrupt from being triggered.
24.15 Interrupt system
Figure 24-6. USB host controller interrupt system.
IN DATA
(to bank 0) ACK
RXIN
FIFOCON
HW
IN DATA
(to bank 0) ACK
HW
SW
SW
SW
Example with 1 IN data bank
read data from CPU
BANK 0
IN DATA
(to bank 0) ACK
RXIN
FIFOCON
HW
IN DATA
(to bank 1) ACK
SW
SW
Example with 2 IN data banks
read data from CPU
BANK 0
HW
SW
read data from CPU
BANK 0
read data from CPU
BANK 1
HWUPE
UHIEN.6
HWUPI
UHINT.6
HSOFI
UHINT.5 HSOFE
UHIEN.5
RXRSMI
UHINT.4 RXRSME
UHIEN.4
RSMEDI
UHINT.3 RSMEDE
UHIEN.3
RSTI
UHINT.2 RSTE
UHIEN.2
DDISCI
UHINT.1 DDISCE
UHIEN.1
DCONNI
UHINT.0 DCONNE
UHIEN.0
USB host
interrupt292
7593L–AVR–09/12
AT90USB64/128
Figure 24-7. USB device controller pipe interrupt system.
24.16 Registers
24.16.1 General USB host registers
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2 - RESUME - Send USB Resume
Set this bit to generate a USB Resume on the USB bus.
Cleared by hardware when the USB Resume has been sent. Clearing by software has no effect.
This bit should be set only when the start of frame generation is enable (SOFEN bit set).
• 1 - RESET - Send USB Reset
Set this bit to generate a USB Reset on the USB bus.
Cleared by hardware when the USB Reset has been sent. Clearing by software has no effect.
Refer to the USB reset section for more details.
• 0 - SOFEN - Start Of Frame Generation Enable
Set this bit to generate SOF on the USB bus in full speed mode and keep-alive in low speed
mode.
Clear this bit to disable the SOF generation and to leave the USB bus in Idle state.
FLERRE
UPIEN.7
UNDERFI
UPSTAX.5
OVERFI
UPSTAX.6
NAKEDI
UPINTX.6 NAKEDE
UPIEN.6
PERRI
UPINTX.4 PERRE
UPIEN.4
TXSTPI
UPINTX.3 TXSTPE
UPIEN.3
TXOUTI
UPINTX.2 TXOUTE
UPIEN.2
RXSTALLI
UPINTX.1 RXSTALLE
UPIEN.1
RXINI
UPINTX.0 RXINE
UPIEN.0
FLERRE
UPIEN.7
PIPE 0
PIPE 1
PIPE 2
PIPE 3
PIPE 4
PIPE 5
Pipe interrupt
PIPE 6
Bit 7 6 5 4 3 2 1 0
----- RESUME RESET SOFEN UHCON
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0293
7593L–AVR–09/12
AT90USB64/128
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6 - HWUPI - Host Wake-Up Interrupt
Set by hardware when a non-idle state is detected on the USB bus.This interrupt should be
enable only to wake up the CPU core from power down mode.
Shall be clear by software to acknowledge the interrupt. Setting by software has no effect.
• 5 - HSOFI - Host Start Of Frame Interrupt
Set by hardware when a SOF is issued by the Host controller. This triggers a USB interrupt
when HSOFE is set. When using the host controller in low speed mode, this bit is also set when
a keep-alive is sent.
Shall be cleared by software to acknowledge the interrupt. Setting by software has no effect.
• 4 - RXRSMI - Upstream Resume Received Interrupt
Set by hardware when an Upstream Resume has been received from the Device.
Shall be cleared by software. Setting by software has no effect.
• 3 - RSMEDI - Downstream Resume Sent Interrupt
Set by hardware when a Downstream Resume has been sent to the Device.
Shall be cleared by software. Setting by software has no effect.
• 2 - RSTI - USB Reset Sent Interrupt
Set by hardware when a USB Reset has been sent to the Device.
Shall be cleared by software. Setting by software has no effect.
• 1 - DDISCI - Device Disconnection Interrupt
Set by hardware when the device has been removed from the USB bus.
Shall be cleared by software. Setting by software has no effect.
• 0 - DCONNI - Device Connection Interrupt
Set by hardware when a new device has been connected to the USB bus.
Shall be cleared by software. Setting by software has no effect.
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
Bit 7 6 5 4 3 2 1 0
- HWUPI HSOFI RXRSMI RSMEDI RSTI DDISCI DCONNI UHINT
Read/write R R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
HWUPE HSOFE RXRSME RSMEDE RSTE DDISCE DCONNE UHIEN
Read/write R R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0294
7593L–AVR–09/12
AT90USB64/128
• 6 - HWUPE - Host Wake-Up Interrupt Enable
Set this bit to enable HWUP interrupt.For correct interrupt handle execution, this interrupt should
be enable only before entering power-down mode.
Clear this bit to disable HWUP interrupt.
• 5 - HSOFE - Host Start Of frame Interrupt Enable
Set this bit to enable HSOF interrupt.
Clear this bit to disable HSOF interrupt.
• 4 - RXRSME -Upstream Resume Received Interrupt Enable
Set this bit to enable the RXRSMI interrupt.
Clear this bit to disable the RXRSMI interrupt.
• 3 - RSMEDE - Downstream Resume Sent Interrupt Enable
Set this bit to enable the RSMEDI interrupt.
Clear this bit to disable the RSMEDI interrupt.
• 2 - RSTE - USB Reset Sent Interrupt Enable
Set this bit to enable the RSTI interrupt.
Clear this bit to disable the RSTI interrupt.
• 1 - DDISCE - Device Disconnection Interrupt Enable
Set this bit to enable the DDISCI interrupt.
Clear this bit to disable the DDISCI interrupt.
• 0 - DCONNE - Device Connection Interrupt Enable
Set this bit to enable the DCONNI interrupt.
Clear this bit to disable the DCONNI interrupt.
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-0 - HADDR6:0 - USB Host Address
These bits contain the address of the USB Device.
Bit 7 6 5 4 3 2 1 0
HADDR6 HADDR5 HADDR4 HADDR3 HADDR2 HADDR1 HADDR0 HADDR6 UHADDR
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0295
7593L–AVR–09/12
AT90USB64/128
• 7-4 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 3-0 - FNUM10:8 - Frame Number
The value contained in this register is the current SOF number.
This value can be modified by software.
• 7-0 - FNUM7:0 - Frame Number
The value contained in this register is the current SOF number.
This value can be modified by software.
• 7-0 - FLEN7:0 - Frame Length
The value contained the data frame length transmited.
24.16.2 USB Host Pipe registers
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2-0 - PNUM2:0 - Pipe Number
Select the pipe using this register. The USB Host registers ended by a X correspond then to this
number.
This number is used for the USB controller following the value of the PNUMD bit.
Bit 7 6 5 4 3 2 1 0
- - - - - FNUM10 FNUM9 FNUM8 UHFNUMH
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
FNUM7 FNUM6 FNUM5 FNUM4 FNUM3 FNUM2 FNUM1 FNUM0 UHFNUML
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
FLEN7 FLEN6 FLEN5 FLEN4 FLEN3 FLEN2 FLEN1 FLEN0 UHFLEN
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
PNUM2 PNUM1 PNUM0 UPNUM
Read/write RW RW RW
Initial value 0 0 0 0 0 0 0 0296
7593L–AVR–09/12
AT90USB64/128
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6 - P6RST - Pipe 6 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 6.
• 5 - P5RST - Pipe 5 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 5.
• 4 - P4RST - Pipe 4 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 4.
• 3 - P3RST - Pipe 3 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 3.
• 2 - P2RST - Pipe 2 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 2.
• 1 - P1RST - Pipe 1 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 1.
• 0 - P0RST - Pipe 0 Reset
Set this bit to 1 and reset this bit to 0 to reset the Pipe 0.
• 7 - Reserved
The value read from this bit is always 0. Do not set this bit.
• 6 - PFREEZE - Pipe Freeze
Set this bit to Freeze the Pipe requests generation.
Clear this bit to enable the Pipe request generation.
This bit is set by hardware when:
- the pipe is not configured
- a STALL handshake has been received on this Pipe
- An error occurs on the Pipe (UPINTX.PERRI = 1)
- (INRQ+1) In requests have been processed
This bit is set at 1 by hardware after a Pipe reset or a Pipe enable.
Bit 7 6 5 4 3 2 1 0
- P6RST P5RST P4RST P3RST P2RST P1RST P0RST UPRST
Read/write RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- PFREEZE INMODE - RSTDT - - PEN UPCONX
Read/write RW RW RW RW
Initial value 0 0 0 0 0 0 0 0297
7593L–AVR–09/12
AT90USB64/128
• 5 - INMODE - IN Request mode
Set this bit to allow the USB controller to perform infinite IN requests when the Pipe is not frozen.
Clear this bit to perform a pre-defined number of IN requests. This number is stored in the UINRQX
register.
• 4 - Reserved
The value read from this bit is always 0. Do not set this bit.
• 3 - RSTDT - Reset Data Toggle
Set this bit to reset the Data Toggle to its initial value for the current Pipe.
Cleared by hardware when proceed. Clearing by software has no effect.
• 2 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 1 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 0 - PEN - Pipe Enable
Set to enable the Pipe.
Clear to disable and set the pipe.
• 7-6 - PTYPE1:0 - Pipe Type
Select the type of the Pipe:
- 00: Control
- 01: Isochronous
- 10: Bulk
- 11: Interrupt
• 5-4 - PTOKEN1:0 - Pipe Token
Select the Token to associate to the Pipe
- 00: SETUP
- 01: IN
- 10: OUT
- 11: reserved
• 3-0 - PEPNUM3:0 - Pipe Endpoint Number
Set this field according to the Pipe configuration. Set the number of the Endpoint targeted by the
Pipe. This value is from 0 and 15.
Bit 7 6 5 4 3 2 1 0
PTYPE1 PTYPE0 PTOKEN1 PTOKEN0 PEPNUM3 PEPNUM2 PEPNUM1 PEPNUM0 UPCFG0X
Read/write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0298
7593L–AVR–09/12
AT90USB64/128
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-4 - PSIZE2:0 - Pipe Size
Select the size of the Pipe:
- 000: 8 - 100: 128 (only for endpoint 1)
- 001: 16 - 101: 256 (only for endpoint 1)
- 010: 32 - 110: Reserved. Do not use this configuration.
- 011: 64 - 111: Reserved. Do not use this configuration.
• 3-2 - PBK1:0 - Pipe Bank
Select the number of bank to declare for the current Pipe.
- 00: 1 bank
- 01: 2 banks
- 10: invalid
- 11: invalid
• ALLOC - Configure Pipe Memory
Set to configure the pipe memory with the characteristics.
Clear to update the memory allocation. Refer to the Memory Management chapter for more
details.
7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 7 - INTFRQ7:0 - Interrupt Pipe Request Frequency
These bits are the maximum value in millisecond of the polling period for an Interrupt Pipe.
This value has no effect for a non-Interrupt Pipe.
Bit 7 6 5 4 3 2 1 0
- PSIZE2:0 PBK1:0 ALLOC - UPCFG1X
Read/write R RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
INTFRQ7 INTFRQ6 INTFRQ5 INTFRQ4 INTFRQ3 INTFRQ2 INTFRQ1 INTFRQ0 UPCFG2X
Read/write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0299
7593L–AVR–09/12
AT90USB64/128
• 7 - CFGOK - Configure Pipe Memory OK
Set by hardware if the required memory configuration has been successfully performed.
Cleared by hardware when the pipe is disabled. The USB reset and the reset pipe have no effect
on the configuration of the pipe.
• 6 - OVERFI - Overflow
Set by hardware when a the current Pipe has received more data than the maximum length of
the current Pipe. An interrupt is triggered if the FLERRE bit is set.
Shall be cleared by software. Setting by software has no effect.
• 5 - UNDERFI - Underflow
Set by hardware when a transaction underflow occurs in the current isochronous or interrupt
Pipe. The Pipe can’t send the data flow required by the device. A ZLP will be sent instead. An
interrupt is triggered if the FLERRE bit is set.
Shall be cleared by software. Setting by software has no effect.
Note: the Host controller has to send a OUT packet, but the bank is empty. A ZLP will be sent
and the UNDERFI bit is set.
• 4 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 3-2 - DTSEQ1:0 - Toggle Sequencing flag
Set by hardware to indicate the PID data of the current bank:
00b Data0
01b Data1
1xb Reserved.
For OUT Pipe, this value indicates the next data toggle that will be sent. This is not relative to the
current bank.
For IN Pipe, this value indicates the last data toggle received on the current bank.
• 1-0 - NBUSYBK1:0 - Busy Bank flag
Set by hardware to indicate the number of busy bank.
For OUT Pipe, it indicates the number of busy bank(s), filled by the user, ready for OUT transfer.
For IN Pipe, it indicates the number of busy bank(s) filled by IN transaction from the Device.
00b All banks are free
01b 1 busy bank
10b 2 busy banks
11b Reserved.
Bit 7 6 5 4 3 2 1 0
CFGOK OVERFI UNDERFI - DTSEQ1:0 NBUSYBK UPSTAX
Read/write R RW RW R R R R
Initial value 0 0 0 0 0 0 0 0300
7593L–AVR–09/12
AT90USB64/128
• 7-0 - INRQ7:0 - IN Request Number Before Freeze
Enter the number of IN transactions before the USB controller freezes the pipe. The USB controller
will perform (INRQ+1) IN requests before to freeze the Pipe. This counter is automatically
decreased by 1 each time a IN request has been successfully performed.
This register has no effect when the INMODE bit is set (infinite IN requests generation till the
pipe is not frozen).
• 7-6 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 5 - COUNTER1:0 - Error counter
This counter is increased by the USB controller each time an error occurs on the Pipe. When this
value reaches 3, the Pipe is automatically frozen.
Clear these bits by software.
• 4 - CRC16 - CRC16 Error
Set by hardware when a CRC16 error has been detected.
Shall be cleared by software. Setting by software has no effect.
• 3 - TIMEOUT - Time-out Error
Set by hardware when a time-out error has been detected.
Shall be cleared by software. Setting by software has no effect.
• 2 - PID - PID Error
Set by hardware when a PID error has been detected.
Shall be cleared by software. Setting by software has no effect.
• 1 - DATAPID - Data PID Error
Set by hardware when a data PID error has been detected.
Shall be cleared by software. Setting by software has no effect.
• 0 - DATATGL - Bad Data Toggle
Set by hardware when a data toggle error has been detected.
Shall be cleared by software. Setting by software has no effect.
Bit 7 6 5 4 3 2 1 0
INRQ7 INRQ6 INRQ5 INRQ4 INRQ3 INRQ2 INRQ1 INRQ0 UPINRQX
Read/write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- COUNTER1:0 CRC16 TIMEOUT PID DATAPID DATATGL UPERRX
Read/write RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0301
7593L–AVR–09/12
AT90USB64/128
• 7 - FIFOCON - FIFO Control
For OUT and SETUP Pipe:
Set by hardware when the current bank is free, at the same time than TXOUT or TXSTP.
Clear to send the FIFO data and to switch the bank. Setting by software has no effect.
For IN Pipe:
Set by hardware when a new IN message is stored in the current bank, at the same time than
RXIN.
Clear to free the current bank and to switch to the following bank. Setting by software has no
effect.
• 6 - NAKEDI - NAK Handshake received
Set by hardware when a NAK has been received on the current bank of the Pipe. This triggers
an interrupt if the NAKEDE bit is set in the UPIENX register.
Shall be clear to handshake the interrupt. Setting by software has no effect.
• 5 - RWAL - Read/Write Allowed
OUT Pipe:
Set by hardware when the firmware can write a new data into the Pipe FIFO.
Cleared by hardware when the current Pipe FIFO is full.
IN Pipe:
Set by hardware when the firmware can read a new data into the Pipe FIFO.
Cleared by hardware when the current Pipe FIFO is empty.
This bit is also cleared by hardware when the RXSTALL or the PERR bit is set
• 4 - PERRI -PIPE Error
Set by hardware when an error occurs on the current bank of the Pipe. This triggers an interrupt
if the PERRE bit is set in the UPIENX register. Refers to the UPERRX register to determine the
source of the error.
Automatically cleared by hardware when the error source bit is cleared.
• 3 - TXSTPI - SETUP Bank ready
Set by hardware when the current SETUP bank is free and can be filled. This triggers an interrupt
if the TXSTPE bit is set in the UPIENX register.
Shall be cleared to handshake the interrupt. Setting by software has no effect.
• 2 - TXOUTI -OUT Bank ready
Set by hardware when the current OUT bank is free and can be filled. This triggers an interrupt if
the TXOUTE bit is set in the UPIENX register.
Shall be cleared to handshake the interrupt. Setting by software has no effect.
Bit 7 6 5 4 3 2 1 0
FIFOCON NAKEDI RWAL PERRI TXSTPI TXOUTI RXSTALLI RXINI UPINTX
Read/write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0302
7593L–AVR–09/12
AT90USB64/128
• 1 - RXSTALLI / CRCERR - STALL Received / Isochronous CRC Error
Set by hardware when a STALL handshake has been received on the current bank of the Pipe.
The Pipe is automatically frozen. This triggers an interrupt if the RXSTALLE bit is set in the UPIENX
register.
Shall be cleared to handshake the interrupt. Setting by software has no effect.
For Isochronous Pipe:
Set by hardware when a CRC error occurs on the current bank of the Pipe. This triggers an interrupt
if the TXSTPE bit is set in the UPIENX register.
Shall be cleared to handshake the interrupt. Setting by software has no effect.
• 0 - RXINI - IN Data received
Set by hardware when a new USB message is stored in the current bank of the Pipe. This triggers
an interrupt if the RXINE bit is set in the UPIENX register.
Shall be cleared to handshake the interrupt. Setting by software has no effect.
• 7 - FLERRE - Flow Error Interrupt enable
Set to enable the OVERFI and UNDERFI interrupts.
Clear to disable the OVERFI and UNDERFI interrupts.
• 6 - NAKEDE -NAK Handshake Received Interrupt Enable
Set to enable the NAKEDI interrupt.
Clear to disable the NAKEDI interrupt.
• 5 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 4 - PERRE -PIPE Error Interrupt Enable
Set to enable the PERRI interrupt.
Clear to disable the PERRI interrupt.
• 3 - TXSTPE - SETUP Bank ready Interrupt Enable
Set to enable the TXSTPI interrupt.
Clear to disable the TXSTPI interrupt.
• 2 - TXOUTE - OUT Bank ready Interrupt Enable
Set to enable the TXOUTI interrupt.
Clear to disable the TXOUTI interrupt.
• 1 - RXSTALLE - STALL Received Interrupt Enable
Set to enable the RXSTALLI interrupt.
Clear to disable the RXSTALLI interrupt.
Bit 7 6 5 4 3 2 1 0
FLERRE NAKEDE - PERRE TXSTPE TXOUTE RXSTALLE RXINE UPIENX
Read/write RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0303
7593L–AVR–09/12
AT90USB64/128
• 0 - RXINE - IN Data received Interrupt Enable
Set to enable the RXINI interrupt.
Clear to disable the RXINI interrupt.
• 7-0 - PDAT7:0 - Pipe Data bits
Set by the software to read/write a byte from/to the Pipe FIFO selected by PNUM.
• 7-3 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 2-0 - PBYCT10:8 - Byte count (high) bits
Set by hardware. This field is the MSB of the byte count of the FIFO endpoint. The LSB part is
provided by the UPBCLX register.
• 7-0 - PBYCT7:0 - Byte Count (low) bits
Set by the hardware. PBYCT10:0 is:
- (for OUT Pipe) increased after each writing into the Pipe and decremented after each byte
sent,
- (for IN Pipe) increased after each byte received by the host, and decremented after each byte
read by the software.
• 7 - Reserved
The value read from these bits is always 0. Do not set these bits.
• 6-0 - PINT6:0 - Pipe Interrupts bits
Set by hardware when an interrupt is triggered by the UPINTX register and if the corresponding
endpoint interrupt enable bit is set.
Cleared by hardware when the interrupt source is served.
Bit 7 6 5 4 3 2 1 0
PDAT7 PDAT6 PDAT5 PDAT4 PDAT3 PDAT2 PDAT1 PDAT0 UPDATX
Read/write RW RW RW RW RW RW RW RW
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- - - - - PBYCT10 PBYCT9 PBYCT8 UPBCHX
Read/write R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
PBYCT7 PBYCT6 PBYCT5 PBYCT4 PBYCT3 PBYCT2 PBYCT1 PBYCT0 UPBCLX
Read/write R R R R R R R R
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
- PINT6 PINT5 PINT4 PINT3 PINT2 PINT1 PINT0 UPINT
Read/write
Initial value 0 0 0 0 0 0 0 0304
7593L–AVR–09/12
AT90USB64/128
25. Analog Comparator
The Analog Comparator compares the input values on the positive pin AIN0 and negative pin
AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin
AIN1, the Analog Comparator output, ACO, is set. The comparator’s output can be set to trigger
the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate
interrupt, exclusive to the Analog Comparator. The user can select Interrupt triggering on comparator
output rise, fall or toggle. A block diagram of the comparator and its surrounding logic is
shown in Figure 25-1.
The Power Reduction ADC bit, PRADC, in “PRR0 – Power Reduction Register 0” on page 54
must be disabled by writing a logical zero to be able to use the ADC input MUX.
Figure 25-1. Analog Comparator block diagram (2).
Notes: 1. See Table 25-2 on page 306.
2. Refer to Figure 1-1 on page 3 and Table 11-6 on page 79 for Analog Comparator pin
placement.
25.0.1 ADCSRB – ADC Control and Status Register B
• Bit 6 – ACME: Analog Comparator Multiplexer Enable
When this bit is written logic one and the ADC is switched off (ADEN in ADCSRA is zero), the
ADC multiplexer selects the negative input to the Analog Comparator. When this bit is written
logic zero, AIN1 is applied to the negative input of the Analog Comparator. For a detailed
description of this bit, see “Analog Comparator multiplexed input” on page 306.
25.0.2 ACSR – Analog Comparator Control and Status Register
ACBG
BANDGAP
REFERENCE
ADC MULTIPLEXER
OUTPUT
ACME
ADEN
(1)
Bit 7 6 5 4 3 2 1 0
– ACME – – - ADTS2 ADTS1 ADTS0 ADCSRB
Read/write R R/W R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 ACSR
Read/write R/W R/W R R/W R/W R/W R/W R/W
Initial value 0 0 N/A 0 0 0 0 0305
7593L–AVR–09/12
AT90USB64/128
• Bit 7 – ACD: Analog Comparator Disable
When this bit is written logic one, the power to the Analog Comparator is switched off. This bit
can be set at any time to turn off the Analog Comparator. This will reduce power consumption in
Active and Idle mode. When changing the ACD bit, the Analog Comparator Interrupt must be
disabled by clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when the bit is
changed.
• Bit 6 – ACBG: Analog Comparator Bandgap Select
When this bit is set, a fixed bandgap reference voltage replaces the positive input to the Analog
Comparator. When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator.
See “Internal voltage reference” on page 62.
• Bit 5 – ACO: Analog Comparator Output
The output of the Analog Comparator is synchronized and then directly connected to ACO. The
synchronization introduces a delay of 1 - 2 clock cycles.
• Bit 4 – ACI: Analog Comparator Interrupt Flag
This bit is set by hardware when a comparator output event triggers the interrupt mode defined
by ACIS1 and ACIS0. The Analog Comparator interrupt routine is executed if the ACIE bit is set
and the I-bit in SREG is set. ACI is cleared by hardware when executing the corresponding interrupt
handling vector. Alternatively, ACI is cleared by writing a logic one to the flag.
• Bit 3 – ACIE: Analog Comparator Interrupt Enable
When the ACIE bit is written logic one and the I-bit in the Status Register is set, the Analog Comparator
interrupt is activated. When written logic zero, the interrupt is disabled.
• Bit 2 – ACIC: Analog Comparator Input Capture Enable
When written logic one, this bit enables the input capture function in Timer/Counter1 to be triggered
by the Analog Comparator. The comparator output is in this case directly connected to the
input capture front-end logic, making the comparator utilize the noise canceler and edge select
features of the Timer/Counter1 Input Capture interrupt. When written logic zero, no connection
between the Analog Comparator and the input capture function exists. To make the comparator
trigger the Timer/Counter1 Input Capture interrupt, the ICIE1 bit in the Timer Interrupt Mask
Register (TIMSK1) must be set.
• Bits 1, 0 – ACIS1, ACIS0: Analog Comparator Interrupt Mode Select
These bits determine which comparator events that trigger the Analog Comparator interrupt. The
different settings are shown in Table 25-1.
When changing the ACIS1/ACIS0 bits, the Analog Comparator Interrupt must be disabled by
clearing its Interrupt Enable bit in the ACSR Register. Otherwise an interrupt can occur when the
bits are changed.
Table 25-1. ACIS1/ACIS0 settings.
ACIS1 ACIS0 Interrupt mode
0 0 Comparator Interrupt on Output Toggle
0 1 Reserved
1 0 Comparator Interrupt on Falling Output Edge
1 1 Comparator Interrupt on Rising Output Edge306
7593L–AVR–09/12
AT90USB64/128
25.1 Analog Comparator multiplexed input
It is possible to select any of the ADC7..0 pins to replace the negative input to the Analog Comparator.
The ADC multiplexer is used to select this input, and consequently, the ADC must be
switched off to utilize this feature. If the Analog Comparator Multiplexer Enable bit (ACME in
ADCSRB) is set and the ADC is switched off (ADEN in ADCSRA is zero), and MUX2..0 in
ADMUX select the input pin to replace the negative input to the Analog Comparator, as shown in
Table 25-2. If ACME is cleared or ADEN is set, AIN1 is applied to the negative input to the Analog
Comparator.
25.1.1 DIDR1 – Digital Input Disable Register 1
• Bit 1, 0 – AIN1D, AIN0D: AIN1, AIN0 Digital Input Disable
When this bit is written logic one, the digital input buffer on the AIN1/0 pin is disabled. The corresponding
PIN Register bit will always read as zero when this bit is set. When an analog signal is
applied to the AIN1/0 pin and the digital input from this pin is not needed, this bit should be written
logic one to reduce power consumption in the digital input buffer.
Table 25-2. Analog Comparator multiplexed input.
ACME ADEN MUX2..0 Analog Comparator negative input
0 x xxx AIN1
1 1 xxx AIN1
1 0 000 ADC0
1 0 001 ADC1
1 0 010 ADC2
1 0 011 ADC3
1 0 100 ADC4
1 0 101 ADC5
1 0 110 ADC6
1 0 111 ADC7
Bit 7 6 5 4 3 2 1 0
– – – – – – AIN1D AIN0D DIDR1
Read/write R R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0307
7593L–AVR–09/12
AT90USB64/128
26. ADC – Analog to Digital Converter
26.1 Features
• 10-bit resolution
• 0.5 LSB integral non-linearity
• ±2 LSB absolute accuracy
• 65 - 260µs conversion time
• Up to 15ksps at maximum resolution
• Eight multiplexed single ended input channels
• Seven differential input channels
• Optional left adjustment for ADC result readout
• 0 - VCC ADC input voltage range
• Selectable 2.56V ADC reference voltage
• Free running or single conversion mode
• ADC start conversion by auto triggering on interrupt sources
• Interrupt on ADC conversion complete
• Sleep mode noise canceler
26.2 Overview
The Atmel AT90USB64/128 features a 10-bit successive approximation ADC. The ADC is connected
to an 8-channel Analog Multiplexer which allows eight single-ended voltage inputs
constructed from the pins of Port F. The single-ended voltage inputs refer to 0V (GND).
The device also supports 16 differential voltage input combinations. Two of the differential inputs
(ADC1, ADC0 and ADC3, ADC2) are equipped with a programmable gain stage, providing
amplification steps of 0 dB (1×), 20 dB (10×), or 46 dB (200×) on the differential input voltage
before the A/D conversion. Seven differential analog input channels share a common negative
terminal (ADC1), while any other ADC input can be selected as the positive input terminal. If 1×
or 10× gain is used, 8-bit resolution can be expected. If 200× gain is used, 7-bit resolution can
be expected.
The ADC contains a Sample and Hold circuit which ensures that the input voltage to the ADC is
held at a constant level during conversion. A block diagram of the ADC is shown in Figure 26-1
on page 308.
The ADC has a separate analog supply voltage pin, AVCC. AVCC must not differ more than ±0.3V
from VCC. See the paragraph “ADC noise canceler” on page 314 on how to connect this pin.
Internal reference voltages of nominally 2.56V or AVCC are provided on-chip. The voltage reference
may be externally decoupled at the AREF pin by a capacitor for better noise performance.308
7593L–AVR–09/12
AT90USB64/128
Figure 26-1. Analog to digital converter block schematic.
ADC CONVERSION
COMPLETE IRQ
8-BIT DATA BUS
15 0
ADC MULTIPLEXER
SELECT (ADMUX)
ADC CTRL. & STATUS
REGISTER (ADCSRA)
ADC DATA REGISTER
(ADCH/ADCL)
MUX2
ADIE
ADATE
ADEN
ADSC
ADIF ADIF
MUX1
MUX0
ADPS2
ADPS1
ADPS0
MUX3
CONVERSION LOGIC
10-BIT DAC
+
-
SAMPLE & HOLD
COMPARATOR
INTERNAL
REFERENCE
MUX DECODER MUX4
AVCC
ADC7
ADC6
ADC5
ADC4
ADC3
ADC2
ADC1
ADC0
REFS1
REFS0
ADLAR
+
-
CHANNEL SELECTION
GAIN SELECTION
ADC[9:0]
ADC MULTIPLEXER
OUTPUT
DIFFERENTIAL
AMPLIFIER
AREF
BANDGAP
REFERENCE
PRESCALER
SINGLE ENDED / DIFFERENTIAL SELECTION
GND
POS.
INPUT
MUX
NEG.
INPUT
MUX
TRIGGER
SELECT
ADTS[2:0]
INTERRUPT
FLAGS
ADHSM
START309
7593L–AVR–09/12
AT90USB64/128
26.3 Operation
The ADC converts an analog input voltage to a 10-bit digital value through successive approximation.
The minimum value represents GND and the maximum value represents the voltage on
the AREF pin minus 1 LSB. Optionally, AVCC or an internal 2.56V reference voltage may be connected
to the AREF pin by writing to the REFSn bits in the ADMUX Register. The internal
voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve
noise immunity.
The analog input channel and differential gain are selected by writing to the MUX bits in
ADMUX. Any of the ADC input pins, as well as GND and a fixed bandgap voltage reference, can
be selected as single ended inputs to the ADC. A selection of ADC input pins can be selected as
positive and negative inputs to the differential amplifier.
The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA. Voltage reference and
input channel selections will not go into effect until ADEN is set. The ADC does not consume
power when ADEN is cleared, so it is recommended to switch off the ADC before entering power
saving sleep modes.
The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and
ADCL. By default, the result is presented right adjusted, but can optionally be presented left
adjusted by setting the ADLAR bit in ADMUX.
If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read
ADCH. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the Data
Registers belongs to the same conversion. Once ADCL is read, ADC access to Data Registers
is blocked. This means that if ADCL has been read, and a conversion completes before ADCH is
read, neither register is updated and the result from the conversion is lost. When ADCH is read,
ADC access to the ADCH and ADCL Registers is re-enabled.
The ADC has its own interrupt which can be triggered when a conversion completes. The ADC
access to the Data Registers is prohibited between reading of ADCH and ADCL, the interrupt
will trigger even if the result is lost.
26.4 Starting a conversion
A single conversion is started by writing a logical one to the ADC Start Conversion bit, ADSC.
This bit stays high as long as the conversion is in progress and will be cleared by hardware
when the conversion is completed. If a different data channel is selected while a conversion is in
progress, the ADC will finish the current conversion before performing the channel change.
Alternatively, a conversion can be triggered automatically by various sources. Auto Triggering is
enabled by setting the ADC Auto Trigger Enable bit, ADATE in ADCSRA. The trigger source is
selected by setting the ADC Trigger Select bits, ADTS in ADCSRB (See description of the ADTS
bits for a list of the trigger sources). When a positive edge occurs on the selected trigger signal,
the ADC prescaler is reset and a conversion is started. This provides a method of starting conversions
at fixed intervals. If the trigger signal is still set when the conversion completes, a new
conversion will not be started. If another positive edge occurs on the trigger signal during conversion,
the edge will be ignored. Note that an interrupt flag will be set even if the specific
interrupt is disabled or the Global Interrupt Enable bit in SREG is cleared. A conversion can thus
be triggered without causing an interrupt. However, the interrupt flag must be cleared in order to
trigger a new conversion at the next interrupt event. 310
7593L–AVR–09/12
AT90USB64/128
Figure 26-2. ADC auto trigger logic.
Using the ADC Interrupt Flag as a trigger source makes the ADC start a new conversion as soon
as the ongoing conversion has finished. The ADC then operates in Free Running mode, constantly
sampling and updating the ADC Data Register. The first conversion must be started by
writing a logical one to the ADSC bit in ADCSRA. In this mode the ADC will perform successive
conversions independently of whether the ADC Interrupt Flag, ADIF is cleared or not.
If Auto Triggering is enabled, single conversions can be started by writing ADSC in ADCSRA to
one. ADSC can also be used to determine if a conversion is in progress. The ADSC bit will be
read as one during a conversion, independently of how the conversion was started.
26.5 Prescaling and conversion timing
Figure 26-3. ADC prescaler.
By default, the successive approximation circuitry requires an input clock frequency between
50kHz and 200kHz to get maximum resolution. If a lower resolution than 10 bits is needed, the
input clock frequency to the ADC can be higher than 200kHz to get a higher sample rate. Alternatively,
setting the ADHSM bit in ADCSRB allows an increased ADC clock frequency at the
expense of higher power consumption.
The ADC module contains a prescaler, which generates an acceptable ADC clock frequency
from any CPU frequency above 100kHz. The prescaling is set by the ADPS bits in ADCSRA.
The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit
ADSC
ADIF
SOURCE 1
SOURCE n
ADTS[2:0]
CONVERSION
LOGIC
PRESCALER
START CLKADC
.
.
.
. EDGE
DETECTOR
ADATE
7-BIT ADC PRESCALER
ADC CLOCK SOURCE
CK
ADPS0
ADPS1
ADPS2
CK/128
CK/2
CK/4
CK/8
CK/16
CK/32
CK/64
Reset
ADEN
START311
7593L–AVR–09/12
AT90USB64/128
in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously
reset when ADEN is low.
When initiating a single ended conversion by setting the ADSC bit in ADCSRA, the conversion
starts at the following rising edge of the ADC clock cycle. See “Differential channels” on page
312 for details on differential conversion timing.
A normal conversion takes 13 ADC clock cycles. The first conversion after the ADC is switched
on (ADEN in ADCSRA is set) takes 25 ADC clock cycles in order to initialize the analog circuitry.
The actual sample-and-hold takes place 1.5 ADC clock cycles after the start of a normal conversion
and 13.5 ADC clock cycles after the start of an first conversion. When a conversion is
complete, the result is written to the ADC Data Registers, and ADIF is set. In Single Conversion
mode, ADSC is cleared simultaneously. The software may then set ADSC again, and a new
conversion will be initiated on the first rising ADC clock edge.
When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures
a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold
takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional
CPU clock cycles are used for synchronization logic.
In Free Running mode, a new conversion will be started immediately after the conversion completes,
while ADSC remains high. For a summary of conversion times, see Table 26-1 on page
312.
Figure 26-4. ADC timing diagram, first conversion (single conversion mode).
Figure 26-5. ADC timing diagram, single conversion.
Sign and MSB of result
LSB of result
ADC clock
ADSC
Sample & hold
ADIF
ADCH
ADCL
Cycle number
ADEN
1 2 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2
First conversion Next
conversion
3
MUX and REFS
update
MUX
and REFS
update
Conversion
complete
1 2 3 4 5 6 7 8 9 10 11 12 13
Sign and MSB of result
LSB of result
ADC clock
ADSC
ADIF
ADCH
ADCL
Cycle number 1 2
One conversion Next conversion
3
Sample & hold
MUX and REFS
update
Conversion
complete MUX and REFS
update312
7593L–AVR–09/12
AT90USB64/128
Figure 26-6. ADC timing diagram, auto triggered conversion.
Figure 26-7. ADC timing diagram, free running conversion.
26.5.1 Differential channels
When using differential channels, certain aspects of the conversion need to be taken into
consideration.
Differential conversions are synchronized to the internal clock CKADC2 equal to half the ADC
clock frequency. This synchronization is done automatically by the ADC interface in such a way
that the sample-and-hold occurs at a specific phase of CKADC2. A conversion initiated by the
user (that is, all single conversions, and the first free running conversion) when CKADC2 is low will
take the same amount of time as a single ended conversion (13 ADC clock cycles from the next
prescaled clock cycle). A conversion initiated by the user when CKADC2 is high will take 14 ADC
clock cycles due to the synchronization mechanism. In Free Running mode, a new conversion is
initiated immediately after the previous conversion completes, and since CKADC2 is high at this
time, all automatically started (that is, all but the first) Free Running conversions will take 14
ADC clock cycles.
Table 26-1. ADC conversion time.
Condition First conversion
Normal conversion,
single ended
Auto triggered
conversion
Sample & Hold
(Cycles from Start of Conversion) 14.5 1.5 2
Conversion Time
(Cycles) 25 13 13.5
1 2 3 4 5 6 7 8 9 10 11 12 13
Sign and MSB of result
LSB of result
ADC clock
Trigger
Source
ADIF
ADCH
ADCL
Cycle number 1 2
One conversion Next conversion
Conversion
complete Prescaler
reset
ADATE
Prescaler
reset
Sample &
hold
MUX and REFS
update
11 12 13
Sign and MSB of result
LSB of result
ADC clock
ADSC
ADIF
ADCH
ADCL
Cycle number 1 2
One conversion Next conversion
3 4
Conversion
complete
Sample & hold
MUX and REFS
update313
7593L–AVR–09/12
AT90USB64/128
If differential channels are used and conversions are started by Auto Triggering, the ADC must
be switched off between conversions. When Auto Triggering is used, the ADC prescaler is reset
before the conversion is started. Since the stage is dependent of a stable ADC clock prior to the
conversion, this conversion will not be valid. By disabling and then re-enabling the ADC between
each conversion (writing ADEN in ADCSRA to “0” then to “1”), only extended conversions are
performed. The result from the extended conversions will be valid. See “Prescaling and conversion
timing” on page 310 for timing details.
The gain stage is optimized for a bandwidth of 4kHz at all gain settings. Higher frequencies may
be subjected to non-linear amplification. An external low-pass filter should be used if the input
signal contains higher frequency components than the gain stage bandwidth. Note that the ADC
clock frequency is independent of the gain stage bandwidth limitation. For example, the ADC
clock period may be 6µs, allowing a channel to be sampled at 12ksps, regardless of the bandwidth
of this channel.
26.6 Changing channel or reference selection
The MUXn and REFS1:0 bits in the ADMUX Register are single buffered through a temporary
register to which the CPU has random access. This ensures that the channels and reference
selection only takes place at a safe point during the conversion. The channel and reference
selection is continuously updated until a conversion is started. Once the conversion starts, the
channel and reference selection is locked to ensure a sufficient sampling time for the ADC. Continuous
updating resumes in the last ADC clock cycle before the conversion completes (ADIF in
ADCSRA is set). Note that the conversion starts on the following rising ADC clock edge after
ADSC is written. The user is thus advised not to write new channel or reference selection values
to ADMUX until one ADC clock cycle after ADSC is written.
If Auto Triggering is used, the exact time of the triggering event can be indeterministic. Special
care must be taken when updating the ADMUX Register, in order to control which conversion
will be affected by the new settings.
If both ADATE and ADEN is written to one, an interrupt event can occur at any time. If the
ADMUX Register is changed in this period, the user cannot tell if the next conversion is based
on the old or the new settings. ADMUX can be safely updated in the following ways:
a. When ADATE or ADEN is cleared.
b. During conversion, minimum one ADC clock cycle after the trigger event.
c. After a conversion, before the interrupt flag used as trigger source is cleared.
When updating ADMUX in one of these conditions, the new settings will affect the next ADC
conversion.
Special care should be taken when changing differential channels. Once a differential channel
has been selected, the stage may take as much as 125µs to stabilize to the new value. Thus
conversions should not be started within the first 125µs after selecting a new differential channel.
Alternatively, conversion results obtained within this period should be discarded.
The same settling time should be observed for the first differential conversion after changing
ADC reference (by changing the REFS1:0 bits in ADMUX).
The settling time and gain stage bandwidth is independent of the ADHSM bit setting.314
7593L–AVR–09/12
AT90USB64/128
26.6.1 ADC input channels
When changing channel selections, the user should observe the following guidelines to ensure
that the correct channel is selected:
• In Single Conversion mode, always select the channel before starting the conversion. The
channel selection may be changed one ADC clock cycle after writing one to ADSC. However,
the simplest method is to wait for the conversion to complete before changing the channel
selection
• In Free Running mode, always select the channel before starting the first conversion. The
channel selection may be changed one ADC clock cycle after writing one to ADSC. However,
the simplest method is to wait for the first conversion to complete, and then change the
channel selection. Since the next conversion has already started automatically, the next
result will reflect the previous channel selection. Subsequent conversions will reflect the new
channel selection
When switching to a differential gain channel, the first conversion result may have a poor accuracy
due to the required settling time for the automatic offset cancellation circuitry. The user
should preferably disregard the first conversion result.
26.6.2 ADC voltage reference
The reference voltage for the ADC (VREF) indicates the conversion range for the ADC. Single
ended channels that exceed VREF will result in codes close to 0x3FF. VREF can be selected as
either AVCC, internal 2.56V reference, or external AREF pin.
AVCC is connected to the ADC through a passive switch. The internal 2.56V reference is generated
from the internal bandgap reference (VBG) through an internal amplifier. In either case, the
external AREF pin is directly connected to the ADC, and the reference voltage can be made
more immune to noise by connecting a capacitor between the AREF pin and ground. VREF can
also be measured at the AREF pin with a high impedant voltmeter. Note that VREF is a high
impedant source, and only a capacitive load should be connected in a system.
If the user has a fixed voltage source connected to the AREF pin, the user may not use the other
reference voltage options in the application, as they will be shorted to the external voltage. If no
external voltage is applied to the AREF pin, the user may switch between AVCC and 2.56V as
reference selection. The first ADC conversion result after switching reference voltage source
may be inaccurate, and the user is advised to discard this result.
If differential channels are used, the selected reference should not be closer to AVCC than indicated
in Table 31-5 on page 397.
26.7 ADC noise canceler
The ADC features a noise canceler that enables conversion during sleep mode to reduce noise
induced from the CPU core and other I/O peripherals. The noise canceler can be used with ADC
Noise Reduction and Idle mode. To make use of this feature, the following procedure should be
used:315
7593L–AVR–09/12
AT90USB64/128
a. Make sure that the ADC is enabled and is not busy converting. Single Conversion
mode must be selected and the ADC conversion complete interrupt must be
enabled.
b. Enter ADC Noise Reduction mode (or Idle mode). The ADC will start a conversion
once the CPU has been halted.
c. If no other interrupts occur before the ADC conversion completes, the ADC interrupt
will wake up the CPU and execute the ADC Conversion Complete interrupt
routine. If another interrupt wakes up the CPU before the ADC conversion is complete,
that interrupt will be executed, and an ADC Conversion Complete interrupt
request will be generated when the ADC conversion completes. The CPU will
remain in active mode until a new sleep command is executed.
Note that the ADC will not be automatically turned off when entering other sleep modes than Idle
mode and ADC Noise Reduction mode. The user is advised to write zero to ADEN before entering
such sleep modes to avoid excessive power consumption.
If the ADC is enabled in such sleep modes and the user wants to perform differential conversions,
the user is advised to switch the ADC off and on after waking up from sleep to prompt an
extended conversion to get a valid result.
26.7.1 Analog input circuitry
The analog input circuitry for single ended channels is illustrated in Figure 26-8. An analog
source applied to ADCn is subjected to the pin capacitance and input leakage of that pin, regardless
of whether that channel is selected as input for the ADC. When the channel is selected, the
source must drive the S/H capacitor through the series resistance (combined resistance in the
input path).
The ADC is optimized for analog signals with an output impedance of approximately 10kΩ or
less. If such a source is used, the sampling time will be negligible. If a source with higher impedance
is used, the sampling time will depend on how long time the source needs to charge the
S/H capacitor, with can vary widely. The user is recommended to only use low impedant sources
with slowly varying signals, since this minimizes the required charge transfer to the S/H
capacitor.
If differential gain channels are used, the input circuitry looks somewhat different, although
source impedances of a few hundred kΩ or less is recommended.
Signal components higher than the Nyquist frequency (fADC/2) should not be present for either
kind of channels, to avoid distortion from unpredictable signal convolution. The user is advised
to remove high frequency components with a low-pass filter before applying the signals as
inputs to the ADC.
Figure 26-8. Analog input circuitry.
ADCn
I
IH
1..100kΩ
CS/H= 14pF
VCC/2
I
IL316
7593L–AVR–09/12
AT90USB64/128
26.7.2 Analog noise canceling techniques
Digital circuitry inside and outside the device generates EMI which might affect the accuracy of
analog measurements. If conversion accuracy is critical, the noise level can be reduced by
applying the following techniques:
a. Keep analog signal paths as short as possible. Make sure analog tracks run over
the analog ground plane, and keep them well away from high-speed switching digital
tracks.
b. The AVCC pin on the device should be connected to the digital VCC supply voltage
via an LC network as shown in Figure 26-9.
c. Use the ADC noise canceler function to reduce induced noise from the CPU.
d. If any ADC port pins are used as digital outputs, it is essential that these do not
switch while a conversion is in progress.
Figure 26-9. ADC power connections.
26.7.3 Offset compensation schemes
The gain stage has a built-in offset cancellation circuitry that nulls the offset of differential measurements
as much as possible. The remaining offset in the analog path can be measured
directly by selecting the same channel for both differential inputs. This offset residue can be then
subtracted in software from the measurement results. Using this kind of software based offset
correction, offset on any channel can be reduced below one LSB.
26.7.4 ADC accuracy definitions
An n-bit single-ended ADC converts a voltage linearly between GND and VREF in 2n steps
(LSBs). The lowest code is read as 0, and the highest code is read as 2n
-1.
Several parameters describe the deviation from the ideal behavior:
VCC
GND
100nF
Analog ground plane
(ADC0) PF0
(ADC7) PF7
(ADC1) PF1
(ADC2) PF2
(ADC3) PF3
(ADC4) PF4
(ADC5) PF5
(ADC6) PF6
AREF
GND
AVCC
52
53
54
55
56
57
58
59
60
61
62
63
64
1
51
NC
(AD0) PA0
10μH317
7593L–AVR–09/12
AT90USB64/128
• Offset: The deviation of the first transition (0x000 to 0x001) compared to the ideal transition
(at 0.5 LSB). Ideal value: 0 LSB
Figure 26-10. Offset error.
• Gain Error: After adjusting for offset, the Gain Error is found as the deviation of the last
transition (0x3FE to 0x3FF) compared to the ideal transition (at 1.5 LSB below maximum).
Ideal value: 0 LSB
Figure 26-11. Gain error.
• Integral non-linearity (INL): After adjusting for offset and gain error, the INL is the maximum
deviation of an actual transition compared to an ideal transition for any code. Ideal value: 0
LSB
Output code
VREF Input voltage
Ideal ADC
Actual ADC
Offset
error
Output code
VREF Input voltage
Ideal ADC
Actual ADC
Gain
error318
7593L–AVR–09/12
AT90USB64/128
Figure 26-12. Integral non-linearity (INL).
• Differential Non-linearity (DNL): The maximum deviation of the actual code width (the interval
between two adjacent transitions) from the ideal code width (1 LSB). Ideal value: 0 LSB
Figure 26-13. Differential non-linearity (DNL).
• Quantization Error: Due to the quantization of the input voltage into a finite number of codes,
a range of input voltages (1 LSB wide) will code to the same value. Always ±0.5 LSB.
• Absolute Accuracy: The maximum deviation of an actual (unadjusted) transition compared to
an ideal transition for any code. This is the compound effect of offset, gain error, differential
error, non-linearity, and quantization error. Ideal value: ±0.5 LSB.
26.8 ADC conversion result
After the conversion is complete (ADIF is high), the conversion result can be found in the ADC
Result Registers (ADCL, ADCH).
Output code
VREF Input voltage
Ideal ADC
Actual ADC
INL
Output code
0x3FF
0x000
0 VREF Input voltage
DNL
1 LSB319
7593L–AVR–09/12
AT90USB64/128
For single ended conversion, the result is:
where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see
Table 26-3 on page 322 and Table 26-4 on page 322). 0x000 represents analog ground, and
0x3FF represents the selected reference voltage minus one LSB.
If differential channels are used, the result is:
where VPOS is the voltage on the positive input pin, VNEG the voltage on the negative input pin,
GAIN the selected gain factor and VREF the selected voltage reference. The result is presented
in two’s complement form, from 0x200 (-512d) through 0x1FF (+511d). Note that if the user
wants to perform a quick polarity check of the result, it is sufficient to read the MSB of the result
(ADC9 in ADCH). If the bit is one, the result is negative, and if this bit is zero, the result is positive.
Figure 26-14 shows the decoding of the differential input range.
Table 82 shows the resulting output codes if the differential input channel pair (ADCn - ADCm) is
selected with a reference voltage of VREF.
ADC
VIN ⋅ 1024
VREF
= --------------------------
ADC
VPOS VNEG ( ) – ⋅ ⋅ GAIN 512
VREF
= ------------------------------------------------------------------------320
7593L–AVR–09/12
AT90USB64/128
Figure 26-14. Differential measurement range.
0
Output code
0x1FF
0x000
VREF Differential input
voltage (volts)
0x3FF
0x200
- VREF321
7593L–AVR–09/12
AT90USB64/128
Example 1:
– ADMUX = 0xED (ADC3 - ADC2, 10× gain, 2.56V reference, left adjusted result)
– Voltage on ADC3 is 300mV, voltage on ADC2 is 500mV.
– ADCR = 512 × 10 × (300 - 500) / 2560 = -400 = 0x270
– ADCL will thus read 0x00, and ADCH will read 0x9C.
Writing zero to ADLAR right adjusts the result: ADCL = 0x70, ADCH = 0x02.
Example 2:
– ADMUX = 0xFB (ADC3 - ADC2, 1× gain, 2.56V reference, left adjusted result)
– Voltage on ADC3 is 300mV, voltage on ADC2 is 500mV.
– ADCR = 512 × 1 × (300 - 500) / 2560 = -41 = 0x029.
– ADCL will thus read 0x40, and ADCH will read 0x0A.
Writing zero to ADLAR right adjusts the result: ADCL = 0x00, ADCH = 0x29.
26.9 ADC register description
26.9.1 ADMUX – ADC Multiplexer Selection Register
• Bit 7:6 – REFS1:0: Reference Selection bits
These bits select the voltage reference for the ADC, as shown in Table 26-3 on page 322. If
these bits are changed during a conversion, the change will not go in effect until this conversion
Table 26-2. Correlation between input voltage and output codes.
VADCn Read code Corresponding decimal value
VADCm + VREF /GAIN 0x1FF 511
VADCm + 0.999 VREF /GAIN 0x1FF 511
VADCm + 0.998 VREF /GAIN 0x1FE 510
... ... ...
VADCm + 0.001 VREF /GAIN 0x001 1
VADCm 0x000 0
VADCm - 0.001 VREF /GAIN 0x3FF -1
... ... ...
VADCm - 0.999 VREF /GAIN 0x201 -511
VADCm - VREF /GAIN 0x200 -512
Bit 7 6 5 4 3 2 1 0
REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0 ADMUX
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0322
7593L–AVR–09/12
AT90USB64/128
is complete (ADIF in ADCSRA is set). The internal voltage reference options may not be used if
an external reference voltage is being applied to the AREF pin.
• Bit 5 – ADLAR: ADC Left Adjust Result
The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register.
Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted. Changing the
ADLAR bit will affect the ADC Data Register immediately, regardless of any ongoing conversions.
For a complete description of this bit, see “ADCL and ADCH – The ADC data register” on
page 324.
• Bits 4:0 – MUX4:0: Analog Channel Selection bits
The value of these bits selects which combination of analog inputs are connected to the ADC.
These bits also select the gain for the differential channels. See Table 26-4 for details. If these
bits are changed during a conversion, the change will not go in effect until this conversion is
complete (ADIF in ADCSRA is set).
Table 26-3. Voltage reference selections for ADC.
REFS1 REFS0 Voltage reference selection
0 0 AREF, internal VREF turned off
0 1 AVCC with external capacitor on AREF pin
1 0 Reserved
1 1 Internal 2.56V Voltage Reference with external capacitor on AREF pin
Table 26-4. Input channel and gain selections.
MUX4..0 Single ended input Positive differential input Negative differential input Gain
00000 ADC0
N/A
00001 ADC1
00010 ADC2
00011 ADC3
00100 ADC4
00101 ADC5
00110 ADC6
00111 ADC7323
7593L–AVR–09/12
AT90USB64/128
26.9.2 ADCSRA – ADC Control and Status Register A
• Bit 7 – ADEN: ADC Enable
Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the
ADC off while a conversion is in progress, will terminate this conversion.
• Bit 6 – ADSC: ADC Start Conversion
In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode,
write this bit to one to start the first conversion. The first conversion after ADSC has been written
after the ADC has been enabled, or if ADSC is written at the same time as the ADC is enabled,
01000
N/A
(ADC0 / ADC0 / 10x)
01001 ADC1 ADC0 10×
01010 (ADC0 / ADC0 / 200x)
01011 ADC1 ADC0 200×
01100 (Reserved - ADC2 / ADC2 / 10x)
01101 ADC3 ADC2 10×
01110 (ADC2 / ADC2 / 200x)
01111 ADC3 ADC2 200×
10000 ADC0 ADC1 1×
10001 (ADC1 / ADC1 / 1x)
10010 ADC2 ADC1 1×
10011 ADC3 ADC1 1×
10100 ADC4 ADC1 1×
10101 ADC5 ADC1 1×
10110 ADC6 ADC1 1×
10111 ADC7 ADC1 1×
11000 ADC0 ADC2 1×
11001 ADC1 ADC2 1×
11010 (ADC2 / ADC2 / 1x)
11011 ADC3 ADC2 1×
11100 ADC4 ADC2 1×
11101 ADC5 ADC2 1×
11110 1.1V (VBand Gap) N/A
11111 0V (GND)
Table 26-4. Input channel and gain selections. (Continued)
MUX4..0 Single ended input Positive differential input Negative differential input Gain
Bit 7 6 5 4 3 2 1 0
ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 ADCSRA
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0324
7593L–AVR–09/12
AT90USB64/128
will take 25 ADC clock cycles instead of the normal 13. This first conversion performs initialization
of the ADC.
ADSC will read as one as long as a conversion is in progress. When the conversion is complete,
it returns to zero. Writing zero to this bit has no effect.
• Bit 5 – ADATE: ADC Auto Trigger Enable
When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion
on a positive edge of the selected trigger signal. The trigger source is selected by setting
the ADC Trigger Select bits, ADTS in ADCSRB.
• Bit 4 – ADIF: ADC Interrupt Flag
This bit is set when an ADC conversion completes and the Data Registers are updated. The
ADC Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set.
ADIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively,
ADIF is cleared by writing a logical one to the flag. Beware that if doing a Read-ModifyWrite
on ADCSRA, a pending interrupt can be disabled. This also applies if the SBI and CBI
instructions are used.
• Bit 3 – ADIE: ADC Interrupt Enable
When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt
is activated.
• Bits 2:0 – ADPS2:0: ADC Prescaler Select Bits
These bits determine the division factor between the XTAL frequency and the input clock to the
ADC.
26.9.3 ADCL and ADCH – The ADC data register
26.9.3.1 ADLAR = 0
Table 26-5. ADC prescaler selections.
ADPS2 ADPS1 ADPS0 Division factor
000 2
001 2
010 4
011 8
1 0 0 16
1 0 1 32
1 1 0 64
1 1 1 128
Bit 15 14 13 12 11 10 9 8
– – – – – – ADC9 ADC8 ADCH
ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 ADCL
Bit 7 6 5 4 3 2 1 0
Read/write R R R R R R R R
RRRRRRRR
Initial value 0 0 0 0 0 0 0 0
00000000325
7593L–AVR–09/12
AT90USB64/128
26.9.3.2 ADLAR = 1
When an ADC conversion is complete, the result is found in these two registers. If differential
channels are used, the result is presented in two’s complement form.
When ADCL is read, the ADC Data Register is not updated until ADCH is read. Consequently, if
the result is left adjusted and no more than 8-bit precision (7 bit + sign bit for differential input
channels) is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then
ADCH.
The ADLAR bit in ADMUX, and the MUXn bits in ADMUX affect the way the result is read from
the registers. If ADLAR is set, the result is left adjusted. If ADLAR is cleared (default), the result
is right adjusted.
• ADC9:0: ADC Conversion Result
These bits represent the result from the conversion, as detailed in “ADC conversion result” on
page 318.
26.9.4 ADCSRB – ADC Control and Status Register B
• Bit 7 – ADHSM: ADC High Speed Mode
Writing this bit to one enables the ADC High Speed mode. This mode enables higher conversion
rate at the expense of higher power consumption.
• Bit 2:0 – ADTS2:0: ADC Auto Trigger Source
If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger
an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion
will be triggered by the rising edge of the selected interrupt flag. Note that switching from a trigger
source that is cleared to a trigger source that is set, will generate a positive edge on the
trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching to Free Running
mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set.
Bit 15 14 13 12 11 10 9 8
ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADCH
ADC1 ADC0 – ––––– ADCL
Bit 7 6 5 4 3 2 1 0
Read/write R R R R R R R R
RRRRRRRR
Initial value 0 0 0 0 0 0 0 0
00000000
Bit 7 6 5 4 3 2 1 0
ADHSM ACME – – – ADTS2 ADTS1 ADTS0 ADCSRB
Read/write R/W R/W R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Table 26-6. ADC auto trigger source selections.
ADTS2 ADTS1 ADTS0 Trigger source
0 0 0 Free running mode
0 0 1 Analog comparator
0 1 0 External interrupt request 0
0 1 1 Timer/Counter0 compare match326
7593L–AVR–09/12
AT90USB64/128
26.9.5 DIDR0 – Digital Input Disable Register 0
• Bit 7:0 – ADC7D..ADC0D: ADC7:0 Digital Input Disable
When this bit is written logic one, the digital input buffer on the corresponding ADC pin is disabled.
The corresponding PIN Register bit will always read as zero when this bit is set. When an
analog signal is applied to the ADC7..0 pin and the digital input from this pin is not needed, this
bit should be written logic one to reduce power consumption in the digital input buffer.
1 0 0 Timer/Counter0 overflow
1 0 1 Timer/Counter1 compare match B
1 1 0 Timer/Counter1 overflow
1 1 1 Timer/Counter1 capture event
Table 26-6. ADC auto trigger source selections. (Continued)
ADTS2 ADTS1 ADTS0 Trigger source
Bit 7 6 5 4 3 2 1 0
ADC7D ADC6D ADC5D ADC4D ADC3D ADC2D ADC1D ADC0D DIDR0
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0327
7593L–AVR–09/12
AT90USB64/128
27. JTAG interface and on-chip debug system
27.0.1 Features
• JTAG (IEEE std. 1149.1 compliant) interface
• Boundary-scan capabilities according to the IEEE std. 1149.1 (JTAG) standard
• Debugger access to:
– All internal peripheral units
– Internal and external RAM
– The internal register file
– Program counter
– EEPROM and flash memories
• Extensive on-chip debug support for break conditions, including
– AVR break instruction
– Break on change of program memory flow
– Single step break
– Program memory break points on single address or address range
– Data memory break points on single address or address range
• Programming of flash, EEPROM, fuses, and lock bits through the JTAG interface
• On-chip debugging supported by Atmel AVR Studio®
27.1 Overview
The AVR IEEE std. 1149.1 compliant JTAG interface can be used for
• Testing PCBs by using the JTAG Boundary-scan capability
• Programming the non-volatile memories, Fuses and Lock bits
• On-chip debugging
A brief description is given in the following sections. Detailed descriptions for Programming via
the JTAG interface, and using the Boundary-scan Chain can be found in the sections “Programming
via the JTAG interface” on page 377 and “IEEE 1149.1 (JTAG) boundary-scan” on page
333, respectively. The On-chip Debug support is considered being private JTAG instructions,
and distributed within Atmel and to selected third party vendors only.
Figure 27-1 on page 328 shows a block diagram of the JTAG interface and the On-chip Debug
system. The TAP Controller is a state machine controlled by the TCK and TMS signals. The TAP
Controller selects either the JTAG Instruction Register or one of several Data Registers as the
scan chain (Shift Register) between the TDI – input and TDO – output. The Instruction Register
holds JTAG instructions controlling the behavior of a Data Register.
The ID-Register, Bypass Register, and the Boundary-scan Chain are the Data Registers used
for board-level testing. The JTAG Programming Interface (actually consisting of several physical
and virtual Data Registers) is used for serial programming via the JTAG interface. The Internal
Scan Chain and Break Point Scan Chain are used for On-chip debugging only.
27.2 TAP – Test Access Port
The JTAG interface is accessed through four of the AVR’s pins. In JTAG terminology, these pins
constitute the Test Access Port – TAP. These pins are:
• TMS: Test mode select. This pin is used for navigating through the TAP-controller state
machine
• TCK: Test Clock. JTAG operation is synchronous to TCK328
7593L–AVR–09/12
AT90USB64/128
• TDI: Test Data In. Serial input data to be shifted in to the Instruction Register or Data Register
(Scan Chains)
• TDO: Test Data Out. Serial output data from Instruction Register or Data Register
The IEEE std. 1149.1 also specifies an optional TAP signal; TRST – Test ReSeT – which is not
provided.
When the JTAGEN Fuse is unprogrammed, these four TAP pins are normal port pins, and the
TAP controller is in reset. When programmed, the input TAP signals are internally pulled high
and the JTAG is enabled for Boundary-scan and programming. The device is shipped with this
fuse programmed.
For the On-chip Debug system, in addition to the JTAG interface pins, the RESET pin is monitored
by the debugger to be able to detect external reset sources. The debugger can also pull
the RESET pin low to reset the whole system, assuming only open collectors on the reset line
are used in the application.
Figure 27-1. Block diagram.
TAP
CONTROLLER
TDI
TDO
TCK
TMS
FLASH
MEMORY
AVR CPU
DIGITAL
PERIPHERAL
UNITS
JTAG / AVR CORE
COMMUNICATION
INTERFACE
BREAKPOINT
UNIT FLOW CONTROL
UNIT
OCD STATUS
AND CONTROL
INTERNAL
SCAN
CHAIN
M
U
X
INSTRUCTION
REGISTER
ID
REGISTER
BYPASS
REGISTER
JTAG PROGRAMMING
INTERFACE
PC
Instruction
Address
Data
BREAKPOINT
SCAN CHAIN
ADDRESS
DECODER
ANALOG
PERIPHERIAL
UNITS
I/O PORT 0
I/O PORT n
BOUNDARY SCAN CHAIN
Analog inputs
Control & clock lines
DEVICE BOUNDARY329
7593L–AVR–09/12
AT90USB64/128
Figure 27-2. TAP controller state diagram.
27.3 TAP Controller
The TAP Controller is a 16-state finite state machine that controls the operation of the Boundaryscan
circuitry, JTAG programming circuitry, or On-chip Debug system. The state transitions
depicted in Figure 27-2 depend on the signal present on TMS (shown adjacent to each state
transition) at the time of the rising edge at TCK. The initial state after a Power-on Reset is TestLogic-Reset.
As a definition in this document, the LSB is shifted in and out first for all Shift Registers.
Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG interface is:
• At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift
Instruction Register – Shift-IR state. While in this state, shift the four bits of the JTAG
instructions into the JTAG Instruction Register from the TDI input at the rising edge of TCK.
The TMS input must be held low during input of the three LSBs in order to remain in the ShiftIR
state. The MSB of the instruction is shifted in when this state is left by setting TMS high.
While the instruction is shifted in from the TDI pin, the captured IR-state 0x01 is shifted out on
the TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI
and TDO and controls the circuitry surrounding the selected Data Register
Test-logic-reset
Run-test/idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR scan
Capture-DR
0
1
0 11 1
0 0
0 0
1 1
1 0
1
1
0
1
0
0
1 0
1
1
0
1
0
0
0 0
1 1330
7593L–AVR–09/12
AT90USB64/128
• Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched
onto the parallel output from the Shift Register path in the Update-IR state. The Exit-IR,
Pause-IR, and Exit2-IR states are only used for navigating the state machine
• At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift
Data Register – Shift-DR state. While in this state, upload the selected Data Register
(selected by the present JTAG instruction in the JTAG Instruction Register) from the TDI input
at the rising edge of TCK. In order to remain in the Shift-DR state, the TMS input must be
held low during input of all bits except the MSB. The MSB of the data is shifted in when this
state is left by setting TMS high. While the Data Register is shifted in from the TDI pin, the
parallel inputs to the Data Register captured in the Capture-DR state is shifted out on the
TDO pin
• Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected Data
Register has a latched parallel-output, the latching takes place in the Update-DR state. The
Exit-DR, Pause-DR, and Exit2-DR states are only used for navigating the state machine
As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting
JTAG instruction and using Data Registers, and some JTAG instructions may select certain
functions to be performed in the Run-Test/Idle, making it unsuitable as an Idle state.
Note: Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be
entered by holding TMS high for five TCK clock periods.
For detailed information on the JTAG specification, refer to the literature listed in “Bibliography”
on page 332.
27.4 Using the Boundary-scan chain
A complete description of the Boundary-scan capabilities are given in the section “IEEE 1149.1
(JTAG) boundary-scan” on page 333.
27.5 Using the on-chip debug system
As shown in Figure 27-1 on page 328, the hardware support for on-chip debugging consists
mainly of
• A scan chain on the interface between the internal AVR CPU and the internal peripheral units
• Break Point unit
• Communication interface between the CPU and JTAG system
All read or modify/write operations needed for implementing the Debugger are done by applying
AVR instructions via the internal AVR CPU Scan Chain. The CPU sends the result to an I/O
memory mapped location which is part of the communication interface between the CPU and the
JTAG system.
The Break Point Unit implements Break on Change of Program Flow, Single Step Break, two
Program Memory Break Points, and two combined Break Points. Together, the four Break
Points can be configured as either:
• Four single program memory break points
• Three single program memory break point + one single data memory break point
• Two single program memory break points + two single data memory break points
• Two single program memory break points + one program memory break point with mask
(“range Break Point”)331
7593L–AVR–09/12
AT90USB64/128
• Two single program memory break points + one data memory break point with mask (“range
Break Point”)
A debugger, like the Atmel AVR Studio, may however use one or more of these resources for its
internal purpose, leaving less flexibility to the end-user.
A list of the On-chip Debug specific JTAG instructions is given in “On-chip debug specific JTAG
instructions” on page 331.
The JTAGEN Fuse must be programmed to enable the JTAG Test Access Port. In addition, the
OCDEN Fuse must be programmed and no Lock bits must be set for the On-chip debug system
to work. As a security feature, the On-chip debug system is disabled when either of the LB1 or
LB2 Lock bits are set. Otherwise, the On-chip debug system would have provided a back-door
into a secured device.
The AVR Studio enables the user to fully control execution of programs on an AVR device with
On-chip Debug capability, AVR In-Circuit Emulator, or the built-in AVR Instruction Set Simulator.
AVR Studio supports source level execution of Assembly programs assembled with Atmel Corporation’s
AVR Assembler and C programs compiled with third party vendors’ compilers.
AVR Studio runs under Microsoft® Windows® 95/98/2000 and Microsoft Windows NT.
For a full description of the Atmel AVR Studio, please refer to the AVR Studio User Guide. Only
highlights are presented in this document.
All necessary execution commands are available in AVR Studio, both on source level and on
disassembly level. The user can execute the program, single step through the code either by
tracing into or stepping over functions, step out of functions, place the cursor on a statement and
execute until the statement is reached, stop the execution, and reset the execution target. In
addition, the user can have an unlimited number of code Break Points (using the BREAK
instruction) and up to two data memory Break Points, alternatively combined as a mask (range)
Break Point.
27.6 On-chip debug specific JTAG instructions
The On-chip debug support is considered being private JTAG instructions, and distributed within
ATMEL and to selected third party vendors only. Instruction opcodes are listed for reference.
27.6.1 PRIVATE0; 0x8
Private JTAG instruction for accessing On-chip debug system.
27.6.2 PRIVATE1; 0x9
Private JTAG instruction for accessing On-chip debug system.
27.6.3 PRIVATE2; 0xA
Private JTAG instruction for accessing On-chip debug system.
27.6.4 PRIVATE3; 0xB
Private JTAG instruction for accessing On-chip debug system.332
7593L–AVR–09/12
AT90USB64/128
27.7 On-chip Debug related Register in I/O memory
27.7.1 OCDR – On-chip Debug Register
The OCDR Register provides a communication channel from the running program in the microcontroller
to the debugger. The CPU can transfer a byte to the debugger by writing to this
location. At the same time, an internal flag; I/O Debug Register Dirty – IDRD – is set to indicate
to the debugger that the register has been written. When the CPU reads the OCDR Register the
seven LSB will be from the OCDR Register, while the MSB is the IDRD bit. The debugger clears
the IDRD bit when it has read the information.
In some AVR devices, this register is shared with a standard I/O location. In this case, the OCDR
Register can only be accessed if the OCDEN Fuse is programmed, and the debugger enables
access to the OCDR Register. In all other cases, the standard I/O location is accessed.
Refer to the debugger documentation for further information on how to use this register.
27.8 Using the JTAG programming capabilities
Programming of AVR parts via JTAG is performed via the 4-pin JTAG port, TCK, TMS, TDI, and
TDO. These are the only pins that need to be controlled/observed to perform JTAG programming
(in addition to power pins). It is not required to apply 12V externally. The JTAGEN Fuse
must be programmed and the JTD bit in the MCUCR Register must be cleared to enable the
JTAG Test Access Port.
The JTAG programming capability supports:
• Flash programming and verifying
• EEPROM programming and verifying
• Fuse programming and verifying
• Lock bit programming and verifying
The Lock bit security is exactly as in parallel programming mode. If the Lock bits LB1 or LB2 are
programmed, the OCDEN Fuse cannot be programmed unless first doing a chip erase. This is a
security feature that ensures no back-door exists for reading out the content of a secured
device.
The details on programming through the JTAG interface and programming specific JTAG
instructions are given in the section “Programming via the JTAG interface” on page 377.
27.9 Bibliography
For more information about general Boundary-scan, the following literature can be consulted:
• IEEE: IEEE Std. 1149.1-1990. IEEE Standard Test Access Port and Boundary-scan
Architecture, IEEE, 1993.
• Colin Maunder: The Board Designers Guide to Testable Logic Circuits, Addison-Wesley,
1992.
Bit 7 6 5 4 3 2 1 0
MSB/IDRD LSB OCDR
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0333
7593L–AVR–09/12
AT90USB64/128
28. IEEE 1149.1 (JTAG) boundary-scan
28.1 Features
• JTAG (IEEE std. 1149.1 compliant) interface
• Boundary-scan capabilities according to the JTAG standard
• Full scan of all port functions as well as analog circuitry having off-chip connections
• Supports the optional IDCODE instruction
• Additional public AVR_RESET instruction to reset the AVR
28.2 System overview
The Boundary-scan chain has the capability of driving and observing the logic levels on the digital
I/O pins, as well as the boundary between digital and analog logic for analog circuitry having
off-chip connections. At system level, all ICs having JTAG capabilities are connected serially by
the TDI/TDO signals to form a long Shift Register. An external controller sets up the devices to
drive values at their output pins, and observe the input values received from other devices. The
controller compares the received data with the expected result. In this way, Boundary-scan provides
a mechanism for testing interconnections and integrity of components on Printed Circuits
Boards by using the four TAP signals only.
The four IEEE 1149.1 defined mandatory JTAG instructions IDCODE, BYPASS, SAMPLE/PRELOAD,
and EXTEST, as well as the AVR specific public JTAG instruction AVR_RESET can be
used for testing the Printed Circuit Board. Initial scanning of the Data Register path will show the
ID-Code of the device, since IDCODE is the default JTAG instruction. It may be desirable to
have the AVR device in reset during test mode. If not reset, inputs to the device may be determined
by the scan operations, and the internal software may be in an undetermined state when
exiting the test mode. Entering reset, the outputs of any port pin will instantly enter the high
impedance state, making the HIGHZ instruction redundant. If needed, the BYPASS instruction
can be issued to make the shortest possible scan chain through the device. The device can be
set in the reset state either by pulling the external RESET pin low, or issuing the AVR_RESET
instruction with appropriate setting of the Reset Data Register.
The EXTEST instruction is used for sampling external pins and loading output pins with data.
The data from the output latch will be driven out on the pins as soon as the EXTEST instruction
is loaded into the JTAG IR-Register. Therefore, the SAMPLE/PRELOAD should also be used for
setting initial values to the scan ring, to avoid damaging the board when issuing the EXTEST
instruction for the first time. SAMPLE/PRELOAD can also be used for taking a snapshot of the
external pins during normal operation of the part.
The JTAGEN Fuse must be programmed and the JTD bit in the I/O Register MCUCR must be
cleared to enable the JTAG Test Access Port.
When using the JTAG interface for Boundary-scan, using a JTAG TCK clock frequency higher
than the internal chip frequency is possible. The chip clock is not required to run.
28.3 Data registers
The Data Registers relevant for Boundary-scan operations are:
• Bypass Register
• Device Identification Register
• Reset Register
• Boundary-scan Chain334
7593L–AVR–09/12
AT90USB64/128
28.3.1 Bypass register
The Bypass register consists of a single Shift register stage. When the Bypass register is
selected as path between TDI and TDO, the register is reset to 0 when leaving the Capture-DR
controller state. The Bypass register can be used to shorten the scan chain on a system when
the other devices are to be tested.
28.3.2 Device Identification register
Figure 28-1 shows the structure of the Device Identification register.
Figure 28-1. The Format of the Device Identification register.
28.3.2.1 Version
Version is a 4-bit number identifying the revision of the component. The JTAG version number
follows the revision of the device. Revision A is 0x0, revision B is 0x1 and so on.
28.3.2.2 Part number
The part number is a 16-bit code identifying the component. The JTAG Part Number for Atmel
AT90USB64/128 is listed in Table 28-1.
28.3.2.3 Manufacturer ID
The Manufacturer ID is a 11-bit code identifying the manufacturer. The JTAG manufacturer ID
for ATMEL is listed in Table 28-2.
28.3.3 Reset register
The Reset Register is a test Data Register used to reset the part. Since the AVR tri-states Port
Pins when reset, the Reset Register can also replace the function of the un-implemented
optional JTAG instruction HIGHZ.
A high value in the Reset Register corresponds to pulling the external Reset low. The part is
reset as long as there is a high value present in the Reset Register. Depending on the fuse settings
for the clock options, the part will remain reset for a reset time-out period (refer to “Clock
sources” on page 41) after releasing the Reset Register. The output from this Data Register is
not latched, so the reset will take place immediately, as shown in Figure 28-2 on page 335.
MSB LSB
Bit 31 28 27 12 11 1 0
Device ID Version Part number Manufacturer ID 1
4 bits 16 bits 11 bits 1-bit
Table 28-1. AVR JTAG part number.
Part number JTAG part number (hex)
AVR USB 0x9782
Table 28-2. Manufacturer ID.
Manufacturer JTAG manufacturer ID (hex)
ATMEL 0x01F335
7593L–AVR–09/12
AT90USB64/128
Figure 28-2. Reset register.
28.3.4 Boundary-scan Chain
The Boundary-scan Chain has the capability of driving and observing the logic levels on the digital
I/O pins, as well as the boundary between digital and analog logic for analog circuitry having
off-chip connections.
See “Boundary-scan chain” on page 337 for a complete description.
28.4 Boundary-scan specific JTAG instructions
The Instruction Register is 4-bit wide, supporting up to 16 instructions. Listed below are the
JTAG instructions useful for Boundary-scan operation. Note that the optional HIGHZ instruction
is not implemented, but all outputs with tri-state capability can be set in high-impedant state by
using the AVR_RESET instruction, since the initial state for all port pins is tri-state.
As a definition in this datasheet, the LSB is shifted in and out first for all Shift Registers.
The OPCODE for each instruction is shown behind the instruction name in hex format. The text
describes which Data Register is selected as path between TDI and TDO for each instruction.
28.4.1 EXTEST; 0x0
Mandatory JTAG instruction for selecting the Boundary-scan Chain as Data Register for testing
circuitry external to the AVR package. For port-pins, Pull-up Disable, Output Control, Output
Data, and Input Data are all accessible in the scan chain. For Analog circuits having off-chip
connections, the interface between the analog and the digital logic is in the scan chain. The contents
of the latched outputs of the Boundary-scan chain is driven out as soon as the JTAG IRRegister
is loaded with the EXTEST instruction.
The active states are:
• Capture-DR: Data on the external pins are sampled into the Boundary-scan Chain
• Shift-DR: The Internal Scan Chain is shifted by the TCK input
• Update-DR: Data from the scan chain is applied to output pins
28.4.2 IDCODE; 0x1
Optional JTAG instruction selecting the 32-bit ID-Register as Data Register. The ID-Register
consists of a version number, a device number and the manufacturer code chosen by JEDEC.
This is the default instruction after power-up.
D Q From
TDI
ClockDR · AVR_RESET
To
TDO
From other internal and
external reset sources
Internal reset336
7593L–AVR–09/12
AT90USB64/128
The active states are:
• Capture-DR: Data in the IDCODE Register is sampled into the Boundary-scan Chain
• Shift-DR: The IDCODE scan chain is shifted by the TCK input
28.4.3 SAMPLE_PRELOAD; 0x2
Mandatory JTAG instruction for pre-loading the output latches and taking a snap-shot of the
input/output pins without affecting the system operation. However, the output latches are not
connected to the pins. The Boundary-scan Chain is selected as Data Register.
The active states are:
• Capture-DR: Data on the external pins are sampled into the Boundary-scan Chain
• Shift-DR: The Boundary-scan Chain is shifted by the TCK input
• Update-DR: Data from the Boundary-scan chain is applied to the output latches. However,
the output latches are not connected to the pins
28.4.4 AVR_RESET; 0xC
The AVR specific public JTAG instruction for forcing the AVR device into the Reset mode or
releasing the JTAG reset source. The TAP controller is not reset by this instruction. The one bit
Reset Register is selected as Data Register. Note that the reset will be active as long as there is
a logic “one” in the Reset Chain. The output from this chain is not latched.
The active states are:
• Shift-DR: The Reset Register is shifted by the TCK input
28.4.5 BYPASS; 0xF
Mandatory JTAG instruction selecting the Bypass Register for Data Register.
The active states are:
• Capture-DR: Loads a logic “0” into the Bypass Register
• Shift-DR: The Bypass Register cell between TDI and TDO is shifted
28.5 Boundary-scan Related Register in I/O memory
28.5.1 MCUCR – MCU Control Register
The MCU Control Register contains control bits for general MCU functions.
• Bits 7 – JTD: JTAG Interface Disable
When this bit is zero, the JTAG interface is enabled if the JTAGEN Fuse is programmed. If this
bit is one, the JTAG interface is disabled. In order to avoid unintentional disabling or enabling of
the JTAG interface, a timed sequence must be followed when changing this bit: The application
software must write this bit to the desired value twice within four cycles to change its value. Note
that this bit must not be altered when using the On-chip Debug system.
Bit 7 6 5 4 3 2 1 0
JTD – – PUD – – IVSEL IVCE MCUCR
Read/write R/W R R R/W R R R/W R/W
Initial value 0 0 0 0 0 0 0 0337
7593L–AVR–09/12
AT90USB64/128
28.5.2 MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU reset.
• Bit 4 – JTRF: JTAG Reset Flag
This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by
the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic
zero to the flag.
28.6 Boundary-scan chain
The Boundary-scan chain has the capability of driving and observing the logic levels on the digital
I/O pins, as well as the boundary between digital and analog logic for analog circuitry having
off-chip connection.
28.6.1 Scanning the digital port pins
Figure 28-3 on page 338 shows the Boundary-scan Cell for a bi-directional port pin. The pull-up
function is disabled during Boundary-scan when the JTAG IC contains EXTEST or
SAMPLE_PRELOAD. The cell consists of a bi-directional pin cell that combines the three signals
Output Control - OCxn, Output Data - ODxn, and Input Data - IDxn, into only a two-stage
Shift Register. The port and pin indexes are not used in the following description
The Boundary-scan logic is not included in the figures in the datasheet. Figure 28-4 on page 339
shows a simple digital port pin as described in the section “I/O-ports” on page 71. The Boundaryscan
details from Figure 28-3 on page 338 replaces the dashed box in Figure 28-4 on page 339.
When no alternate port function is present, the Input Data - ID - corresponds to the PINxn Register
value (but ID has no synchronizer), Output Data corresponds to the PORT Register, Output
Control corresponds to the Data Direction - DD Register, and the Pull-up Enable - PUExn - corresponds
to logic expression PUD · DDxn · PORTxn.
Digital alternate port functions are connected outside the dotted box in Figure 28-4 on page 339
to make the scan chain read the actual pin value. For analog function, there is a direct connection
from the external pin to the analog circuit. There is no scan chain on the interface between
the digital and the analog circuitry, but some digital control signal to analog circuitry are turned
off to avoid driving contention on the pads.
When JTAG IR contains EXTEST or SAMPLE_PRELOAD the clock is not sent out on the port
pins even if the CKOUT fuse is programmed. Even though the clock is output when the JTAG IR
contains SAMPLE_PRELOAD, the clock is not sampled by the boundary scan.
Bit 7 6 5 4 3 2 1 0
– – – JTRF WDRF BORF EXTRF PORF MCUSR
Read/write R R R R/W R/W R/W R/W R/W
Initial value 0 0 0 See bit description338
7593L–AVR–09/12
AT90USB64/128
Figure 28-3. Boundary-scan cell for bi-directional port pin with pull-up function.
D Q D Q
G
0
1 0
1
D Q D Q
G
0
1 0
1
0
1
Port Pin (PXn)
ShiftDR To next cell EXTEST Vcc
Output control (OC)
Output data (OD)
Input data (ID)
From last cell ClockDR UpdateDR
FF1 LD1
FF0 LD0
0
1
Pull-up enable (PUE)339
7593L–AVR–09/12
AT90USB64/128
Figure 28-4. General port pin schematic diagram.
28.6.2 Scanning the RESET pin
The RESET pin accepts 5V active low logic for standard reset operation, and 12V active high
logic for High Voltage Parallel programming. An observe-only cell as shown in Figure 28-5 is
inserted for the 5V reset signal.
Figure 28-5. Observe-only cell.
CLK
RPx
RRx
WRx
RDx
WDx
PUD
SYNCHRONIZER
WDx: WRITE DDRx
WRx: WRITE PORTx
RRx: READ PORTx REGISTER
RPx: READ PORTx PIN
PUD: PULLUP DISABLE
CLK : I/O CLOCK
RDx: READ DDRx
D
L
Q
Q
RESET
RESET
Q
D Q
Q
Q D
CLR
PORTxn
Q
Q D
CLR
DDxn
PINxn
DATA BUS
SLEEP
SLEEP: SLEEP CONTROL
Pxn
I/O
I/O
See Boundary-scan
description for details!
PUExn
OCxn
ODxn
IDxn
PUExn: PULLUP ENABLE for pin Pxn
OCxn: OUTPUT CONTROL for pin Pxn
ODxn: OUTPUT DATA to pin Pxn
IDxn: INPUT DATA from pin Pxn
0
1
D Q
From
previous
cell
ClockDR
ShiftDR
To
next
cell
From system pin To system logic
FF1340
7593L–AVR–09/12
AT90USB64/128
28.7 Atmel AT90USB64/128 Boundary-scan order
Table 28-3 shows the Scan order between TDI and TDO when the Boundary-scan chain is
selected as data path. Bit 0 is the LSB; the first bit scanned in, and the first bit scanned out. The
scan order follows the pin-out order as far as possible. Therefore, the bits of Port A and Port Fis
scanned in the opposite bit order of the other ports. Exceptions from the rules are the Scan
chains for the analog circuits, which constitute the most significant bits of the scan chain regardless
of which physical pin they are connected to. In Figure 28-3 on page 338, PXn. Data
corresponds to FF0, PXn. Control corresponds to FF1, PXn. Bit 4, 5, 6 and 7 of Port F is not in
the scan chain, since these pins constitute the TAP pins when the JTAG is enabled. The USB
pads are not included in the boundary-scan.
Table 28-3. AT90USB64/128 Boundary-scan order.
Bit number Signal name Module
88 PE6.Data
Port E
87 PE6.Control
86 PE7.Data
85 PE7.Control
84 PE3.Data
83 PE3.Control
82 PB0.Data
Port B
81 PB0.Control
80 PB1.Data
79 PB1.Control
78 PB2.Data
77 PB2.Control
76 PB3.Data
75 PB3.Control
74 PB4.Data
73 PB4.Control
72 PB5.Data
71 PB5.Control
70 PB6.Data
69 PB6.Control
68 PB7.Data
67 PB7.Control
66 PE4.Data
PORTE
65 PE4.Control
64 PE5.Data
63 PE5.Control
62 RSTT Reset Logic (observe only)341
7593L–AVR–09/12
AT90USB64/128
61 PD0.Data
Port D
60 PD0.Control
59 PD1.Data
58 PD1.Control
57 PD2.Data
56 PD2.Control
55 PD3.Data
54 PD3.Control
53 PD4.Data
52 PD4.Control
51 PD5.Data
50 PD5.Control
49 PD6.Data
48 PD6.Control
47 PD7.Data
46 PD7.Control
45 PE0.Data
Port E
44 PE0.Control
43 PE1.Data
42 PE1.Control
41 PC0.Data
Port C
40 PC0.Control
39 PC1.Data
38 PC1.Control
37 PC2.Data
36 PC2.Control
35 PC3.Data
34 PC3.Control
33 PC4.Data
32 PC4.Control
31 PC5.Data
30 PC5.Control
29 PC6.Data
28 PC6.Control
27 PC7.Data
26 PC7.Control
Table 28-3. AT90USB64/128 Boundary-scan order. (Continued)
Bit number Signal name Module342
7593L–AVR–09/12
AT90USB64/128
28.8 Boundary-scan description language files
Boundary-scan Description Language (BSDL) files describe Boundary-scan capable devices in
a standard format used by automated test-generation software. The order and function of bits in
the Boundary-scan Data Register are included in this description. BSDL files are available for
Atmel AT90USB64/128.
25 PE2.Data
Port E
24 PE2.Control
23 PA7.Data
Port A
22 PA7.Control
21 PA6.Data
20 PA6.Control
19 PA5.Data
18 PA5.Control
17 PA4.Data
16 PA4.Control
15 PA3.Data
14 PA3.Control
13 PA2.Data
12 PA2.Control
11 PA1.Data
10 PA1.Control
9 PA0.Data
8 PA0.Control
7 PF3.Data
Port F
6 PF3.Control
5 PF2.Data
4 PF2.Control
3 PF1.Data
2 PF1.Control
1 PF0.Data
0 PF0.Control
Table 28-3. AT90USB64/128 Boundary-scan order. (Continued)
Bit number Signal name Module343
7593L–AVR–09/12
AT90USB64/128
29. Boot Loader support – read-while-write self-programming
The Boot Loader Support provides a real Read-While-Write Self-Programming mechanism for
downloading and uploading program code by the MCU itself. This feature allows flexible application
software updates controlled by the MCU using a Flash-resident Boot Loader program. The
Boot Loader program can use any available data interface and associated protocol to read code
and write (program) that code into the Flash memory, or read the code from the program memory.
The program code within the Boot Loader section has the capability to write into the entire
Flash, including the Boot Loader memory. The Boot Loader can thus even modify itself, and it
can also erase itself from the code if the feature is not needed anymore. The size of the Boot
Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot
Lock bits which can be set independently. This gives the user a unique flexibility to select different
levels of protection. General information on SPM and ELPM is provided in See “AVR CPU
core” on page 11.
29.1 Boot Loader features
• Read-while-write self-programming
• Flexible boot memory size
• High security (separate boot lock bits for a flexible protection)
• Separate fuse to select reset vector
• Optimized page (1) size
• Code efficient algorithm
• Efficient read-modify-write support
Note: 1. A page is a section in the Flash consisting of several bytes (see Table 30-11 on page 364)
used during programming. The page organization does not affect normal operation.
29.2 Application and Boot Loader flash sections
The Flash memory is organized in two main sections, the Application section and the Boot
Loader section (see Figure 29-2 on page 346). The size of the different sections is configured by
the BOOTSZ Fuses as shown in Table 29-8 on page 357 and Figure 29-2 on page 346. These
two sections can have different level of protection since they have different sets of Lock bits.
29.2.1 Application section
The Application section is the section of the Flash that is used for storing the application code.
The protection level for the Application section can be selected by the application Boot Lock bits
(Boot Lock bits 0), see Table 29-2 on page 347. The Application section can never store any
Boot Loader code since the SPM instruction is disabled when executed from the Application
section.
29.2.2 BLS – Boot Loader section
While the Application section is used for storing the application code, the The Boot Loader software
must be located in the BLS since the SPM instruction can initiate a programming when
executing from the BLS only. The SPM instruction can access the entire Flash, including the
BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader
Lock bits (Boot Lock bits 1), see Table 29-3 on page 347.
29.3 Read-while-write and no read-while-write flash sections
Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader software
update is dependent on which address that is being programmed. In addition to the two344
7593L–AVR–09/12
AT90USB64/128
sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also
divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-WhileWrite
(NRWW) section. The limit between the RWW- and NRWW sections is given in Table 29-
1 and Figure 29-1 on page 345. The main difference between the two sections is:
• When erasing or writing a page located inside the RWW section, the NRWW section can be
read during the operation
• When erasing or writing a page located inside the NRWW section, the CPU is halted during
the entire operation
Note that the user software can never read any code that is located inside the RWW section during
a Boot Loader software operation. The syntax “Read-While-Write section” refers to which
section that is being programmed (erased or written), not which section that actually is being
read during a Boot Loader software update.
29.3.1 RWW – Read-While-Write section
If a Boot Loader software update is programming a page inside the RWW section, it is possible
to read code from the Flash, but only code that is located in the NRWW section. During an ongoing
programming, the software must ensure that the RWW section never is being read. If the
user software is trying to read code that is located inside the RWW section (i.e., by load program
memory, call, or jump instructions or an interrupt) during programming, the software might end
up in an unknown state. To avoid this, the interrupts should either be disabled or moved to the
Boot Loader section. The Boot Loader section is always located in the NRWW section. The
RWW Section Busy bit (RWWSB) in the Store Program Memory Control and Status Register
(SPMCSR) will be read as logical one as long as the RWW section is blocked for reading. After
a programming is completed, the RWWSB must be cleared by software before reading code
located in the RWW section. See “SPMCSR – Store Program Memory Control and Status Register”
on page 349. for details on how to clear RWWSB.
29.3.2 NRWW – No Read-While-Write section
The code located in the NRWW section can be read when the Boot Loader software is updating
a page in the RWW section. When the Boot Loader code updates the NRWW section, the CPU
is halted during the entire Page Erase or Page Write operation.
Table 29-1. Read-While-Write features.
Which section does the Zpointer
address during the
programming?
Which section can
be read during
programming?
Is the CPU
halted?
Read-While-Write
supported?
RWW section NRWW section No Yes
NRWW section None Yes No345
7593L–AVR–09/12
AT90USB64/128
Figure 29-1. Read-While-Write vs. no Read-While-Write.
Read-While-Write
(RWW) section
No Read-While-Write
(NRWW) section
Z-pointer
Addresses RWW
section
Z-pointer
addresses NRWW
section
CPU is halted
during the operation
Code located in
NRWW section.
Can be read during
the operation346
7593L–AVR–09/12
AT90USB64/128
Figure 29-2. Memory sections.
Note: 1. The parameters in the figure above are given in Table 29-8 on page 357.
29.4 Boot Loader lock bits
If no Boot Loader capability is needed, the entire Flash is available for application code. The
Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives
the user a unique flexibility to select different levels of protection.
The user can select:
• To protect the entire Flash from a software update by the MCU
• To protect only the Boot Loader Flash section from a software update by the MCU
• To protect only the Application Flash section from a software update by the MCU
• Allow software update in the entire Flash
See Table 29-2 on page 347 and Table 29-3 on page 347 for further details. The Boot Lock bits
can be set by software and in Serial or in Parallel Programming mode. They can only be cleared
by a Chip Erase command only. The general Write Lock (Lock Bit mode 2) does not control the
programming of the Flash memory by SPM instruction. Similarly, the general Read/Write Lock
(Lock Bit mode 1) does not control reading nor writing by (E)LPM/SPM, if it is attempted.
0x0000
Flashend
Program memory
BOOTSZ = '11'
Application flash section
Boot loader flash section Flashend
Program memory
BOOTSZ = '10'
0x0000
Program memory
BOOTSZ = '01'
Program memory
BOOTSZ = '00'
Application flash section
Boot loader flash section
0x0000
Flashend
Application flash section
Flashend
End RWW
Start NRWW
Application flash section
Boot loader flash section
Boot loader flash section
End RWW
Start NRWW
End RWW
Start NRWW
0x0000
End RWW, end application
Start NRWW, start boot loader
Application flash section Application flash section
Application flash section
Read-While-Write section No Read-While-Write section Read-While-Write section No Read-While-Write section
Read-While-Write section No Read-While-Write section Read-While-Write section No Read-While-Write section
End application
Start boot loader
End application
Start boot loader
End application
Start boot loader347
7593L–AVR–09/12
AT90USB64/128
Note: 1. “1” means unprogrammed, “0” means programmed.
Note: 1. “1” means unprogrammed, “0” means programmed.
29.5 Entering the Boot Loader program
The boot loader can be executed with three different conditions:
29.5.1 Regular application conditions.
A jump or call from the application program. This may be initiated by a trigger such as a command
received via USART, SPI or USB.
29.5.2 Boot Reset fuse
The Boot Reset Fuse (BOOTRST) can be programmed so that the Reset Vector is pointing to
the Boot Flash start address after a reset. In this case, the Boot Loader is started after a reset.
After the application code is loaded, the program can start executing the application code. Note
that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse
is programmed, the Reset Vector will always point to the Boot Loader Reset and the fuse can
only be changed through the serial or parallel programming interface.
Table 29-2. Boot Lock Bit0 protection modes (application section) (1).
BLB0 Mode BLB02 BLB01 Protection
1 11 No restrictions for SPM or (E)LPM accessing the
Application section.
2 1 0 SPM is not allowed to write to the Application section.
3 00
SPM is not allowed to write to the Application section, and
(E)LPM executing from the Boot Loader section is not
allowed to read from the Application section. If Interrupt
Vectors are placed in the Boot Loader section, interrupts
are disabled while executing from the Application section.
4 01
(E)LPM executing from the Boot Loader section is not
allowed to read from the Application section. If Interrupt
Vectors are placed in the Boot Loader section, interrupts
are disabled while executing from the Application section.
Table 29-3. Boot Lock Bit1 protection modes (boot loader section) (1).
BLB1 Mode BLB12 BLB11 Protection
1 11 No restrictions for SPM or (E)LPM accessing the Boot
Loader section.
2 1 0 SPM is not allowed to write to the Boot Loader section.
3 00
SPM is not allowed to write to the Boot Loader section,
and (E)LPM executing from the Application section is not
allowed to read from the Boot Loader section. If Interrupt
Vectors are placed in the Application section, interrupts
are disabled while executing from the Boot Loader section.
4 01
(E)LPM executing from the Application section is not
allowed to read from the Boot Loader section. If Interrupt
Vectors are placed in the Application section, interrupts
are disabled while executing from the Boot Loader section.348
7593L–AVR–09/12
AT90USB64/128
Note: 1. “1” means unprogrammed, “0” means programmed.
29.5.3 External hardware conditions
The Hardware Boot Enable Fuse (HWBE) can be programmed (see Table 29-5) so that upon
special hardware conditions under reset, the boot loader execution is forced after reset.
Note: 1. “1” means unprogrammed, “0” means programmed.
When the HWBE fuse is enable the ALE/HWB pin is configured as input during reset and sampled
during reset rising edge. When ALE/HWB pin is ‘0’ during reset rising edge, the reset vector
will be set as the Boot Loader Reset address and the Boot Loader will be executed (see Figure
29-3).
Figure 29-3. Boot process description.
Table 29-4. Boot reset fuse (1).
BOOTRST Reset address
1 Reset Vector = Application reset (address 0x0000)
0 Reset Vector = Boot loader reset (see Table 29-8 on page 357)
Table 29-5. Hardware boot enable fuse (1).
HWBE Reset address
1 ALE/HWB pin can not be used to force boot loader execution after reset
0 ALE/HWB pin is used during reset to force boot loader execution after reset
HWBE
BOOTRST ?
Ext. hardware
conditions ?
Reset vector = Application reset Reset vector = Boot loader reset
?
RESET
ALE/HWB
t
SHRH t
HHRH349
7593L–AVR–09/12
AT90USB64/128
29.5.4 SPMCSR – Store Program Memory Control and Status Register
The Store Program Memory Control and Status Register contains the control bits needed to control
the Boot Loader operations.
• Bit 7 – SPMIE: SPM Interrupt Enable
When the SPMIE bit is written to one, and the I-bit in the Status Register is set (one), the SPM
ready interrupt will be enabled. The SPM ready Interrupt will be executed as long as the SPMEN
bit in the SPMCSR Register is cleared.
• Bit 6 – RWWSB: Read-While-Write Section Busy
When a Self-Programming (Page Erase or Page Write) operation to the RWW section is initiated,
the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section
cannot be accessed. The RWWSB bit will be cleared if the RWWSRE bit is written to one after a
Self-Programming operation is completed. Alternatively the RWWSB bit will automatically be
cleared if a page load operation is initiated.
• Bit 5 – SIGRD: Signature Row Read
If this bit is written to one at the same time as SPMEN, the next LPM instruction within three
clock cycles will read a byte from the signature row into the destination register. see “Reading
the Signature Row from software” on page 354 for details. An SPM instruction within four cycles
after SIGRD and SPMEN are set will have no effect. This operation is reserved for future use
and should not be used.
• Bit 4 – RWWSRE: Read-While-Write Section Read Enable
When programming (Page Erase or Page Write) to the RWW section, the RWW section is
blocked for reading (the RWWSB will be set by hardware). To re-enable the RWW section, the
user software must wait until the programming is completed (SPMEN will be cleared). Then, if
the RWWSRE bit is written to one at the same time as SPMEN, the next SPM instruction within
four clock cycles re-enables the RWW section. The RWW section cannot be re-enabled while
the Flash is busy with a Page Erase or a Page Write (SPMEN is set). If the RWWSRE bit is written
while the Flash is being loaded, the Flash load operation will abort and the data loaded will
be lost.
• Bit 3 – BLBSET: Boot Lock Bit Set
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles sets Boot Lock bits, according to the data in R0. The data in R1 and the address in the Zpointer
are ignored. The BLBSET bit will automatically be cleared upon completion of the Lock
bit set, or if no SPM instruction is executed within four clock cycles.
An (E)LPM instruction within three cycles after BLBSET and SPMEN are set in the SPMCSR
Register, will read either the Lock bits or the Fuse bits (depending on Z0 in the Z-pointer) into the
destination register. See “Reading the Fuse and Lock bits from software” on page 353 for
details.
Bit 7 6 5 4 3 2 1 0
SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN SPMCSR
Read/write R/W R R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0350
7593L–AVR–09/12
AT90USB64/128
• Bit 2 – PGWRT: Page Write
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles executes Page Write, with the data stored in the temporary buffer. The page address is
taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit
will auto-clear upon completion of a Page Write, or if no SPM instruction is executed within four
clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is
addressed.
• Bit 1 – PGERS: Page Erase
If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock
cycles executes Page Erase. The page address is taken from the high part of the Z-pointer. The
data in R1 and R0 are ignored. The PGERS bit will auto-clear upon completion of a Page Erase,
or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire
Page Write operation if the NRWW section is addressed.
• Bit 0 – SPMEN: Store Program Memory Enable
This bit enables the SPM instruction for the next four clock cycles. If written to one together with
either RWWSRE, BLBSET, PGWRT’ or PGERS, the following SPM instruction will have a special
meaning, see description above. If only SPMEN is written, the following SPM instruction will
store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of
the Z-pointer is ignored. The SPMEN bit will auto-clear upon completion of an SPM instruction,
or if no SPM instruction is executed within four clock cycles. During Page Erase and Page Write,
the SPMEN bit remains high until the operation is completed.
Writing any other combination than “10001”, “01001”, “00101”, “00011” or “00001” in the lower
five bits will have no effect.
Note: Only one SPM instruction should be active at any time.
29.6 Addressing the flash during self-programming
The Z-pointer is used to address the SPM commands. The Z pointer consists of the Z-registers
ZL and ZH in the register file, and RAMPZ in the I/O space. The number of bits actually used is
implementation dependent. Note that the RAMPZ register is only implemented when the program
space is larger than 64kBytes.
Since the Flash is organized in pages (see Table 30-11 on page 364), the Program Counter can
be treated as having two different sections. One section, consisting of the least significant bits, is
addressing the words within a page, while the most significant bits are addressing the pages.
This is shown in Figure 29-4 on page 351. Note that the Page Erase and Page Write operations
are addressed independently. Therefore it is of major importance that the Boot Loader software
addresses the same page in both the Page Erase and Page Write operation. Once a programming
operation is initiated, the address is latched and the Z-pointer can be used for other
operations.
The (E)LPM instruction use the Z-pointer to store the address. Since this instruction addresses
the Flash byte-by-byte, also bit Z0 of the Z-pointer is used.
Bit 23 22 21 20 19 18 17 16
15 14 13 12 11 10 9 8
RAMPZ RAMPZ7 RAMPZ6 RAMPZ5 RAMPZ4 RAMPZ3 RAMPZ2 RAMPZ1 RAMPZ0
ZH (R31) Z15 Z14 Z13 Z12 Z11 Z10 Z9 Z8
ZL (R30) Z7 Z6 Z5 Z4 Z3 Z2 Z1 Z0
76543210351
7593L–AVR–09/12
AT90USB64/128
Figure 29-4. Addressing the flash during SPM (1).
Note: 1. The different variables used in Figure 29-4 are listed in Table 29-10 on page 358.
29.7 Self-programming the flash
The program memory is updated in a page by page fashion. Before programming a page with
the data stored in the temporary page buffer, the page must be erased. The temporary page buffer
is filled one word at a time using SPM and the buffer can be filled either before the Page
Erase command or between a Page Erase and a Page Write operation:
Alternative 1, fill the buffer before a Page Erase
• Fill temporary page buffer
• Perform a Page Erase
• Perform a Page Write
Alternative 2, fill the buffer after Page Erase
• Perform a Page Erase
• Fill temporary page buffer
• Perform a Page Write
If only a part of the page needs to be changed, the rest of the page must be stored (for example
in the temporary page buffer) before the erase, and then be rewritten. When using alternative 1,
the Boot Loader provides an effective Read-Modify-Write feature which allows the user software
to first read the page, do the necessary changes, and then write back the modified data. If alternative
2 is used, it is not possible to read the old data while loading since the page is already
erased. The temporary page buffer can be accessed in a random sequence. It is essential that
the page address used in both the Page Erase and Page Write operation is addressing the same
PROGRAM MEMORY
23 1 0
Z - POINTER
BIT
0
ZPAGEMSB
WORD ADDRESS
WITHIN A PAGE
PAGE ADDRESS
WITHIN THE FLASH
ZPCMSB
INSTRUCTION WORD
PAGE PCWORD[PAGEMSB:0]:
00
01
02
PAGEEND
PAGE
PCPAGE PCWORD
PCMSB PAGEMSB
PROGRAM COUNTER352
7593L–AVR–09/12
AT90USB64/128
page. See “Simple Assembly Code example for a Boot Loader” on page 355 for an assembly
code example.
29.7.1 Performing page erase by SPM
To execute Page Erase, set up the address in the Z-pointer, write “X0000011” to SPMCSR and
execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored.
The page address must be written to PCPAGE in the Z-register. Other bits in the Z-pointer will
be ignored during this operation.
• Page Erase to the RWW section: The NRWW section can be read during the Page Erase
• Page Erase to the NRWW section: The CPU is halted during the operation
29.7.2 Filling the Temporary Buffer (page loading)
To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write
“00000001” to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The
content of PCWORD in the Z-register is used to address the data in the temporary buffer. The
temporary buffer will auto-erase after a Page Write operation or by writing the RWWSRE bit in
SPMCSR. It is also erased after a system reset. Note that it is not possible to write more than
one time to each address without erasing the temporary buffer.
If the EEPROM is written in the middle of an SPM Page Load operation, all data loaded will be
lost.
29.7.3 Performing a Page Write
To execute Page Write, set up the address in the Z-pointer, write “X0000101” to SPMCSR and
execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored.
The page address must be written to PCPAGE. Other bits in the Z-pointer must be written to
zero during this operation.
• Page Write to the RWW section: The NRWW section can be read during the Page Write
• Page Write to the NRWW section: The CPU is halted during the operation
29.7.4 Using the SPM interrupt
If the SPM interrupt is enabled, the SPM interrupt will generate a constant interrupt when the
SPMEN bit in SPMCSR is cleared. This means that the interrupt can be used instead of polling
the SPMCSR Register in software. When using the SPM interrupt, the Interrupt Vectors should
be moved to the BLS section to avoid that an interrupt is accessing the RWW section when it is
blocked for reading. How to move the interrupts is described in “Interrupts” on page 68.
29.7.5 Consideration while updating BLS
Special care must be taken if the user allows the Boot Loader section to be updated by leaving
Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the
entire Boot Loader, and further software updates might be impossible. If it is not necessary to
change the Boot Loader software itself, it is recommended to program the Boot Lock bit11 to
protect the Boot Loader software from any internal software changes.
29.7.6 Prevent reading the RWW section during self-programming
During Self-Programming (either Page Erase or Page Write), the RWW section is always
blocked for reading. The user software itself must prevent that this section is addressed during
the self programming operation. The RWWSB in the SPMCSR will be set as long as the RWW
section is busy. During Self-Programming the Interrupt Vector table should be moved to the BLS353
7593L–AVR–09/12
AT90USB64/128
as described in “Interrupts” on page 68, or the interrupts must be disabled. Before addressing
the RWW section after the programming is completed, the user software must clear the
RWWSB by writing the RWWSRE. See “Simple Assembly Code example for a Boot Loader” on
page 355 for an example.
29.7.7 Setting the Boot Loader Lock bits by SPM
To set the Boot Loader Lock bits, write the desired data to R0, write “X0001001” to SPMCSR
and execute SPM within four clock cycles after writing SPMCSR. The only accessible Lock bits
are the Boot Lock bits that may prevent the Application and Boot Loader section from any software
update by the MCU.
See Table 29-2 on page 347 and Table 29-3 on page 347 for how the different settings of the
Boot Loader bits affect the Flash access.
If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock bit will be programmed if an
SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCSR.
The Z-pointer is don’t care during this operation, but for future compatibility it is recommended to
load the Z-pointer with 0x0001 (same as used for reading the lOck bits). For future compatibility it
is also recommended to set bits 7, 6, 1, and 0 in R0 to “1” when writing the Lock bits. When programming
the Lock bits the entire Flash can be read during the operation.
29.7.8 EEPROM Write prevents writing to SPMCSR
Note that an EEPROM write operation will block all software programming to Flash. Reading the
Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It
is recommended that the user checks the status bit (EEPE) in the EECR Register and verifies
that the bit is cleared before writing to the SPMCSR Register.
29.7.9 Reading the Fuse and Lock bits from software
It is possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the
Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an (E)LPM
instruction is executed within three CPU cycles after the BLBSET and SPMEN bits are set in
SPMCSR, the value of the Lock bits will be loaded in the destination register. The BLBSET and
SPMEN bits will auto-clear upon completion of reading the Lock bits or if no (E)LPM instruction
is executed within three CPU cycles or no SPM instruction is executed within four CPU cycles.
When BLBSET and SPMEN are cleared, (E)LPM will work as described in the Instruction set
Manual.
The algorithm for reading the Fuse Low byte is similar to the one described above for reading
the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 and set the BLBSET
and SPMEN bits in SPMCSR. When an (E)LPM instruction is executed within three cycles after
the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will
be loaded in the destination register as shown below. Refer to Table 30-5 on page 361 for a
detailed description and mapping of the Fuse Low byte.
Bit 7 6 5 4 3 2 1 0
R0 1 1 BLB12 BLB11 BLB02 BLB01 1 1
Bit 7 6 5 4 3 2 1 0
Rd – – BLB12 BLB11 BLB02 BLB01 LB2 LB1
Bit 7 6 5 4 3 2 1 0
Rd FLB7 FLB6 FLB5 FLB4 FLB3 FLB2 FLB1 FLB0354
7593L–AVR–09/12
AT90USB64/128
Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. When an (E)LPM
instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the
SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as
shown below. Refer to Table 30-4 on page 361 for detailed description and mapping of the Fuse
High byte.
When reading the Extended Fuse byte, load 0x0002 in the Z-pointer. When an (E)LPM instruction
is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR,
the value of the Extended Fuse byte (EFB) will be loaded in the destination register as shown
below. Refer to Table 30-3 on page 360 for detailed description and mapping of the Extended
Fuse byte.
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are
unprogrammed, will be read as one.
29.7.10 Reading the Signature Row from software
To read the Signature Row from software, load the Z-pointer with the signature byte address
given in Table 29-6 on page 354 and set the SIGRD and SPMEN bits in SPMCSR. When an
LPM instruction is executed within three CPU cycles after the SIGRD and SPMEN bits are set in
SPMCSR, the signature byte value will be loaded in the destination register. The SIGRD and
SPMEN bits will auto-clear upon completion of reading the Signature Row Lock bits or if no LPM
instruction is executed within three CPU cycles. When SIGRD and SPMEN are cleared, LPM will
work as described in the Instruction set Manual.
AT90USB64/128 includes a unique 10-bytes serial number located in the signature row. This
unique serial number can be used as a USB serial number in the device enumeration process.
The pointer addresses to access this unique serial number are given in Table 29-6 on page 354.
Note: All other addresses are reserved for future use.
29.7.11 Preventing flash corruption
During periods of low VCC, the Flash program can be corrupted because the supply voltage is
too low for the CPU and the Flash to operate properly. These issues are the same as for board
level systems using the Flash, and the same design solutions should be applied.
A Flash program corruption can be caused by two situations when the voltage is too low. First, a
regular write sequence to the Flash requires a minimum voltage to operate correctly. Secondly,
Bit 7 6 5 4 3 2 1 0
Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0
Bit 7 6 5 4 3 2 1 0
Rd – – – – – EFB2 EFB1 EFB0
Table 29-6. Signature Row addressing.
Signature byte Z-pointer address
Device Signature Byte 1 0x0000
Device Signature Byte 2 0x0002
Device Signature Byte 3 0x0004
RC Oscillator Calibration Byte 0x0001
Unique Serial Number From 0x000E to 0x0018355
7593L–AVR–09/12
AT90USB64/128
the CPU itself can execute instructions incorrectly, if the supply voltage for executing instructions
is too low.
Flash corruption can easily be avoided by following these design recommendations (one is
sufficient):
1. If there is no need for a Boot Loader update in the system, program the Boot Loader
Lock bits to prevent any Boot Loader software updates.
2. Keep the AVR RESET active (low) during periods of insufficient power supply voltage.
This can be done by enabling the internal Brown-out Detector (BOD) if the operating
voltage matches the detection level. If not, an external low VCC reset protection circuit
can be used. If a reset occurs while a write operation is in progress, the write operation
will be completed provided that the power supply voltage is sufficient.
3. Keep the AVR core in Power-down sleep mode during periods of low VCC. This will prevent
the CPU from attempting to decode and execute instructions, effectively protecting
the SPMCSR Register and thus the Flash from unintentional writes.
29.7.12 Programming time for flash when using SPM
The calibrated RC Oscillator is used to time Flash accesses. Table 29-7 shows the typical programming
time for Flash accesses from the CPU.
29.7.13 Simple Assembly Code example for a Boot Loader
;- the routine writes one page of data from RAM to Flash
; the first data location in RAM is pointed to by the Y-pointer
; the first data location in Flash is pointed to by the Z-pointer
;- error handling is not included
;- the routine must be placed inside the Boot space
; (at least the Do_spm sub routine). Only code inside NRWW section can
; be read during Self-Programming (Page Erase and Page Write).
;- registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24),
; loophi (r25), spmcsrval (r20)
; storing and restoring of registers is not included in the routine
; register usage can be optimized at the expense of code size
;- it is assumed that either the interrupt table is moved to the Boot
; loader section or that the interrupts are disabled.
.equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words
.org SMALLBOOTSTART
Write_page:
; Page Erase
ldi spmcsrval, (1< 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck >= 12MHz
High: > 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck >= 12MHz
30.8.1 Serial programming algorithm
When writing serial data to the Atmel AT90USB64/128, data is clocked on the rising edge of
SCK. When reading data from the AT90USB64/128, data is clocked on the falling edge of SCK.
See Figure 30-11 on page 375 for timing details.
To program and verify the AT90USB64/128 in the serial programming mode, the following
sequence is recommended (See four byte instruction formats in Table 30-16 on page 376):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
the programmer can not guarantee that SCK is held low during power-up. In this
case, RESET must be given a positive pulse of at least two CPU clock cycles duration
after SCK has been set to “0”.
2. Wait for at least 20ms and enable serial programming by sending the Programming
Enable serial instruction to pin PDI.
Table 30-14. Pin mapping serial programming.
Symbol Pins (TQFP-64) I/O Description
PDI PB2 I Serial Data in
PDO PB3 O Serial Data out
SCK PB1 I Serial Clock
VCC
GND
XTAL1
SCK
PDO
PDI
RESET
+1.8 - 5.5V
AVCC
+1.8 - 5.5V(2)375
7593L–AVR–09/12
AT90USB64/128
3. The serial programming instructions will not work if the communication is out of synchronization.
When in sync. the second byte (0x53), will echo back when issuing the
third byte of the Programming Enable instruction. Whether the echo is correct or not, all
four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give
RESET a positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The memory page is loaded one byte at
a time by supplying the 7 LSB of the address and data together with the Load Program
Memory Page instruction. To ensure correct loading of the page, the data low byte must
be loaded before data high byte is applied for a given address. The Program Memory
Page is stored by loading the Write Program Memory Page instruction with the address
lines 15..8. Before issuing this command, make sure the instruction Load Extended
Address Byte has been used to define the MSB of the address. The extended address
byte is stored until the command is re-issued, i.e., the command needs only be issued
for the first page, and when crossing the 64KWord boundary. If polling (RDY/BSY) is not
used, the user must wait at least tWD_FLASH before issuing the next page. (See Table 30-
15.) Accessing the serial programming interface before the Flash write operation completes
can result in incorrect programming.
5. The EEPROM array is programmed one byte at a time by supplying the address and
data together with the appropriate Write instruction. An EEPROM memory location is
first automatically erased before new data is written. If polling is not used, the user must
wait at least tWD_EEPROM before issuing the next byte. (See Table 30-15.) In a chip
erased device, no 0xFFs in the data file(s) need to be programmed.
6. Any memory location can be verified by using the Read instruction which returns the
content at the selected address at serial output PDO. When reading the Flash memory,
use the instruction Load Extended Address Byte to define the upper address byte,
which is not included in the Read Program Memory instruction. The extended address
byte is stored until the command is re-issued, that is, the command needs only be
issued for the first page, and when crossing the 64KWord boundary.
7. At the end of the programming session, RESET can be set high to commence normal
operation.
8. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off.
Figure 30-11. Serial programming waveforms.
Table 30-15. Minimum wait delay before writing the next Flash or EEPROM location.
Symbol Minimum wait delay
tWD_FLASH 4.5ms
tWD_EEPROM 9.0ms
tWD_ERASE 9.0ms
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT376
7593L–AVR–09/12
AT90USB64/128
Table 30-16. Serial programming instruction set.
Instruction
Instruction format
Byte 1 Byte 2 Byte 3 Byte 4 Operation
Programming Enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx Enable Serial Programming after
RESET goes low.
Chip Erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx Chip Erase EEPROM and Flash.
Load Extended Address Byte
0100 1101 0000 0000 cccc cccc xxxx xxxx Defines Extended Address Byte for
Read Program Memory and Write
Program Memory Page.
Read Program Memory
0010 H000 aaaa aaaa bbbb bbbb oooo oooo Read H (high or low) data o from
Program memory at word address
c:a:b.
Load Program Memory Page
0100 H000 xxxx xxxx xxbb bbbb iiii iiii Write H (high or low) data i to Program
Memory page at word address b. Data
low byte must be loaded before Data
high byte is applied within the same
address.
Write Program Memory Page 0100 1100 aaaa aaaa bbxx xxxx xxxx xxxx Write Program Memory Page at
address c:a:b.
Read EEPROM Memory 1010 0000 0000 aaaa bbbb bbbb oooo oooo Read data o from EEPROM memory at
address a:b.
Write EEPROM Memory 1100 0000 0000 aaaa bbbb bbbb iiii iiii Write data i to EEPROM memory at
address a:b.
Load EEPROM Memory
Page (page access)
1100 0001 0000 0000 0000 00bb iiii iiii Load data i to EEPROM memory page
buffer. After data is loaded, program
EEPROM page.
Write EEPROM Memory
Page (page access)
1100 0010 0000 aaaa bbbb bb00 xxxx xxxx Write EEPROM page at address a:b.
Read Lock bits
0101 1000 0000 0000 xxxx xxxx xxoo oooo Read Lock bits. “0” = programmed, “1”
= unprogrammed. See Table 30-1 on
page 359 for details.
Write Lock bits
1010 1100 111x xxxx xxxx xxxx 11ii iiii Write Lock bits. Set bits = “0” to
program Lock bits. See Table 30-1 on
page 359 for details.
Read Signature Byte 0011 0000 000x xxxx xxxx xxbb oooo oooo Read Signature Byte o at address b.
Write Fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram.
Write Fuse High bits 1010 1100 1010 1000 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram.
Write Extended Fuse Bits
1010 1100 1010 0100 xxxx xxxx iiii iiii Set bits = “0” to program, “1” to
unprogram. See Table 30-3 on page
360 for details.
Read Fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo Read Fuse bits. “0” = programmed, “1”
= unprogrammed.
Read Fuse High bits 0101 1000 0000 1000 xxxx xxxx oooo oooo Read Fuse High bits. “0” = programmed,
“1” = unprogrammed. 377
7593L–AVR–09/12
AT90USB64/128
Note: a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i = data in,
x = don’t care.
30.8.2 Serial programming characteristics
For characteristics of the Serial Programming module see “SPI timing characteristics” on page
395.
30.9 Programming via the JTAG interface
Programming through the JTAG interface requires control of the four JTAG specific pins: TCK,
TMS, TDI, and TDO. Control of the reset and clock pins is not required.
To be able to use the JTAG interface, the JTAGEN Fuse must be programmed. The device is
default shipped with the fuse programmed. In addition, the JTD bit in MCUCR must be cleared.
Alternatively, if the JTD bit is set, the external reset can be forced low. Then, the JTD bit will be
cleared after two chip clocks, and the JTAG pins are available for programming. This provides a
means of using the JTAG pins as normal port pins in Running mode while still allowing In-System
Programming via the JTAG interface. Note that this technique can not be used when using
the JTAG pins for Boundary-scan or On-chip Debug. In these cases the JTAG pins must be dedicated
for this purpose.
During programming the clock frequency of the TCK Input must be less than the maximum frequency
of the chip. The System Clock Prescaler can not be used to divide the TCK Clock Input
into a sufficiently low frequency.
As a definition in this datasheet, the LSB is shifted in and out first of all Shift Registers.
30.9.1 Programming specific JTAG instructions
The Instruction Register is 4-bit wide, supporting up to 16 instructions. The JTAG instructions
useful for programming are listed below.
The OPCODE for each instruction is shown behind the instruction name in hex format. The text
describes which Data Register is selected as path between TDI and TDO for each instruction.
The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be
used as an idle state between JTAG sequences. The state machine sequence for changing the
instruction word is shown in Figure 30-12 on page 378.
Read Extended Fuse Bits
0101 0000 0000 1000 xxxx xxxx oooo oooo Read Extended Fuse bits. “0” = programmed,
“1” = unprogrammed. See
Table 30-3 on page 360 for details.
Read Calibration Byte 0011 1000 000x xxxx 0000 0000 oooo oooo Read Calibration Byte
Poll RDY/BSY
1111 0000 0000 0000 xxxx xxxx xxxx xxxo If o = “1”, a programming operation is
still busy. Wait until this bit returns to
“0” before applying another command.
Table 30-16. Serial programming instruction set. (Continued)
Instruction
Instruction format
Byte 1 Byte 2 Byte 3 Byte 4 Operation378
7593L–AVR–09/12
AT90USB64/128
Figure 30-12. State machine sequence for changing the instruction word.
30.9.2 AVR_RESET (0xC)
The AVR specific public JTAG instruction for setting the AVR device in the Reset mode or taking
the device out from the Reset mode. The TAP controller is not reset by this instruction. The one
bit Reset Register is selected as Data Register. Note that the reset will be active as long as there
is a logic “one” in the Reset Chain. The output from this chain is not latched.
The active states are:
• Shift-DR: The Reset Register is shifted by the TCK input
30.9.3 PROG_ENABLE (0x4)
The AVR specific public JTAG instruction for enabling programming via the JTAG port. The 16-
bit Programming Enable Register is selected as Data Register. The active states are the
following:
• Shift-DR: The programming enable signature is shifted into the Data Register
• Update-DR: The programming enable signature is compared to the correct value, and
Programming mode is entered if the signature is valid
Test-logic-reset
Run-test/idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR scan
Capture-DR
0
1
0 11 1
0 0
0 0
1 1
1 0
1
1
0
1
0
0
1 0
1
1
0
1
0
0
0 0
1 1379
7593L–AVR–09/12
AT90USB64/128
30.9.4 PROG_COMMANDS (0x5)
The AVR specific public JTAG instruction for entering programming commands via the JTAG
port. The 15-bit Programming Command Register is selected as Data Register. The active
states are the following:
• Capture-DR: The result of the previous command is loaded into the Data Register
• Shift-DR: The Data Register is shifted by the TCK input, shifting out the result of the previous
command and shifting in the new command
• Update-DR: The programming command is applied to the Flash inputs
• Run-Test/Idle: One clock cycle is generated, executing the applied command
30.9.5 PROG_PAGELOAD (0x6)
The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the eight
LSBs of the Programming Command Register. The active states are the following:
• Shift-DR: The Flash Data Byte Register is shifted by the TCK input
• Update-DR: The content of the Flash Data Byte Register is copied into a temporary register.
A write sequence is initiated that within 11 TCK cycles loads the content of the temporary
register into the Flash page buffer. The AVR automatically alternates between writing the low
and the high byte for each new Update-DR state, starting with the low byte for the first
Update-DR encountered after entering the PROG_PAGELOAD command. The Program
Counter is pre-incriminated before writing the low byte, except for the first written byte. This
ensures that the first data is written to the address set up by PROG_COMMANDS, and
loading the last location in the page buffer does not make the program counter increment into
the next page
30.9.6 PROG_PAGEREAD (0x7)
The AVR specific public JTAG instruction to directly capture the Flash content via the JTAG port.
An 8-bit Flash Data Byte Register is selected as the Data Register. This is physically the 8 LSBs
of the Programming Command Register. The active states are the following:
• Capture-DR: The content of the selected Flash byte is captured into the Flash Data Byte
Register. The AVR automatically alternates between reading the low and the high byte for
each new Capture-DR state, starting with the low byte for the first Capture-DR encountered
after entering the PROG_PAGEREAD command. The Program Counter is post-incremented
after reading each high byte, including the first read byte. This ensures that the first data is
captured from the first address set up by PROG_COMMANDS, and reading the last location
in the page makes the program counter increment into the next page
• Shift-DR: The Flash Data Byte Register is shifted by the TCK input
30.9.7 Data Registers
The Data Registers are selected by the JTAG instruction registers described in section “Programming
specific JTAG instructions” on page 377. The Data Registers relevant for
programming operations are:
• Reset Register
• Programming Enable Register
• Programming Command Register
• Flash Data Byte Register380
7593L–AVR–09/12
AT90USB64/128
30.9.8 Reset Register
The Reset Register is a Test Data Register used to reset the part during programming. It is
required to reset the part before entering Programming mode.
A high value in the Reset Register corresponds to pulling the external reset low. The part is reset
as long as there is a high value present in the Reset Register. Depending on the Fuse settings
for the clock options, the part will remain reset for a Reset Time-out period (refer to “Clock
sources” on page 41) after releasing the Reset Register. The output from this Data Register is
not latched, so the reset will take place immediately, as shown in Figure 9-1 on page 58.
30.9.9 Programming Enable Register
The Programming Enable Register is a 16-bit register. The contents of this register is compared
to the programming enable signature, binary code 0b1010_0011_0111_0000. When the contents
of the register is equal to the programming enable signature, programming via the JTAG
port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when
leaving Programming mode.
Figure 30-13. Programming enable register.
30.9.10 Programming Command Register
The Programming Command Register is a 15-bit register. This register is used to serially shift in
programming commands, and to serially shift out the result of the previous command, if any. The
JTAG Programming Instruction Set is shown in Table 30-17 on page 382. The state sequence
when shifting in the programming commands is illustrated in Figure 30-15 on page 385.
TDI
TDO
D
A
T
A
= D Q
ClockDR & PROG_ENABLE
Programming enable
0xA370381
7593L–AVR–09/12
AT90USB64/128
Figure 30-14. Programming Command register.
TDI
TDO
S
T
R
O
B
E
S
A
D
D
R
E
S
S
/
D
A
T
A
Flash
EEPROM
fuses
lock bits382
7593L–AVR–09/12
AT90USB64/128
Table 30-17. JTAG programming instruction set.
a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i =
data in, x = don’t care.
Instruction TDI sequence TDO sequence Notes
1a. Chip Erase
0100011_10000000
0110001_10000000
0110011_10000000
0110011_10000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
1b. Poll for Chip Erase Complete 0110011_10000000 xxxxxox_xxxxxxxx (2)
2a. Enter Flash Write 0100011_00010000 xxxxxxx_xxxxxxxx
2b. Load Address Extended High Byte 0001011_cccccccc xxxxxxx_xxxxxxxx (10)
2c. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx
2d. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
2e. Load Data Low Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
2f. Load Data High Byte 0010111_iiiiiiii xxxxxxx_xxxxxxxx
2g. Latch Data
0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
2h. Write Flash Page
0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
2i. Poll for Page Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
3a. Enter Flash Read 0100011_00000010 xxxxxxx_xxxxxxxx
3b. Load Address Extended High Byte 0001011_cccccccc xxxxxxx_xxxxxxxx (10)
3c. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx
3d. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
3e. Read Data Low and High Byte
0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo
Low byte
High byte
4a. Enter EEPROM Write 0100011_00010001 xxxxxxx_xxxxxxxx
4b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (10)
4c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
4d. Load Data Byte 0010011_iiiiiiii xxxxxxx_xxxxxxxx
4e. Latch Data
0110111_00000000
1110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
4f. Write EEPROM Page
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)383
7593L–AVR–09/12
AT90USB64/128
4g. Poll for Page Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
5a. Enter EEPROM Read 0100011_00000011 xxxxxxx_xxxxxxxx
5b. Load Address High Byte 0000111_aaaaaaaa xxxxxxx_xxxxxxxx (10)
5c. Load Address Low Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
5d. Read Data Byte
0110011_bbbbbbbb
0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
6a. Enter Fuse Write 0100011_01000000 xxxxxxx_xxxxxxxx
6b. Load Data Low Byte (6) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6c. Write Fuse Extended Byte
0111011_00000000
0111001_00000000
0111011_00000000
0111011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6d. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
6e. Load Data Low Byte (7) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6f. Write Fuse High Byte
0110111_00000000
0110101_00000000
0110111_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6g. Poll for Fuse Write Complete 0110111_00000000 xxxxxox_xxxxxxxx (2)
6h. Load Data Low Byte (7) 0010011_iiiiiiii xxxxxxx_xxxxxxxx (3)
6i. Write Fuse Low Byte
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
6j. Poll for Fuse Write Complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
7a. Enter Lock Bit Write 0100011_00100000 xxxxxxx_xxxxxxxx
7b. Load Data Byte (9) 0010011_11iiiiii xxxxxxx_xxxxxxxx (4)
7c. Write Lock Bits
0110011_00000000
0110001_00000000
0110011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
(1)
7d. Poll for Lock Bit Write complete 0110011_00000000 xxxxxox_xxxxxxxx (2)
8a. Enter Fuse/Lock Bit Read 0100011_00000100 xxxxxxx_xxxxxxxx
8b. Read Extended Fuse Byte (6) 0111010_00000000
0111011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8c. Read Fuse High Byte (7) 0111110_00000000
0111111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
Table 30-17. JTAG programming instruction set. (Continued)
a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i =
data in, x = don’t care.
Instruction TDI sequence TDO sequence Notes384
7593L–AVR–09/12
AT90USB64/128
Notes: 1. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is
normally the case).
2. Repeat until o = “1”.
3. Set bits to “0” to program the corresponding Fuse, “1” to un-program the Fuse.
4. Set bits to “0” to program the corresponding Lock bit, “1” to leave the Lock bit unchanged.
5. “0” = programmed, “1” = un-programmed.
6. The bit mapping for Fuses Extended byte is listed in Table 30-3 on page 360.
7. The bit mapping for Fuses High byte is listed in Table 30-4 on page 361.
8. The bit mapping for Fuses Low byte is listed in Table 30-5 on page 361.
9. The bit mapping for Lock bits byte is listed in Table 30-1 on page 359.
10. Address bits exceeding PCMSB and EEAMSB (Table 30-11 on page 364 and Table 30-12 on page 365) are don’t care.
11. All TDI and TDO sequences are represented by binary digits (0b...).
8d. Read Fuse Low Byte (8) 0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
8e. Read Lock Bits (9) 0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxoooooo (5)
8f. Read Fuses and Lock Bits
0111010_00000000
0111110_00000000
0110010_00000000
0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
xxxxxxx_oooooooo
xxxxxxx_oooooooo
xxxxxxx_oooooooo
(5)
Fuse Ext. byte
Fuse High byte
Fuse Low byte
Lock bits
9a. Enter Signature Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
9b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
9c. Read Signature Byte 0110010_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
10a. Enter Calibration Byte Read 0100011_00001000 xxxxxxx_xxxxxxxx
10b. Load Address Byte 0000011_bbbbbbbb xxxxxxx_xxxxxxxx
10c. Read Calibration Byte 0110110_00000000
0110111_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_oooooooo
11a. Load No Operation Command 0100011_00000000
0110011_00000000
xxxxxxx_xxxxxxxx
xxxxxxx_xxxxxxxx
Table 30-17. JTAG programming instruction set. (Continued)
a = address high bits, b = address low bits, c = address extended bits, H = 0 - Low byte, 1 - High Byte, o = data out, i =
data in, x = don’t care.
Instruction TDI sequence TDO sequence Notes385
7593L–AVR–09/12
AT90USB64/128
Figure 30-15. State machine sequence for changing/reading the data word.
30.9.11 Flash Data Byte Register
The Flash Data Byte Register provides an efficient way to load the entire Flash page buffer
before executing Page Write, or to read out/verify the content of the Flash. A state machine sets
up the control signals to the Flash and senses the strobe signals from the Flash, thus only the
data words need to be shifted in/out.
The Flash Data Byte Register actually consists of the 8-bit scan chain and a 8-bit temporary register.
During page load, the Update-DR state copies the content of the scan chain over to the
temporary register and initiates a write sequence that within 11 TCK cycles loads the content of
the temporary register into the Flash page buffer. The AVR automatically alternates between
writing the low and the high byte for each new Update-DR state, starting with the low byte for the
first Update-DR encountered after entering the PROG_PAGELOAD command. The Program
Counter is pre-incremented before writing the low byte, except for the first written byte. This
ensures that the first data is written to the address set up by PROG_COMMANDS, and loading
the last location in the page buffer does not make the Program Counter increment into the next
page.
During Page Read, the content of the selected Flash byte is captured into the Flash Data Byte
Register during the Capture-DR state. The AVR automatically alternates between reading the
low and the high byte for each new Capture-DR state, starting with the low byte for the first CapTest-logic-reset
Run-test/idle
Shift-DR
Exit1-DR
Pause-DR
Exit2-DR
Update-DR
Select-IR scan
Capture-IR
Shift-IR
Exit1-IR
Pause-IR
Exit2-IR
Update-IR
Select-DR scan
Capture-DR
0
1
0 11 1
0 0
0 0
1 1
1 0
1
1
0
1
0
0
1 0
1
1
0
1
0
0
0 0
1 1386
7593L–AVR–09/12
AT90USB64/128
ture-DR encountered after entering the PROG_PAGEREAD command. The Program Counter is
post-incremented after reading each high byte, including the first read byte. This ensures that
the first data is captured from the first address set up by PROG_COMMANDS, and reading the
last location in the page makes the program counter increment into the next page.
Figure 30-16. Flash Data Byte Register.
The state machine controlling the Flash Data Byte Register is clocked by TCK. During normal
operation in which eight bits are shifted for each Flash byte, the clock cycles needed to navigate
through the TAP controller automatically feeds the state machine for the Flash Data Byte Register
with sufficient number of clock pulses to complete its operation transparently for the user.
However, if too few bits are shifted between each Update-DR state during page load, the TAP
controller should stay in the Run-Test/Idle state for some TCK cycles to ensure that there are at
least 11 TCK cycles between each Update-DR state.
30.9.12 Programming algorithm
All references below of type “1a”, “1b”, and so on, refer to Table 30-17 on page 382.
30.9.13 Entering Programming mode
1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register.
2. Enter instruction PROG_ENABLE and shift 0b1010_0011_0111_0000 in the Programming
Enable Register.
30.9.14 Leaving Programming mode
1. Enter JTAG instruction PROG_COMMANDS.
2. Disable all programming instructions by using no operation instruction 11a.
3. Enter instruction PROG_ENABLE and shift 0b0000_0000_0000_0000 in the programming
Enable Register.
4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register.
TDI
TDO
D
A
T
A
Flash
EEPROM
fuses
lock bits
STROBES
ADDRESS
State
machine387
7593L–AVR–09/12
AT90USB64/128
30.9.15 Performing Chip Erase
1. Enter JTAG instruction PROG_COMMANDS.
2. Start Chip Erase using programming instruction 1a.
3. Poll for Chip Erase complete using programming instruction 1b, or wait for tWLRH_CE
(refer to Table 30-13 on page 373).
30.9.16 Programming the Flash
Before programming the Flash a Chip Erase must be performed, see “Performing Chip Erase”
on page 387.
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load address Extended High byte using programming instruction 2b.
4. Load address High byte using programming instruction 2c.
5. Load address Low byte using programming instruction 2d.
6. Load data using programming instructions 2e, 2f and 2g.
7. Repeat steps 5 and 6 for all instruction words in the page.
8. Write the page using programming instruction 2h.
9. Poll for Flash write complete using programming instruction 2i, or wait for tWLRH (refer to
Table 30-13 on page 373).
10. Repeat steps 3 to 9 until all data have been programmed.
A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction:
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash write using programming instruction 2a.
3. Load the page address using programming instructions 2b, 2c and 2d. PCWORD (refer
to Table 30-11 on page 364) is used to address within one page and must be written as
0.
4. Enter JTAG instruction PROG_PAGELOAD.
5. Load the entire page by shifting in all instruction words in the page byte-by-byte, starting
with the LSB of the first instruction in the page and ending with the MSB of the last
instruction in the page. Use Update-DR to copy the contents of the Flash Data Byte
Register into the Flash page location and to auto-increment the Program Counter
before each new word.
6. Enter JTAG instruction PROG_COMMANDS.
7. Write the page using programming instruction 2h.
8. Poll for Flash write complete using programming instruction 2i, or wait for tWLRH (refer to
Table 30-13 on page 373).
9. Repeat steps 3 to 8 until all data have been programmed.
30.9.17 Reading the Flash
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.
3. Load address using programming instructions 3b, 3c and 3d.
4. Read data using programming instruction 3e.
5. Repeat steps 3 and 4 until all data have been read.
A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction:388
7593L–AVR–09/12
AT90USB64/128
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Flash read using programming instruction 3a.
3. Load the page address using programming instructions 3b, 3c and 3d. PCWORD (refer
to Table 30-11 on page 364) is used to address within one page and must be written as
0.
4. Enter JTAG instruction PROG_PAGEREAD.
5. Read the entire page (or Flash) by shifting out all instruction words in the page (or
Flash), starting with the LSB of the first instruction in the page (Flash) and ending with
the MSB of the last instruction in the page (Flash). The Capture-DR state both captures
the data from the Flash, and also auto-increments the program counter after each word
is read. Note that Capture-DR comes before the shift-DR state. Hence, the first byte
which is shifted out contains valid data.
6. Enter JTAG instruction PROG_COMMANDS.
7. Repeat steps 3 to 6 until all data have been read.
30.9.18 Programming the EEPROM
Before programming the EEPROM a Chip Erase must be performed, see “Performing Chip
Erase” on page 387.
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM write using programming instruction 4a.
3. Load address High byte using programming instruction 4b.
4. Load address Low byte using programming instruction 4c.
5. Load data using programming instructions 4d and 4e.
6. Repeat steps 4 and 5 for all data bytes in the page.
7. Write the data using programming instruction 4f.
8. Poll for EEPROM write complete using programming instruction 4g, or wait for tWLRH
(refer to Table 30-13 on page 373).
9. Repeat steps 3 to 8 until all data have been programmed.
Note that the PROG_PAGELOAD instruction can not be used when programming the EEPROM.
30.9.19 Reading the EEPROM
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable EEPROM read using programming instruction 5a.
3. Load address using programming instructions 5b and 5c.
4. Read data using programming instruction 5d.
5. Repeat steps 3 and 4 until all data have been read.
Note that the PROG_PAGEREAD instruction can not be used when reading the EEPROM.
30.9.20 Programming the Fuses
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse write using programming instruction 6a.
3. Load data high byte using programming instructions 6b. A bit value of “0” will program
the corresponding fuse, a “1” will un-program the fuse.
4. Write Fuse High byte using programming instruction 6c.
5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (refer to
Table 30-13 on page 373).389
7593L–AVR–09/12
AT90USB64/128
6. Load data low byte using programming instructions 6e. A “0” will program the fuse, a “1”
will unprogram the fuse.
7. Write Fuse low byte using programming instruction 6f.
8. Poll for Fuse write complete using programming instruction 6g, or wait for tWLRH (refer to
Table 30-13 on page 373).
30.9.21 Programming the Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Lock bit write using programming instruction 7a.
3. Load data using programming instructions 7b. A bit value of “0” will program the corresponding
lock bit, a “1” will leave the lock bit unchanged.
4. Write Lock bits using programming instruction 7c.
5. Poll for Lock bit write complete using programming instruction 7d, or wait for tWLRH (refer
to Table 30-13 on page 373).
30.9.22 Reading the Fuses and Lock Bits
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Fuse/Lock bit read using programming instruction 8a.
3. To read all Fuses and Lock bits, use programming instruction 8e.
To only read Fuse High byte, use programming instruction 8b.
To only read Fuse Low byte, use programming instruction 8c.
To only read Lock bits, use programming instruction 8d.
30.9.23 Reading the Signature Bytes
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Signature byte read using programming instruction 9a.
3. Load address 0x00 using programming instruction 9b.
4. Read first signature byte using programming instruction 9c.
5. Repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third
signature bytes, respectively.
30.9.24 Reading the Calibration Byte
1. Enter JTAG instruction PROG_COMMANDS.
2. Enable Calibration byte read using programming instruction 10a.
3. Load address 0x00 using programming instruction 10b.
4. Read the calibration byte using programming instruction 10c.390
7593L–AVR–09/12
AT90USB64/128
31. Electrical characteristics for Atmel AT90USB64/128
31.1 Absolute maximum ratings*
31.2 DC characteristics
Operating temperature..................................... -40°C to +85°C *NOTICE: Stresses beyond those listed under “Absolute
maximum ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage temperature...................................... -65°C to +150°C
Voltage on any pin except RESET and VBUS
with respect to ground (7) .............................-0.5V to VCC+0.5V
Voltage on RESET with respect to ground ......-0.5V to +13.0V
Voltage on VBUS with respect to ground...........-0.5V to +6.0V
Maximum operating voltage............................................ +6.0V
DC current per I/O pin.................................................. 40.0mA
DC current VCC and GND pins .................................. 200.0mA
TA = -40°C to 85°C, VCC = 2.7V to 5.5V (unless otherwise noted).
Symbol Parameter Condition Min. (5) Typ. Max. (5) Units
VIL
Input Low Voltage,Except
XTAL1 and Reset pin VCC = 2.7V - 5.5V -0.5 0.2VCC (1)
V
VIL1
Input Low Voltage,
XTAL1 pin VCC = 2.7V - 5.5V -0.5 0.1VCC (1)
VIL2
Input Low Voltage,
RESET pin VCC = 2.7V - 5.5V -0.5 0.1VCC (1)
VIH
Input High Voltage,
Except XTAL1 and
RESET pins
VCC = 2.7V - 5.5V 0.6VCC (2) VCC + 0.5
VIH1
Input High Voltage,
XTAL1 pin VCC = 2.7V - 5.5V 0.7VCC (2) VCC + 0.5
VIH2
Input High Voltage,
RESET pin VCC = 2.7V - 5.5V 0.9VCC (2) VCC + 0.5
VOL Output Low Voltage (3) IOL = 10mA, VCC = 5V
IOL = 5mA, VCC = 3V
0.3
0.2
0.7
0.5
VOH Output High Voltage (4) IOH = -20mA, VCC = 5V
IOH = -10mA, VCC = 3V
4.2
2.3
4.5
2.6
IIL
Input Leakage
Current I/O Pin
VCC = 5.5V, pin low
(absolute value) 1
µA
IIH
Input Leakage
Current I/O Pin
VCC = 5.5V, pin high
(absolute value) 1
RRST Reset Pull-up Resistor 30 60
kΩ
RPU I/O Pin Pull-up Resistor 20 50391
7593L–AVR–09/12
AT90USB64/128
Note: 1. "Max" means the highest value where the pin is guaranteed to be read as low
2. "Min" means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
Atmel AT90USB64/128:
1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
4.)The sum of all IOL, for ports F0-F7 should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
AT90USB64/128:
1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
4)The sum of all IOH, for ports F0-F7 should not exceed 100mA.
5. All DC Characteristics contained in this datasheet are based on simulation and characterization of other AVR microcontrollers
manufactured in the same process technology. These values are preliminary values representing design targets, and
will be updated after characterization of actual silicon
6. Values with “PRR1 – Power Reduction Register 1” disabled (0x00).
ICC Power Supply Current (6)
Active 4MHz, VCC = 3V
(AT90USB64/128) 2.5 5
mA
Active 8MHz, VCC = 3V
(AT90USB64/128) 5 10
Active 8MHz, VCC = 5V
(AT90USB64/128) 10 18
Active 16MHz, VCC = 5V
(AT90USB64/128) 19 30
Icc Power-down mode
WDT enabled, BOD
enabled, VCC = 3V, 25°C 30
µA WDT enabled, BOD
disabled, VCC = 3V, 25°C 10
WDT disabled, BOD
disabled, VCC = 3V, 25°C 2
VACIO
Analog Comparator
Input Offset Voltage
VCC = 5V
Vin = VCC/2 10 40 mV
IACLK
Analog Comparator
Input Leakage Current
VCC = 5V
Vin = VCC/2 -50 50 nA
tACID
Analog Comparator
Propagation Delay
VCC = 2.7V
VCC = 4.0V
750
500 ns
Iq USB Regulator Quiescent
Current UVCC >3.6V, I = 0mA 10 30 µA
Vusb USB Regulator Output
Voltage (Ucap) UVCC >3.6V, I = 40mA (8) 3.0 3.3 3.5 V
TA = -40°C to 85°C, VCC = 2.7V to 5.5V (unless otherwise noted). (Continued)
Symbol Parameter Condition Min. (5) Typ. Max. (5) Units392
7593L–AVR–09/12
AT90USB64/128
7. As specified on the USB Electrical chapter of USB Specifications 2.0, the D+/D- pads can withstand voltages down to -1V
applied through a 39Ω resistor
8. USB Peripheral consumes up to 50mA from the regulator or UVCC pin when USB is used at full-load
31.3 External clock drive waveforms
Figure 31-1. External clock drive waveforms.
31.4 External clock drive
Note: All DC characteristics contained in this datasheet are based on simulation and characterization of
other AVR microcontrollers manufactured in the same process technology. These values are preliminary
values representing design targets, and will be updated after characterization of actual
silicon.
31.5 Maximum speed vs. VCC
Maximum frequency is depending on VCC. As shown in Figure 31-2 on page 393, the maximum
frequency vs. VCC curve is linear between 2.7V < VCC < 5.5V.
VIL1
VIH1
Table 31-1. External clock drive.
Symbol Parameter
VCC=1.8-5.5V VCC=2.7-5.5V VCC=4.5-5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL
Oscillator
Frequency 0 2 0 8 0 16 MHz
tCLCL Clock Period 500 125 62.5
tCHCX High Time 200 50 25 ns
t
CLCX Low Time 200 50 25
tCLCH Rise Time 2.0 1.6 0.5
μs
tCHCL Fall Time 2.0 1.6 0.5
ΔtCLCL
Change in period
from one clock
cycle to the next
2 2 2%393
7593L–AVR–09/12
AT90USB64/128
Figure 31-2. Maximum frequency vs. VCC, Atmel AT90USB64/128.
31.6 2-wire serial interface characteristics
Table 31-2 describes the requirements for devices connected to the 2-wire Serial Bus. The AT90USB64/128 2-wire Serial
Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 31-3 on page 394.
16MHz
8MHz
Table 31-2. 2-wire serial bus requirements.
Symbol Parameter Condition Min Max Units
VIL Input Low-voltage -0.5 0.3 VCC
V VIH Input High-voltage 0.7 VCC VCC + 0.5
Vhys
(1) Hysteresis of Schmitt Trigger Inputs 0.05 VCC (2) –
VOL (1) Output Low-voltage 3mA sink current 0 0.4
tr
(1) Rise Time for both SDA and SCL 20 + 0.1Cb
(3)(2) 300
tof ns (1) Output Fall Time from VIHmin to VILmax 10pF < Cb < 400pF (3) 20 + 0.1Cb
(3)(2) 250
tSP (1) Spikes Suppressed by Input Filter 0 50 (2)
Ii Input Current each I/O Pin 0.1VCC < Vi
< 0.9VCC -10 10 µA
Ci
(1) Capacitance for each I/O Pin – 10 pF
fSCL SCL Clock Frequency fCK (4) > max(16fSCL, 250kHz) (5) 0 400 kHz
Rp Value of Pull-up resistor
fSCL ≤ 100kHz
fSCL > 100kHz
VCC – 0.4V
3mA ---------------------------- 1000ns
Cb
-------------------
Ω
VCC – 0.4V
3mA ---------------------------- 300ns
Cb
----------------394
7593L–AVR–09/12
AT90USB64/128
Notes: 1. In Atmel AT90USB64/128, this parameter is characterized and not 100% tested.
2. Required only for fSCL >100kHz.
3. Cb = capacitance of one bus line in pF.
4. fCK = CPU clock frequency
5. This requirement applies to all AT90USB64/128 2-wire Serial Interface operation. Other devices connected to the 2-wire
Serial Bus need only obey the general fSCL requirement.
6. The actual low period generated by the AT90USB64/128 2-wire Serial Interface is (1/fSCL - 2/fCK), thus fCK must be greater
than 6MHz for the low time requirement to be strictly met at fSCL = 100kHz.
7. The actual low period generated by the AT90USB64/128 2-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement
will not be strictly met for fSCL > 308kHz when fCK = 8MHz. Still, AT90USB64/128 devices connected to the bus may
communicate at full speed (400kHz) with other AT90USB64/128 devices, as well as any other device with a proper tLOW
acceptance margin.
Figure 31-3. 2-wire serial bus timing.
tHD;STA Hold Time (repeated) START Condition
fSCL ≤ 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tLOW Low Period of the SCL Clock
fSCL ≤ 100kHz (6) 4.7 –
fSCL > 100kHz (7) 1.3 –
tHIGH High period of the SCL clock
fSCL ≤ 100kHz 4.0 –
fSCL > 100kHz 0.6 –
tSU;STA
Set-up time for a repeated START
condition
fSCL ≤ 100kHz 4.7 –
fSCL > 100kHz 0.6 –
tHD;DAT Data hold time
fSCL ≤ 100kHz 0 3.45
fSCL > 100kHz 0 0.9
tSU;DAT Data setup time
fSCL ≤ 100kHz 250 –
ns
fSCL > 100kHz 100 –
tSU;STO Setup time for STOP condition
fSCL ≤ 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tBUF
Bus free time between a STOP and
START condition
fSCL ≤ 100kHz 4.7 –
fSCL > 100kHz 1.3 –
Table 31-2. 2-wire serial bus requirements. (Continued)
Symbol Parameter Condition Min Max Units
t
SU;STA
t
LOW
t
HIGH
t
LOW
t
of
t
HD;STA t
HD;DAT t
SU;DAT t
SU;STO
t
BUF
SCL
SDA
t
r395
7593L–AVR–09/12
AT90USB64/128
31.7 SPI timing characteristics
See Figure 31-4 and Figure 31-5 on page 396 for details.
Note: 1. In SPI Programming mode the minimum SCK high/low period is:
- 2 tCLCL for fCK <12MHz
- 3 tCLCL for fCK >12MHz
Figure 31-4. SPI interface timing requirements (master mode).
Table 31-3. SPI timing parameters.
Description Mode Min. Typ. Max.
1 SCK period Master See Table 18-4 on
page 174
ns
2 SCK high/low Master 50% duty cycle
3 Rise/Fall time Master 3.6
4 Setup Master 10
5 Hold Master 10
6 Out to SCK Master 0.5 × tsck
7 SCK to out Master 10
8 SCK to out high Master 10
9 SS low to out Slave 15
10 SCK period Slave 4 × tck
11 SCK high/low (1) Slave 2 × tck
12 Rise/Fall time Slave 1.6 µs
13 Setup Slave 10
ns
14 Hold Slave tck
15 SCK to out Slave 15
16 SCK to SS high Slave 20
17 SS high to tri-state Slave 10
18 SS low to SCK Slave 20
MOSI
(Data output)
SCK
(CPOL = 1)
MISO
(Data input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
6 1
2 2
4 5 3
7 8396
7593L–AVR–09/12
AT90USB64/128
Figure 31-5. SPI interface timing requirements (slave mode).
31.8 Hardware boot entrance timing characteristics
Figure 31-6. Hardware boot timing requirements.
MISO
(Data output)
SCK
(CPOL = 1)
MOSI
(Data input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
10
11 11
13 14 12
15 17
9
X
16
Table 31-4. Hardware boot timings.
Symbol Parameter Min. Max.
tSHRH HWB low Setup before Reset High 0
tHHRH HWB low Hold after Reset High
StartUpTime (SUT)
+
Time Out Delay (TOUT)
RESET
ALE/HWB
t
SHRH t
HHRH397
7593L–AVR–09/12
AT90USB64/128
31.9 ADC characteristics
Table 31-5. ADC characteristics.
Symbol Parameter Condition Min. Typ. Max. Units
Resolution
Single Ended Conversion 10
Bits
Differential Conversion
Gain = 1× or 10× 8
Differential Conversion
Gain = 200× 7
Absolute accuracy (Including
INL, DNL, quantization error,
gain and offset error)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
1.5
LSB
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
Noise Reduction Mode
1.5
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
Noise Reduction Mode
Absolute accuracy
Gain = 1×, 10×, 200×
VREF = 4V, VCC = 5V
ADC Clock = 50 - 200kHz
1
Integral Non-Linearity (INL)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
0.5 1
Integral Non-Linearity (INL)
(Accuracy after calibration for
offset and gain error)
Gain = 1×, 10×, 200×
VREF = 4V, VCC = 5V
ADC Clock = 50 - 200kHz
0.5 1
Differential Non-Linearity (DNL)
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
0.3 1
Gain Error
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
-2 0 +2
Gain = 1×, 10×, 200× -2 0 +2
Offset Error
Single Ended Conversion
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
-2 1 +2
Gain = 1×, 10×, 200×
VREF = 4V, VCC = 5V
ADC Clock = 50 - 200kHz
-1 0 +1
Conversion Time Free Running Conversion 65 260 µs
Clock Frequency Single Ended Conversion 50 1000 kHz398
7593L–AVR–09/12
AT90USB64/128
AVCC Analog Supply Voltage VCC - 0.3 VCC + 0.3
V
VREF Reference Voltage Single Ended Conversion 2.0 AVCC
Differential Conversion 2.0 AVCC - 0.5
VIN Input Voltage
Single ended channels 0 VREF
Differential Conversion 0 AVCC
Input Bandwidth
Single Ended Channels 38,5
kHz
Differential Channels 4
VINT1 Internal Voltage Reference 1.1V 1.0 1.1 1.2
V
VINT2 Internal Voltage Reference 2.56V 2.4 2.56 2.8
RREF Reference Input Resistance 32 kΩ
RAIN Analog Input Resistance 100 MΩ
Table 31-5. ADC characteristics. (Continued)
Symbol Parameter Condition Min. Typ. Max. Units399
7593L–AVR–09/12
AT90USB64/128
31.10 External data memory timing
Notes: 1. This assumes 50% clock duty cycle. The half period is actually the high time of the external clock, XTAL1.
2. This assumes 50% clock duty cycle. The half period is actually the low time of the external clock, XTAL1.
Table 31-6. External data memory characteristics, 4.5 - 5.5 Volts, no wait-state.
Symbol Parameter
8MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 16 MHz
1 tLHLL ALE Pulse Width 115 1.0tCLCL-10
ns
2 tAVLL Address Valid A to ALE Low 57.5 0.5tCLCL-5 (1)
3a tLLAX_ST
Address Hold After ALE Low,
write access 5 5
3b tLLAX_LD
Address Hold after ALE Low,
read access 5 5
4 tAVLLC Address Valid C to ALE Low 57.5 0.5tCLCL-5 (1)
5 tAVRL Address Valid to RD Low 115 1.0tCLCL-10
6 tAVWL Address Valid to WR Low 115 1.0tCLCL-10
7 tLLWL ALE Low to WR Low 47.5 67.5 0.5tCLCL-15 (2) 0.5tCLCL+5 (2)
8 tLLRL ALE Low to RD Low 47.5 67.5 0.5tCLCL-15 (2) 0.5tCLCL+5 (2)
9 tDVRH Data Setup to RD High 40 40
10 tRLDV Read Low to Data Valid 75 1.0tCLCL-50
11 tRHDX Data Hold After RD High 0 0
12 tRLRH RD Pulse Width 115 1.0tCLCL-10
13 tDVWL Data Setup to WR Low 42.5 0.5tCLCL-20 (1)
14 tWHDX Data Hold After WR High 115 1.0tCLCL-10
15 tDVWH Data Valid to WR High 125 1.0tCLCL
16 tWLWH WR Pulse Width 115 1.0tCLCL-10
Table 31-7. External data memory characteristics, 4.5 - 5.5 Volts, 1 cycle wait-state.
Symbol Parameter
8MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 16 MHz
10 tRLDV Read Low to Data Valid 200 2.0tCLCL-50
ns
12 tRLRH RD Pulse Width 240 2.0tCLCL-10
15 tDVWH Data Valid to WR High 240 2.0tCLCL
16 tWLWH WR Pulse Width 240 2.0tCLCL-10400
7593L–AVR–09/12
AT90USB64/128
Table 31-8. External data memory characteristics, 4.5 - 5.5 Volts, SRWn1 = 1, SRWn0 = 0.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 16 MHz
10 tRLDV Read Low to Data Valid 325 3.0tCLCL-50
ns
12 tRLRH RD Pulse Width 365 3.0tCLCL-10
15 tDVWH Data Valid to WR High 375 3.0tCLCL
16 tWLWH WR Pulse Width 365 3.0tCLCL-10
Table 31-9. External data memory characteristics, 4.5 - 5.5 Volts, SRWn1 = 1, SRWn0 = 1.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 16 MHz
10 tRLDV Read Low to Data Valid 325 3.0tCLCL-50
ns
12 tRLRH RD Pulse Width 365 3.0tCLCL-10
14 tWHDX Data Hold After WR High 240 2.0tCLCL-10
15 tDVWH Data Valid to WR High 375 3.0tCLCL
16 tWLWH WR Pulse Width 365 3.0tCLCL-10
Table 31-10. External data memory characteristics, 2.7 - 5.5 Volts, no wait-state.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 8 MHz
1 tLHLL ALE Pulse Width 235 tCLCL-15
ns
2 tAVLL Address Valid A to ALE Low 115 0.5tCLCL-10 (1)
3a tLLAX_ST
Address Hold After ALE Low,
write access 5 5
3b tLLAX_LD
Address Hold after ALE Low,
read access 5 5
4 tAVLLC Address Valid C to ALE Low 115 0.5tCLCL-10 (1)
5 tAVRL Address Valid to RD Low 235 1.0tCLCL-15
6 tAVWL Address Valid to WR Low 235 1.0tCLCL-15
7 tLLWL ALE Low to WR Low 115 130 0.5tCLCL-10 (2) 0.5tCLCL+5 (2)
8 tLLRL ALE Low to RD Low 115 130 0.5tCLCL-10 (2) 0.5tCLCL+5 (2)
9 tDVRH Data Setup to RD High 45 45
10 tRLDV Read Low to Data Valid 190 1.0tCLCL-60
11 tRHDX Data Hold After RD High 0 0401
7593L–AVR–09/12
AT90USB64/128
Notes: 1. This assumes 50% clock duty cycle. The half period is actually the high time of the external clock, XTAL1.
2. This assumes 50% clock duty cycle. The half period is actually the low time of the external clock, XTAL1.
12 tRLRH RD Pulse Width 235 1.0tCLCL-15
ns
13 tDVWL Data Setup to WR Low 105 0.5tCLCL-20 (1)
14 tWHDX Data Hold After WR High 235 1.0tCLCL-15
15 tDVWH Data Valid to WR High 250 1.0tCLCL
16 tWLWH WR Pulse Width 235 1.0tCLCL-15
Table 31-10. External data memory characteristics, 2.7 - 5.5 Volts, no wait-state. (Continued)
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
Table 31-11. External data memory characteristics, 2.7 - 5.5 Volts, SRWn1 = 0, SRWn0 = 1.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 8 MHz
10 tRLDV Read Low to Data Valid 440 2.0tCLCL-60
ns
12 tRLRH RD Pulse Width 485 2.0tCLCL-15
15 tDVWH Data Valid to WR High 500 2.0tCLCL
16 tWLWH WR Pulse Width 485 2.0tCLCL-15
Table 31-12. External data memory characteristics, 2.7 - 5.5 Volts, SRWn1 = 1, SRWn0 = 0.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 8 MHz
10 tRLDV Read Low to Data Valid 690 3.0tCLCL-60
ns
12 tRLRH RD Pulse Width 735 3.0tCLCL-15
15 tDVWH Data Valid to WR High 750 3.0tCLCL
16 tWLWH WR Pulse Width 735 3.0tCLCL-15
Table 31-13. External data memory characteristics, 2.7 - 5.5 Volts, SRWn1 = 1, SRWn0 = 1.
Symbol Parameter
4MHz oscillator Variable oscillator
Min. Max. Min. Max. Unit
0 1/tCLCL Oscillator Frequency 0.0 8 MHz
10 tRLDV Read Low to Data Valid 690 3.0tCLCL-60
ns
12 tRLRH RD Pulse Width 735 3.0tCLCL-15
14 tWHDX Data Hold After WR High 485 2.0tCLCL-15
15 tDVWH Data Valid to WR High 750 3.0tCLCL
16 tWLWH WR Pulse Width 735 3.0tCLCL-15402
7593L–AVR–09/12
AT90USB64/128
Figure 31-7. External memory timing (SRWn1 = 0, SRWn0 = 0.
Figure 31-8. External memory timing (SRWn1 = 0, SRWn0 = 1).
ALE
T1 T2 T3
Write Read
WR
T4
A15:8 Prev. addr. Address
DA7:0 Prev. data Address XX Data
RD
DA7:0 (XMBK = 0) Address Data
System clock (CLK CPU)
1
4
2
7
6
3a
3b
5
8 12
16
13
10
11
14
15
9
ALE
T1 T2 T3
Write Read
WR
T5
A15:8 Prev. addr. Address
DA7:0 Prev. data Address XX Data
RD
DA7:0 (XMBK = 0) Address Data
System clock (CLK CPU)
1
4
2
7
6
3a
3b
5
8 12
16
13
10
11
14
15
9
T4403
7593L–AVR–09/12
AT90USB64/128
Figure 31-9. External memory timing (SRWn1 = 1, SRWn0 = 0).
Figure 31-10. External memory timing (SRWn1 = 1, SRWn0 = 1).
The ALE pulse in the last period (T4-T7) is only present if the next instruction accesses the RAM (internal
or external).
ALE
T1 T2 T3
Write Read
WR
T6
A15:8 Prev. addr. Address
DA7:0 Prev. data Address XX Data
RD
DA7:0 (XMBK = 0) Address Data
System clock (CLK CPU)
1
4
2
7
6
3a
3b
5
8 12
16
13
10
11
14
15
9
T4 T5
ALE
T1 T2 T3
Write Read
WR
T7
A15:8 Prev. addr. Address
DA7:0 Prev. data Address XX Data
RD
DA7:0 (XMBK = 0) Address Data
System clock (CLK CPU)
1
4
2
7
6
3a
3b
5
8 12
16
13
10
11
14
15
9
T4 T5 T6404
7593L–AVR–09/12
AT90USB64/128
32. Atmel AT90USB64/128 typical characteristics
The following charts show typical behavior. These figures are not tested during manufacturing.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. A sine wave generator with rail-to-rail output is used as clock
source.
All Active- and Idle current consumption measurements are done with all bits in the PRR registers
set and thus, the corresponding I/O modules are turned off. Also the Analog Comparator is
disabled during these measurements.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating
frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature.
The dominating factors are operating voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL×VCC×f
where CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O
pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to
function properly at frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer
enabled and Power-down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.405
7593L–AVR–09/12
AT90USB64/128
32.1 Input voltage levels
Figure 32-1. Input low voltage vs. VCC, all I/Os excluding DP/DM, XTAL1 and reset.
Figure 32-2. Input high voltage vs. VCC, all I/Os excluding DP/DM, XTAL1 and reset.
0.50
0.75
1.00
1.25
1.50
1.75
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
Thres hold (V)
85
25
-40
0.50
0.75
1.00
1.25
1.50
1.75
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
Thres hold (V)
85
25
-40406
7593L–AVR–09/12
AT90USB64/128
32.2 Output voltage levels
Figure 32-3. Output low voltage vs. output current, all I/Os excluding DP/DM, VCC = 3V.
Figure 32-4. Output low voltage vs. output current, all I/Os excluding DP/DM, VCC = 5V.
0
0.2
0.4
0.6
0.8
1.0
1.2
0 5 10 15 20
I
OL (mA)
VOL (V)
85
25
-40
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 5 10 15 20
I
OL (mA)
VOL (V)
85
25
-40407
7593L–AVR–09/12
AT90USB64/128
Figure 32-5. Output high voltage vs. output current, all I/Os excluding DP/DM, VCC = 3V.
Figure 32-6. Output high voltage vs. output current, all I/Os excluding DP/DM, VCC = 5V.
1.8
2.0
2.2
2.4
2.6
2.8
3.0
0 5 10 15 20
I
OH (mA)
VOH (V)
85
25
-40
4.2
4.4
4.6
4.8
5.0
0 5 10 15 20
I
OH (mA)
VOH (V)
85
25
-40408
7593L–AVR–09/12
AT90USB64/128
32.3 Power-down supply current
Figure 32-7. Power-down supply current vs. VCC, with BOD disabled, WDT disabled, T = 25°C.
Figure 32-8. Power-down supply current vs. VCC, with BOD disabled, WDT enabled, T = 25°C.
0
0.5
1.0
1.5
2.0
2.5
3.0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
ICC (µA)
0
2
4
6
8
10
12
14
16
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
ICC (µA)409
7593L–AVR–09/12
AT90USB64/128
Figure 32-9. Power-down supply current vs. VCC, with BOD enabled, WDT enabled, T = 25°C.
32.4 Power-save supply current
Figure 32-10. Power-save supply current vs. VCC, with BOD & WDT disabled, T = 25°C.
0
10
20
30
40
50
60
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
ICC (µA)
0
1
2
3
4
5
6
7
8
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
ICC (µA)410
7593L–AVR–09/12
AT90USB64/128
32.5 Idle supply current
Figure 32-11. Idle supply current vs. frequency, T = 25°C.
32.6 Active supply current
Figure 32-12. Active supply current vs. frequency, T = 25°C.
0
5
10
15
20
246 8 10 12 14 16
Frequency (MHz)
ICC (mA)
5.5
5.0
4.5
3.3
2.7
0
5
10
15
20
25
246 8 10 12 14 16
Frequency (MHz)
ICC (mA)
5.5
5.0
4.5
3.3
2.7411
7593L–AVR–09/12
AT90USB64/128
32.7 Reset supply current
Figure 32-13. Reset supply current vs. frequency.
32.8 I/O pull-up current
Figure 32-14. I/O pull-up current vs. pin voltage, VCC = 5V.
0
2
4
6
8
10
12
4 6 8 10 12 14 16
Frequency (MHz)
ICC (mA)
5.5
5.0
4.5
3.3
2.7
-20
0
20
40
60
80
100
120
140
012345
VOP (V)
IOP (uA)
85
25
-40412
7593L–AVR–09/12
AT90USB64/128
Figure 32-15. Reset pull-up current vs. pin voltage, VCC = 5V.
32.9 Bandgap voltage
Figure 32-16. Bandgap voltage vs. temperature.
0
20
40
60
80
100
120
012345
VRESET (V)
IRESET (µA)
85
25
-40
1.080
1.085
1.090
1.095
1.100
1.105
1.110
1.115
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
Bandgap voltage (V)
5.5
5.0
4.5
4.0
3.6
2.7413
7593L–AVR–09/12
AT90USB64/128
32.10 Internal ARef voltage
Figure 32-17. Internal ARef reference voltage vs. temperature, VCC = 2.7-5.5V.
32.11 USB regulator
Figure 32-18. USB regulator quiescent current vs. input voltage, no load.
2.54
2.56
2.58
2.60
2.62
2.64
-40 -20 0 20 40 60 80
Temperature (°C)
Tens ion Vref Inter (V)
0
10
20
30
40
50
60
70
80
90
100
3.0 3.5 4.0 4.5 5.0 5.5 6.0
Voltage (V)
ICC (µA)414
7593L–AVR–09/12
AT90USB64/128
Figure 32-19. USB regulator output voltage vs. input voltage, load = 75Ω.
Note: The 75Ω load is equivalent to the maximum average consumption of the USB peripheral in operation
(full bus load).
32.12 BOD levels
Figure 32-20. BOD voltage (2.4V level) vs. temperature.
2.6
2.8
3.0
3.2
3.4
3.0 3.5 4.0 4.5 5.0 5.5
Input Voltage (V)
Output voltage (V)
85
25
-40
2.42
2.44
2.46
2.48
2.50
2.52
2.54
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
Thres hold (V)
Rising Vcc
Falling Vcc415
7593L–AVR–09/12
AT90USB64/128
Figure 32-21. BOD voltage (3.4V level) vs. temperature.
Figure 32-22. BOD voltage (4.3V level) vs. temperature.
3.42
3.44
3.46
3.48
3.50
3.52
3.54
3.56
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
Thres hold (V)
Rising Vcc
Falling Vcc
4.34
4.36
4.38
4.40
4.42
4.44
4.46
4.48
4.50
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
Thres hold (V)
Rising Vcc
Falling Vcc416
7593L–AVR–09/12
AT90USB64/128
32.13 Watchdog timer frequency
Figure 32-23. WDT oscillator frequency vs. VCC.
32.14 Internal RC oscillator frequency
Figure 32-24. RC oscillator frequency vs. OSCCAL, T = 25°C.
108
110
112
114
116
118
120
122
124
2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
FRC (kHz)
85
25
-40
2
4
6
8
10
12
14
16
-1 15 31 47 63 79 95 111 127 143 159 175 191 207 223 239 255
OSCCAL (X1)
FRC (MHz)417
7593L–AVR–09/12
AT90USB64/128
Figure 32-25. RC oscillator frequency vs. VCC.
Figure 32-26. RC oscillator frequency vs. temperature.
7.8
7.9
8.0
8.1
8.2
8.3
8.4
8.5
8.6
8.7
8.8
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VCC (V)
FRC (MHz)
85
25
-40
7.8
8.0
8.2
8.4
8.6
8.8
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
FRC (MHz)
5.5
4.0
3.3
3.0
2.7418
7593L–AVR–09/12
AT90USB64/128
32.15 Power-on reset
Figure 32-27. Power-on reset level vs. temperature.
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
-40 -30 -20 -10 0 10 20 30 40 50 60 70 80
Temperature (°C)
POR Voltage (V)419
7593L–AVR–09/12
AT90USB64/128
33. Register summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0xFF) Reserved - - - - - - - -
(0xFE) Reserved - - - - - - - -
(0xFD) Reserved - - - - - - - -
(0xFC) Reserved - - - - - - - -
(0xFB) Reserved - - - - - - - -
(0xFA) Reserved - - - - - - - -
(0xF9) OTGTCON PAGE VALUE
(0xF8) UPINT PINT7:0
(0xF7) UPBCHX - - - - - PBYCT10:8
(0xF6) UPBCLX PBYCT7:0
(0xF5) UPERRX - COUNTER1:0 CRC16 TIMEOUT PID DATAPID DATATGL
(0xF4) UEINT EPINT6:0
(0xF3) UEBCHX - - - - - BYCT10:8
(0xF2) UEBCLX BYCT7:0
(0xF1) UEDATX DAT7:0
(0xF0) UEIENX FLERRE NAKINE - NAKOUTE RXSTPE RXOUTE STALLEDE TXINE
(0xEF) UESTA1X - - - - - CTRLDIR CURRBK1:0
(0xEE) UESTA0X CFGOK OVERFI UNDERFI - DTSEQ1:0 NBUSYBK1:0
(0xED) UECFG1X EPSIZE2:0 EPBK1:0 ALLOC
(0xEC) UECFG0X EPTYPE1:0 - - EPDIR
(0xEB) UECONX STALLRQ STALLRQC RSTDT EPEN
(0xEA) UERST EPRST6:0
(0xE9) UENUM EPNUM2:0
(0xE8) UEINTX FIFOCON NAKINI RWAL NAKOUTI RXSTPI RXOUTI STALLEDI TXINI
(0xE7) Reserved - - - -
(0xE6) UDMFN FNCERR
(0xE5) UDFNUMH FNUM10:8
(0xE4) UDFNUML FNUM7:0
(0xE3) UDADDR ADDEN UADD6:0
(0xE2) UDIEN UPRSME EORSME WAKEUPE EORSTE SOFE SUSPE
(0xE1) UDINT UPRSMI EORSMI WAKEUPI EORSTI SOFI SUSPI
(0xE0) UDCON LSM RMWKUP DETACH
(0xDF) OTGINT STOI HNPERRI ROLEEXI BCERRI VBERRI SRPI
(0xDE) OTGIEN STOE HNPERRE ROLEEXE BCERRE VBERRE SRPE
(0xDD) OTGCON HNPREQ SRPREQ SRPSEL VBUSHWC VBUSREQ VBUSRQC
(0xDC) Reserved
(0xDB) Reserved
(0xDA) USBINT IDTI VBUSTI
(0xD9) USBSTA SPEED ID VBUS
(0xD8) USBCON USBE HOST FRZCLK OTGPADE IDTE VBUSTE
(0xD7) UHWCON UIMOD UIDE UVCONE UVREGE
(0xD6) Reserved
(0xD5) Reserved
(0xD4) Reserved
(0xD3) Reserved
(0xD2) Reserved - - - - - - - -
(0xD1) Reserved - - - - - - - -
(0xD0) Reserved - - - - - - - -
(0xCF) Reserved - - - - - - - -
(0xCE) UDR1 USART1 I/O Data Register
(0xCD) UBRR1H - - - - USART1 Baud Rate Register High Byte
(0xCC) UBRR1L USART1 Baud Rate Register Low Byte
(0xCB) Reserved - - - - - - - -
(0xCA) UCSR1C UMSEL11 UMSEL10 UPM11 UPM10 USBS1 UCSZ11 UCSZ10 UCPOL1
(0xC9) UCSR1B RXCIE1 TXCIE1 UDRIE1 RXEN1 TXEN1 UCSZ12 RXB81 TXB81
(0xC8) UCSR1A RXC1 TXC1 UDRE1 FE1 DOR1 PE1 U2X1 MPCM1
(0xC7) Reserved - - - - - - - -
(0xC6) Reserved - - - - - - - -
(0xC5) Reserved - - - - - - - -
(0xC4) Reserved - - - - - - - -
(0xC3) Reserved - - - - - - - -
(0xC2) Reserved - - - - - - - -
(0xC1) Reserved - - - - - - - -
(0xC0) Reserved - - - - - - - -
(0xBF) Reserved - - - - - - - -420
7593L–AVR–09/12
AT90USB64/128
(0xBE) Reserved - - - - - - - -
(0xBD) TWAMR TWAM6 TWAM5 TWAM4 TWAM3 TWAM2 TWAM1 TWAM0 -
(0xBC) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
(0xBB) TWDR 2-wire Serial Interface Data Register
(0xBA) TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
(0xB9) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 - TWPS1 TWPS0
(0xB8) TWBR 2-wire Serial Interface Bit Rate Register
(0xB7) Reserved - - - - - - - -
(0xB6) ASSR - EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB
(0xB5) Reserved - - - - - - - -
(0xB4) OCR2B Timer/Counter2 Output Compare Register B
(0xB3) OCR2A Timer/Counter2 Output Compare Register A
(0xB2) TCNT2 Timer/Counter2 (8 Bit)
(0xB1) TCCR2B FOC2A FOC2B - - WGM22 CS22 CS21 CS20
(0xB0) TCCR2A COM2A1 COM2A0 COM2B1 COM2B0 - - WGM21 WGM20
(0xAF) UPDATX PDAT7:0
(0xAE) UPIENX FLERRE NAKEDE - PERRE TXSTPE TXOUTE RXSTALLE RXINE
(0xAD) UPCFG2X INTFRQ7:0
(0xAC) UPSTAX CFGOK OVERFI UNDERFI DTSEQ1:0 NBUSYBK1:0
(0xAB) UPCFG1X PSIZE2:0 PBK1:0 ALLOC
(0xAA) UPCFG0X PTYPE1:0 PTOKEN1:0 PEPNUM3:0
(0xA9) UPCONX PFREEZE INMODE RSTDT PEN
(0xA8) UPRST PRST6:0
(0xA7) UPNUM PNUM2:0
(0xA6) UPINTX FIFOCON NAKEDI RWAL PERRI TXSTPI TXOUTI RXSTALLI RXINI
(0xA5) UPINRQX INRQ7:0
(0xA4) UHFLEN FLEN7:0
(0xA3) UHFNUMH FNUM10:8
(0xA2) UHFNUML FNUM7:0
(0xA1) UHADDR HADD6:0
(0xA0) UHIEN HWUPE HSOFE RXRSME RSMEDE RSTE DDISCE DCONNE
(0x9F) UHINT HWUPI HSOFI RXRSMI RSMEDI RSTI DDISCI DCONNI
(0x9E) UHCON RESUME RESET SOFEN
(0x9D) OCR3CH Timer/Counter3 - Output Compare Register C High Byte
(0x9C) OCR3CL Timer/Counter3 - Output Compare Register C Low Byte
(0x9B) OCR3BH Timer/Counter3 - Output Compare Register B High Byte
(0x9A) OCR3BL Timer/Counter3 - Output Compare Register B Low Byte
(0x99) OCR3AH Timer/Counter3 - Output Compare Register A High Byte
(0x98) OCR3AL Timer/Counter3 - Output Compare Register A Low Byte
(0x97) ICR3H Timer/Counter3 - Input Capture Register High Byte
(0x96) ICR3L Timer/Counter3 - Input Capture Register Low Byte
(0x95) TCNT3H Timer/Counter3 - Counter Register High Byte
(0x94) TCNT3L Timer/Counter3 - Counter Register Low Byte
(0x93) Reserved - - - - - - - -
(0x92) TCCR3C FOC3A FOC3B FOC3C - - - - -
(0x91) TCCR3B ICNC3 ICES3 - WGM33 WGM32 CS32 CS31 CS30
(0x90) TCCR3A COM3A1 COM3A0 COM3B1 COM3B0 COM3C1 COM3C0 WGM31 WGM30
(0x8F) Reserved - - - - - - - -
(0x8E) Reserved - - - - - - - -
(0x8D) OCR1CH Timer/Counter1 - Output Compare Register C High Byte
(0x8C) OCR1CL Timer/Counter1 - Output Compare Register C Low Byte
(0x8B) OCR1BH Timer/Counter1 - Output Compare Register B High Byte
(0x8A) OCR1BL Timer/Counter1 - Output Compare Register B Low Byte
(0x89) OCR1AH Timer/Counter1 - Output Compare Register A High Byte
(0x88) OCR1AL Timer/Counter1 - Output Compare Register A Low Byte
(0x87) ICR1H Timer/Counter1 - Input Capture Register High Byte
(0x86) ICR1L Timer/Counter1 - Input Capture Register Low Byte
(0x85) TCNT1H Timer/Counter1 - Counter Register High Byte
(0x84) TCNT1L Timer/Counter1 - Counter Register Low Byte
(0x83) Reserved - - - - - - - -
(0x82) TCCR1C FOC1A FOC1B FOC1C - - - - -
(0x81) TCCR1B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
(0x80) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 COM1C1 COM1C0 WGM11 WGM10
(0x7F) DIDR1 - - - - - - AIN1D AIN0D
(0x7E) DIDR0 ADC7D ADC6D ADC5D ADC4D ADC3D ADC2D ADC1D ADC0D
(0x7D) - - - - - - - - -
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page421
7593L–AVR–09/12
AT90USB64/128
(0x7C) ADMUX REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0
(0x7B) ADCSRB ADHSM ACME - - - ADTS2 ADTS1 ADTS0
(0x7A) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0
(0x79) ADCH ADC Data Register High byte
(0x78) ADCL ADC Data Register Low byte
(0x77) Reserved - - - - - - - -
(0x76) Reserved - - - - - - - -
(0x75) XMCRB XMBK - - - - XMM2 XMM1 XMM0
(0x74) XMCRA SRE SRL2 SRL1 SRL0 SRW11 SRW10 SRW01 SRW00
(0x73) Reserved - - - - - - - -
(0x72) Reserved - - - - - - - -
(0x71) TIMSK3 - - ICIE3 - OCIE3C OCIE3B OCIE3A TOIE3
(0x70) TIMSK2 - - - - - OCIE2B OCIE2A TOIE2
(0x6F) TIMSK1 - - ICIE1 - OCIE1C OCIE1B OCIE1A TOIE1
(0x6E) TIMSK0 - - - - - OCIE0B OCIE0A TOIE0
(0x6D) Reserved - - - - - - - -
(0x6C) Reserved - - - - - - - -
(0x6B) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0
(0x6A) EICRB ISC71 ISC70 ISC61 ISC60 ISC51 ISC50 ISC41 ISC40
(0x69) EICRA ISC31 ISC30 ISC21 ISC20 ISC11 ISC10 ISC01 ISC00
(0x68) PCICR - - - - - - - PCIE0
(0x67) Reserved - - - - - - - -
(0x66) OSCCAL Oscillator Calibration Register
(0x65) PRR1 PRUSB - - - PRTIM3 - - PRUSART1
(0x64) PRR0 PRTWI PRTIM2 PRTIM0 - PRTIM1 PRSPI - PRADC
(0x63) Reserved - - - - - - - -
(0x62) Reserved - - - - - - - -
(0x61) CLKPR CLKPCE - - - CLKPS3 CLKPS2 CLKPS1 CLKPS0
(0x60) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0
0x3F (0x5F) SREG I T H S V N Z C
0x3E (0x5E) SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0
0x3C (0x5C) Reserved - - - - - - - -
0x3B (0x5B) RAMPZ - - - - - - RAMPZ1 RAMPZ0
0x3A (0x5A) Reserved - - - - - - - -
0x39 (0x59) Reserved - - - - - - - -
0x38 (0x58) Reserved - - - - - - - -
0x37 (0x57) SPMCSR SPMIE RWWSB SIGRD RWWSRE BLBSET PGWRT PGERS SPMEN
0x36 (0x56) Reserved - - - - - - - -
0x35 (0x55) MCUCR JTD - - PUD - - IVSEL IVCE
0x34 (0x54) MCUSR - - - JTRF WDRF BORF EXTRF PORF
0x33 (0x53) SMCR - - - - SM2 SM1 SM0 SE
0x32 (0x52) Reserved - - - - - - - -
0x31 (0x51) OCDR/
MONDR
OCDR7 OCDR6 OCDR5 OCDR4 OCDR3 OCDR2 OCDR1 OCDR0
Monitor Data Register
0x30 (0x50) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0
0x2F (0x4F) Reserved - - - - - - - -
0x2E (0x4E) SPDR SPI Data Register
0x2D (0x4D) SPSR SPIF WCOL - - - - - SPI2X
0x2C (0x4C) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
0x2B (0x4B) GPIOR2 General Purpose I/O Register 2
0x2A (0x4A) GPIOR1 General Purpose I/O Register 1
0x29 (0x49) PLLCSR - - - PLLP2 PLLP1 PLLP0 PLLE PLOCK
0x28 (0x48) OCR0B Timer/Counter0 Output Compare Register B
0x27 (0x47) OCR0A Timer/Counter0 Output Compare Register A
0x26 (0x46) TCNT0 Timer/Counter0 (8 Bit)
0x25 (0x45) TCCR0B FOC0A FOC0B - - WGM02 CS02 CS01 CS00
0x24 (0x44) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 - - WGM01 WGM00
0x23 (0x43) GTCCR TSM - - - - - PSRASY PSRSYNC
0x22 (0x42) EEARH - - - - EEPROM Address Register High Byte
0x21 (0x41) EEARL EEPROM Address Register Low Byte
0x20 (0x40) EEDR EEPROM Data Register
0x1F (0x3F) EECR - - EEPM1 EEPM0 EERIE EEMPE EEPE EERE
0x1E (0x3E) GPIOR0 General Purpose I/O Register 0
0x1D (0x3D) EIMSK INT7 INT6 INT5 INT4 INT3 INT2 INT1 INT0
0x1C (0x3C) EIFR INTF7 INTF6 INTF5 INTF4 INTF3 INTF2 INTF1 INTF0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page422
7593L–AVR–09/12
AT90USB64/128
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O registers within the address range $00 - $1F are directly bit-accessible using the SBI and CBI instructions. In these registers,
the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on
all bits in the I/O register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions
work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O registers
as data space using LD and ST instructions, $20 must be added to these addresses. The Atmel AT90USB64/128 is a
complex microcontroller with more peripheral units than can be supported within the 64 location reserved in Opcode for the
IN and OUT instructions. For the Extended I/O space from $60 - $1FF in SRAM, only the ST/STS/STD and LD/LDS/LDD
instructions can be used.
0x1B (0x3B) PCIFR - - - - - - - PCIF0
0x1A (0x3A) Reserved - - - - - - - -
0x19 (0x39) Reserved - - - - - - - -
0x18 (0x38) TIFR3 - - ICF3 - OCF3C OCF3B OCF3A TOV3
0x17 (0x37) TIFR2 - - - - - OCF2B OCF2A TOV2
0x16 (0x36) TIFR1 - - ICF1 - OCF1C OCF1B OCF1A TOV1
0x15 (0x35) TIFR0 - - - - - OCF0B OCF0A TOV0
0x14 (0x34) Reserved - - - - - - - -
0x13 (0x33) Reserved - - - - - - - -
0x12 (0x32) Reserved - - - - - - - -
0x11 (0x31) PORTF PORTF7 PORTF6 PORTF5 PORTF4 PORTF3 PORTF2 PORTF1 PORTF0
0x10 (0x30) DDRF DDF7 DDF6 DDF5 DDF4 DDF3 DDF2 DDF1 DDF0
0x0F (0x2F) PINF PINF7 PINF6 PINF5 PINF4 PINF3 PINF2 PINF1 PINF0
0x0E (0x2E) PORTE PORTE7 PORTE6 PORTE5 PORTE4 PORTE3 PORTE2 PORTE1 PORTE0
0x0D (0x2D) DDRE DDE7 DDE6 DDE5 DDE4 DDE3 DDE2 DDE1 DDE0
0x0C (0x2C) PINE PINE7 PINE6 PINE5 PINE4 PINE3 PINE2 PINE1 PINE0
0x0B (0x2B) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0
0x0A (0x2A) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0
0x09 (0x29) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0
0x08 (0x28) PORTC PORTC7 PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0
0x07 (0x27) DDRC DDC7 DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0
0x06 (0x26) PINC PINC7 PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0
0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0
0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0
0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0
0x02 (0x22) PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1 PORTA0
0x01 (0x21) DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0
0x00 (0x20) PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page423
7593L–AVR–09/12
AT90USB64/128
34. Instruction set summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two Registers Rd ← Rd + Rr Z,C,N,V,H 1
ADC Rd, Rr Add with Carry two Registers Rd ← Rd + Rr + C Z,C,N,V,H 1
ADIW Rdl,K Add Immediate to Word Rdh:Rdl ← Rdh:Rdl + K Z,C,N,V,S 2
SUB Rd, Rr Subtract two Registers Rd ← Rd - Rr Z,C,N,V,H 1
SUBI Rd, K Subtract Constant from Register Rd ← Rd - K Z,C,N,V,H 1
SBC Rd, Rr Subtract with Carry two Registers Rd ← Rd - Rr - C Z,C,N,V,H 1
SBCI Rd, K Subtract with Carry Constant from Reg. Rd ← Rd - K - C Z,C,N,V,H 1
SBIW Rdl,K Subtract Immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z,C,N,V,S 2
AND Rd, Rr Logical AND Registers Rd ← Rd • Rr Z,N,V 1
ANDI Rd, K Logical AND Register and Constant Rd ← Rd • K Z,N,V 1
OR Rd, Rr Logical OR Registers Rd ← Rd v Rr Z,N,V 1
ORI Rd, K Logical OR Register and Constant Rd ← Rd v K Z,N,V 1
EOR Rd, Rr Exclusive OR Registers Rd ← Rd ⊕ Rr Z,N,V 1
COM Rd One’s Complement Rd ← 0xFF − Rd Z,C,N,V 1
NEG Rd Two’s Complement Rd ← 0x00 − Rd Z,C,N,V,H 1
SBR Rd,K Set Bit(s) in Register Rd ← Rd v K Z,N,V 1
CBR Rd,K Clear Bit(s) in Register Rd ← Rd • (0xFF - K) Z,N,V 1
INC Rd Increment Rd ← Rd + 1 Z,N,V 1
DEC Rd Decrement Rd ← Rd − 1 Z,N,V 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd Z,N,V 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd Z,N,V 1
SER Rd Set Register Rd ← 0xFF None 1
MUL Rd, Rr Multiply Unsigned R1:R0 ← Rd x Rr Z,C 2
MULS Rd, Rr Multiply Signed R1:R0 ← Rd x Rr Z,C 2
MULSU Rd, Rr Multiply Signed with Unsigned R1:R0 ← Rd x Rr Z,C 2
FMUL Rd, Rr Fractional Multiply Unsigned R1:R0 ← (Rd x Rr) << 1 Z,C 2
FMULS Rd, Rr Fractional Multiply Signed R1:R0 ← (Rd x Rr) << 1 Z,C 2
FMULSU Rd, Rr Fractional Multiply Signed with Unsigned R1:R0 ← (Rd x Rr) << 1 Z,C 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC ← PC + k + 1 None 2
IJMP Indirect Jump to (Z) PC ← Z None 2
EIJMP Extended Indirect Jump to (Z) PC ←(EIND:Z) None 2
JMP k Direct Jump PC ← k None 3
RCALL k Relative Subroutine Call PC ← PC + k + 1 None 4
ICALL Indirect Call to (Z) PC ← Z None 4
EICALL Extended Indirect Call to (Z) PC ←(EIND:Z) None 4
CALL k Direct Subroutine Call PC ← k None 5
RET Subroutine Return PC ← STACK None 5
RETI Interrupt Return PC ← STACK I 5
CPSE Rd,Rr Compare, Skip if Equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd − Rr Z, N,V,C,H 1
CPC Rd,Rr Compare with Carry Rd − Rr − C Z, N,V,C,H 1
CPI Rd,K Compare Register with Immediate Rd − K Z, N,V,C,H 1
SBRC Rr, b Skip if Bit in Register Cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if Bit in Register is Set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3
SBIC P, b Skip if Bit in I/O Register Cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBIS P, b Skip if Bit in I/O Register is Set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2
BREQ k Branch if Equal if (Z = 1) then PC ← PC + k + 1 None 1/2
BRNE k Branch if Not Equal if (Z = 0) then PC ← PC + k + 1 None 1/2
BRCS k Branch if Carry Set if (C = 1) then PC ← PC + k + 1 None 1/2
BRCC k Branch if Carry Cleared if (C = 0) then PC ← PC + k + 1 None 1/2
BRSH k Branch if Same or Higher if (C = 0) then PC ← PC + k + 1 None 1/2
BRLO k Branch if Lower if (C = 1) then PC ← PC + k + 1 None 1/2
BRMI k Branch if Minus if (N = 1) then PC ← PC + k + 1 None 1/2
BRPL k Branch if Plus if (N = 0) then PC ← PC + k + 1 None 1/2
BRGE k Branch if Greater or Equal, Signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2
BRLT k Branch if Less Than Zero, Signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2
BRHS k Branch if Half Carry Flag Set if (H = 1) then PC ← PC + k + 1 None 1/2
BRHC k Branch if Half Carry Flag Cleared if (H = 0) then PC ← PC + k + 1 None 1/2
BRTS k Branch if T Flag Set if (T = 1) then PC ← PC + k + 1 None 1/2
BRTC k Branch if T Flag Cleared if (T = 0) then PC ← PC + k + 1 None 1/2
BRVS k Branch if Overflow Flag is Set if (V = 1) then PC ← PC + k + 1 None 1/2424
7593L–AVR–09/12
AT90USB64/128
BRVC k Branch if Overflow Flag is Cleared if (V = 0) then PC ← PC + k + 1 None 1/2
BRIE k Branch if Interrupt Enabled if ( I = 1) then PC ← PC + k + 1 None 1/2
BRID k Branch if Interrupt Disabled if ( I = 0) then PC ← PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set Bit in I/O Register I/O(P,b) ← 1 None 2
CBI P,b Clear Bit in I/O Register I/O(P,b) ← 0 None 2
LSL Rd Logical Shift Left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z,C,N,V 1
LSR Rd Logical Shift Right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z,C,N,V 1
ROL Rd Rotate Left Through Carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z,C,N,V 1
ROR Rd Rotate Right Through Carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z,C,N,V 1
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 Z,C,N,V 1
SWAP Rd Swap Nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1
BSET s Flag Set SREG(s) ← 1 SREG(s) 1
BCLR s Flag Clear SREG(s) ← 0 SREG(s) 1
BST Rr, b Bit Store from Register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to Register Rd(b) ← T None 1
SEC Set Carry C ← 1 C1
CLC Clear Carry C ← 0 C 1
SEN Set Negative Flag N ← 1 N1
CLN Clear Negative Flag N ← 0 N 1
SEZ Set Zero Flag Z ← 1 Z1
CLZ Clear Zero Flag Z ← 0 Z 1
SEI Global Interrupt Enable I ← 1 I1
CLI Global Interrupt Disable I ← 0 I 1
SES Set Signed Test Flag S ← 1 S1
CLS Clear Signed Test Flag S ← 0 S 1
SEV Set Twos Complement Overflow. V ← 1 V1
CLV Clear Twos Complement Overflow V ← 0 V 1
SET Set T in SREG T ← 1 T1
CLT Clear T in SREG T ← 0 T 1
SEH Set Half Carry Flag in SREG H ← 1 H1
CLH Clear Half Carry Flag in SREG H ← 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move Between Registers Rd ← Rr None 1
MOVW Rd, Rr Copy Register Word Rd+1:Rd ← Rr+1:Rr None 1
LDI Rd, K Load Immediate Rd ← K None 1
LD Rd, X Load Indirect Rd ← (X) None 2
LD Rd, X+ Load Indirect and Post-Inc. Rd ← (X), X ← X + 1 None 2
LD Rd, - X Load Indirect and Pre-Dec. X ← X - 1, Rd ← (X) None 2
LD Rd, Y Load Indirect Rd ← (Y) None 2
LD Rd, Y+ Load Indirect and Post-Inc. Rd ← (Y), Y ← Y + 1 None 2
LD Rd, - Y Load Indirect and Pre-Dec. Y ← Y - 1, Rd ← (Y) None 2
LDD Rd,Y+q Load Indirect with Displacement Rd ← (Y + q) None 2
LD Rd, Z Load Indirect Rd ← (Z) None 2
LD Rd, Z+ Load Indirect and Post-Inc. Rd ← (Z), Z ← Z+1 None 2
LD Rd, -Z Load Indirect and Pre-Dec. Z ← Z - 1, Rd ← (Z) None 2
LDD Rd, Z+q Load Indirect with Displacement Rd ← (Z + q) None 2
LDS Rd, k Load Direct from SRAM Rd ← (k) None 2
ST X, Rr Store Indirect (X) ← Rr None 2
ST X+, Rr Store Indirect and Post-Inc. (X) ← Rr, X ← X + 1 None 2
ST - X, Rr Store Indirect and Pre-Dec. X ← X - 1, (X) ← Rr None 2
ST Y, Rr Store Indirect (Y) ← Rr None 2
ST Y+, Rr Store Indirect and Post-Inc. (Y) ← Rr, Y ← Y + 1 None 2
ST - Y, Rr Store Indirect and Pre-Dec. Y ← Y - 1, (Y) ← Rr None 2
STD Y+q,Rr Store Indirect with Displacement (Y + q) ← Rr None 2
ST Z, Rr Store Indirect (Z) ← Rr None 2
ST Z+, Rr Store Indirect and Post-Inc. (Z) ← Rr, Z ← Z + 1 None 2
ST -Z, Rr Store Indirect and Pre-Dec. Z ← Z - 1, (Z) ← Rr None 2
STD Z+q,Rr Store Indirect with Displacement (Z + q) ← Rr None 2
STS k, Rr Store Direct to SRAM (k) ← Rr None 2
LPM Load Program Memory R0 ← (Z) None 3
LPM Rd, Z Load Program Memory Rd ← (Z) None 3
LPM Rd, Z+ Load Program Memory and Post-Inc Rd ← (Z), Z ← Z+1 None 3
ELPM Extended Load Program Memory R0 ← (RAMPZ:Z) None 3
ELPM Rd, Z Extended Load Program Memory Rd ← (Z) None 3
ELPM Rd, Z+ Extended Load Program Memory Rd ← (RAMPZ:Z), RAMPZ:Z ←RAMPZ:Z+1 None 3
Mnemonics Operands Description Operation Flags #Clocks425
7593L–AVR–09/12
AT90USB64/128
SPM Store Program Memory (Z) ← R1:R0 None -
IN Rd, P In Port Rd ← P None 1
OUT P, Rr Out Port P ← Rr None 1
PUSH Rr Push Register on Stack STACK ← Rr None 2
POP Rd Pop Register from Stack Rd ← STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No Operation None 1
SLEEP Sleep (see specific descr. for Sleep function) None 1
WDR Watchdog Reset (see specific descr. for WDR/timer) None 1
BREAK Break For On-chip Debug Only None N/A
Mnemonics Operands Description Operation Flags #Clocks426
7593L–AVR–09/12
AT90USB64/128
35. Ordering information
35.1 Atmel AT90USB646
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging complies to the European directive for Restriction of Hazardous Substances (RoHS directive). Also
Halide free and fully green.
3. See “Maximum speed vs. VCC” on page 392.
Speed [MHz] Power supply [V] Ordering code (2) USB interface Package (1) Operating range
16 (3) 2.7-5.5
AT90USB646-AU
AT90USB646-MU Device
MD
PS
Industrial
(-40° to +85°C)
MD
64 - lead, 14 × 14mm body size, 1.0mm body thickness
0.8mm lead pitch, thin profile plastic quad flat package (TQFP)
PS
64 - lead, 9 × 9mm body size, 0.50mm pitch
Quad flat no lead package (QFN)427
7593L–AVR–09/12
AT90USB64/128
35.2 Atmel AT90USB647
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging complies to the European directive for Restriction of Hazardous Substances (RoHS directive). Also
Halide free and fully green.
3. See “Maximum speed vs. VCC” on page 392.
Speed [MHz] Power supply [V] Ordering code (2) USB interface Package (1) Operating range
16 (3) 2.7-5.5
AT90USB647-AU
AT90USB647-MU USB OTG MD
PS
Industrial
(-40° to +85°C)
MD
64 - lead, 14 × 14mm body size, 1.0mm body thickness
0.8mm lead pitch, thin profile plastic quad flat package (TQFP)
PS
64 - lead, 9 × 9mm body size, 0.50mm pitch
Quad flat no lead package (QFN)428
7593L–AVR–09/12
AT90USB64/128
35.3 Atmel AT90USB1286
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging complies to the European directive for Restriction of Hazardous Substances (RoHS directive). Also
Halide free and fully green.
3. See “Maximum speed vs. VCC” on page 392.
Speed [MHz] Power supply [V] Ordering code (2) USB interface Package (1) Operating range
16 (3) 2.7-5.5
AT90USB1286-AU
AT90USB1286-MU Device
MD
PS
Industrial
(-40° to +85°C)
MD
64 - lead, 14 × 14mm body size, 1.0mm body thickness
0.8mm lead pitch, thin profile plastic quad flat package (TQFP)
PS
64 - lead, 9 × 9mm body size, 0.50mm pitch
Quad flat no lead package (QFN)429
7593L–AVR–09/12
AT90USB64/128
35.4 Atmel AT90USB1287
Notes: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging complies to the European directive for Restriction of Hazardous Substances (RoHS directive). Also
Halide free and fully green.
3. See “Maximum speed vs. VCC” on page 392.
Speed [MHz] Power supply [V] Ordering code (2) USB interface Package (1) Operating range
16 (3) 2.7-5.5
AT90USB1287-AU
AT90USB1287-MU Host (OTG) MD
PS
Industrial
(-40° to +85°C)
MD
64 - lead, 14 × 14mm body size, 1.0mm body thickness
0.8mm lead pitch, thin profile plastic quad flat package (TQFP)
PS
64 - lead, 9 × 9mm body size, 0.50mm pitch
Quad flat no lead package (QFN)430
7593L–AVR–09/12
AT90USB64/128
36. Packaging information
36.1 TQFP64431
7593L–AVR–09/12
AT90USB64/128432
7593L–AVR–09/12
AT90USB64/128
36.2 QFN64433
7593L–AVR–09/12
AT90USB64/128434
7593L–AVR–09/12
AT90USB64/128
37. Errata
37.1 Atmel AT90USB1287/6 errata
37.1.1 AT90USB1287/6 errata history
Notes: 1. A blank or any alphanumeric string.
37.1.2 AT90USB1287/6 first release
• Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
• USB Eye Diagram violation in low-speed mode
• Transient perturbation in USB suspend mode generates over consumption
• VBUS Session valid threshold voltage
• USB signal rate
• VBUS residual level
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
9. Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
The CPU core may incorrectly execute the interrupt vector related to the VBUSTI and IDTI
interrupt flags.
Problem fix/workaround
Do not enable these interrupts, firmware must process these USB events by polling VBUSTI
and IDTI flags.
8. USB Eye Diagram violation in low-speed mode
The low to high transition of D- violates the USB eye diagram specification when transmitting
with low-speed signaling.
Problem fix/workaround
None.
7. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
Silicon Release 90USB1286-16MU 90USB1287-16AU 90USB1287-16MU
First Release Date Code up to 0648 Date Code up to 0714
and lots 0735 6H2726 (1) Date Code up to 0701
Second Release Date Code from 0709 to 0801
except lots 0801 7H5103 (1)
from Date Code 0722 to 0806
except lots 0735 6H2726 (1)
Date Code from 0714 to 0810
except lots 0748 7H5103 (1)
Third Release Lots 0801 7H5103 (1) and
Date Code from 0814 Date Code from 0814 Lots 0748 7H5103 (1) and
Date Code from 0814
Fourth Release TBD TBD TBD435
7593L–AVR–09/12
AT90USB64/128
not set the SUSPI bit anymore. The internal USB engine remains in suspend mode but the
USB differential receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be
performed by software (instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
6. VBUS session valid threshold voltage
The VSession valid threshold voltage is internally connected to VBus_Valid (4.4V approx.).
That causes the device to attach to the bus only when Vbus is greater than VBusValid
instead of V_Session Valid. Thus if VBUS is lower than 4.4V, the device is detached.
Problem fix/workaround
According to the USB power drop budget, this may require connecting the device toa root
hub or a self-powered hub.
5. UBS signal rate
The average USB signal rate may sometime be measured out of the USB specifications
(12MHz ±30kHz) with short frames. When measured on a long period, the average signal
rate value complies with the specifications. This bit rate deviation does not generates communication
or functional errors.
Problem fix/workaround
None.
4. VBUS residual level
In USB device and host mode, once a 5V level has been detected to the VBUS pad, a residual
level (about 3V) can be measured on the VBUS pin.
Problem fix/workaround
None.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.
Problem fix/workaround
No known workaround, enable Atmel AT90USB64/128 TWI first versus the others nodes of
the TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from the sleep mode should
be disabled.436
7593L–AVR–09/12
AT90USB64/128
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep and wakes-up from an asynchronous timer interrupt and then go
back in sleep again it may wake up multiple times.
Problem fix/workaround
A software workaround is to wait with performing the sleep instruction until
TCNT2>OCR2+1.437
7593L–AVR–09/12
AT90USB64/128
37.1.3 Atmel AT90USB1287/6 second release
• Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
• USB Eye Diagram violation in low-speed mode
• Transient perturbation in USB suspend mode generates over consumption
• VBUS Session valid threshold voltage
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
7. Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
The CPU core may incorrectly execute the interrupt vector related to the VBUSTI and IDTI
interrupt flags.
Problem fix/workaround
Do not enable these interrupts, firmware must process these USB events by polling VBUSTI
and IDTI flags.
6. USB Eye Diagram violation in low-speed mode
The low to high transition of D- violates the USB eye diagram specification when transmitting
with low-speed signaling.
Problem fix/workaround
None.
5. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
not set the SUSPI bit anymore. The internal USB engine remains in suspend mode but the
USB differential receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be
performed by software (instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
4. VBUS session valid threshold voltage
The VSession valid threshold voltage is internally connected to VBus_Valid (4.4V approx.).
That causes the device to attach to the bus only when Vbus is greater than VBusValid
instead of V_Session Valid. Thus if VBUS is lower than 4.4V, the device is detached.
Problem fix/workaround
According to the USB power drop budget, this may require connecting the device toa root
hub or a self-powered hub.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.438
7593L–AVR–09/12
AT90USB64/128
Problem fix/workaround
No known workaround, enable Atmel AT90USB64/128 TWI first versus the others nodes of
the TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from the sleep mode should
be disabled.
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep and wakes-up from an asynchronous timer interrupt and then go
back in sleep again it may wake up multiple times.
Problem fix/workaround
A software workaround is to wait with performing the sleep instruction until
TCNT2>OCR2+1.439
7593L–AVR–09/12
AT90USB64/128
37.1.4 Atmel AT90USB1287/6 Third Release
• Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
• Transient perturbation in USB suspend mode generates over consumption
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
5. Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
The CPU core may incorrectly execute the interrupt vector related to the VBUSTI and IDTI
interrupt flags.
Problem fix/workaround
Do not enable these interrupts, firmware must process these USB events by polling VBUSTI
and IDTI flags.
4. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
not set the SUSPI bit. The internal USB engine remains in suspend mode but the USB differential
receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be performed by software
(instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.
Problem fix/workaround
No known workaround, enable AT90USB64/128 TWI first, before the others nodes of the
TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from sleep mode should be
disabled.
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep mode and wakes-up from an asynchronous timer interrupt and
then goes back into sleep mode, it may wake up multiple times.440
7593L–AVR–09/12
AT90USB64/128
Problem fix/workaround
A software workaround is to wait before performing the sleep instruction: until
TCNT2>OCR2+1.441
7593L–AVR–09/12
AT90USB64/128
37.1.5 Atmel AT90USB1287/6 Fourth Release
• Transient perturbation in USB suspend mode generates over consumption
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
4. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
not set the SUSPI bit. The internal USB engine remains in suspend mode but the USB differential
receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be performed by software
(instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.
Problem fix/workaround
No known workaround, enable Atmel AT90USB64/128 TWI first, before the others nodes of
the TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from sleep mode should be
disabled.
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep mode and wakes-up from an asynchronous timer interrupt and
then goes back into sleep mode, it may wake up multiple times.
Problem fix/workaround
A software workaround is to wait before performing the sleep instruction: until
TCNT2>OCR2+1.442
7593L–AVR–09/12
AT90USB64/128
37.2 Atmel AT90USB646/7 errata
37.2.1 AT90USB646/7 errata history TBD
Note ‘*’ means a blank or any alphanumeric string.
37.2.2 AT90USB646/7 first release.
• Incorrect interrupt routine execution for VBUSTI, IDTI interrupts flags
• USB Eye Diagram violation in low-speed mode
• Transient perturbation in USB suspend mode generates over consumption
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
6. Incorrect CPU behavior for VBUSTI and IDTI interrupts routines
The CPU core may incorrectly execute the interrupt vector related to the VBUSTI and IDTI
interrupt flags.
Problem fix/workaround
Do not enable these interrupts, firmware must process these USB events by polling VBUSTI
and IDTI flags.
5. USB Eye Diagram violation in low-speed mode
The low to high transition of D- violates the USB eye diagram specification when transmitting
with low-speed signaling.
Problem fix/workaround
None.
4. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
not set the SUSPI bit anymore. The internal USB engine remains in suspend mode but the
USB differential receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be
performed by software (instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.
Silicon Release 90USB646-16MU 90USB647-16AU 90USB647-16MU
First Release
Second Release443
7593L–AVR–09/12
AT90USB64/128
Problem fix/workaround
No known workaround, enable Atmel AT90USB64/128 TWI first versus the others nodes of
the TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from the sleep mode should
be disabled.
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep and wakes-up from an asynchronous timer interrupt and then go
back in sleep mode again it may wake up several times.
Problem fix/workaround
A software workaround is to wait with performing the sleep instruction until
TCNT2>OCR2+1.444
7593L–AVR–09/12
AT90USB64/128
37.2.3 Atmel AT90USB646/7 Second Release.
• USB Eye Diagram violation in low-speed mode
• Transient perturbation in USB suspend mode generates over consumption
• Spike on TWI pins when TWI is enabled
• High current consumption in sleep mode
• Async timer interrupt wake up from sleep generate multiple interrupts
5. USB Eye Diagram violation in low-speed mode
The low to high transition of D- violates the USB eye diagram specification when transmitting
with low-speed signaling.
Problem fix/workaround
None.
4. Transient perturbation in USB suspend mode generates overconsumption
In device mode and when the USB is suspended, transient perturbation received on the
USB lines generates a wake up state. However the idle state following the perturbation does
not set the SUSPI bit anymore. The internal USB engine remains in suspend mode but the
USB differential receiver is still enabled and generates a typical 300µA extra-power consumption.
Detection of the suspend state after the transient perturbation should be
performed by software (instead of reading the SUSPI bit).
Problem fix/workaround
USB waiver allows bus powered devices to consume up to 2.5mA in suspend state.
3. Spike on TWI pins when TWI is enabled
100ns negative spike occurs on SDA and SCL pins when TWI is enabled.
Problem fix/workaround
No known workaround, enable Atmel AT90USB64/128 TWI first versus the others nodes of
the TWI network.
2. High current consumption in sleep mode
If a pending interrupt cannot wake the part up from the selected mode, the current consumption
will increase during sleep when executing the SLEEP instruction directly after a SEI
instruction.
Problem fix/workaround
Before entering sleep, interrupts not used to wake up the part from the sleep mode should
be disabled.
1. Asynchronous timer interrupt wake up from sleep generates multiple interrupts
If the CPU core is in sleep and wakes-up from an asynchronous timer interrupt and then go
back in sleep mode again it may wake up several times.
Problem fix/workaround
A software workaround is to wait with performing the sleep instruction until
TCNT2>OCR2+1.445
7593L–AVR–09/12
AT90USB64/128
38. Datasheet revision history for Atmel AT90USB64/128
Please note that the referring page numbers in this section are referred to this document. The
referring revision in this section are referring to the document revision.
38.1 Changes from 7593A to 7593B
1. Changed default configuration for fuse bytes and security byte.
2. Suppression of timer 4,5 registers which does not exist.
3. Updated typical application schematics in USB section
38.2 Changes from 7593B to 7593C
1. Update to package drawings, MQFP64 and TQFP64.
38.3 Changes from 7593C to 7593D
1. For further product compatibility, changed USB PLL possible prescaler configurations.
Only 8MHz and 16MHz crystal frequencies allows USB operation (see Table 7-11 on
page 50).
38.4 Changes from 7593D to 7593E
1. Updated PLL Prescaler table: configuration words are different between AT90USB64x
and AT90USB128x to enable the PLL with a 16MHz source.
2. Cleaned up some bits from USB registers, and updated information about OTG timers,
remote wake-up, reset and connection timings.
3. Updated clock distribution tree diagram (USB prescaler source and configuration
register).
4. Cleaned up register summary.
5. Suppressed PCINT23:8 that do not exist from External Interrupts.
6. Updated Electrical Characteristics.
7. Added Typical Characteristics.
8. Update Errata section.
38.5 Changes from 7593E to 7593F
1. Removed ’Preliminary’ from document status.
2. Clarification in Stand by mode regarding USB.
38.6 Changes from 7593F to 7593G
1. Updated Errata section.
38.7 Changes from 7593G to 7593H
1. Added Signature information for 64K devices.
2. Fixed figure for typical bus powered application
3. Added min/max values for BOD levels
4. Added ATmega32U6 product
5. Update Errata section
6. Modified descriptions for HWUPE and WAKEUPE interrupts enable (these interrupts
should be enabled only to wake up the CPU core from power down mode).446
7593L–AVR–09/12
AT90USB64/128
7. Added description to access unique serial number located in Signature Row see
“Reading the Signature Row from software” on page 354.
38.8 Changes from 7593H to 7593I
1. Updated Table 9-2 in “Brown-out detection” on page 60. Unused BOD levels removed.
38.9 Changes from 7593I to 7593J
1. Updated Table 9-2 in “Brown-out detection” on page 60. BOD level 100 removed.
2. Updated “Ordering information” on page 426.
3. Removed ATmega32U6 errata section.
38.10 Changes from 7593J to 7593K
1. Corrected Figure 6-7 on page 34, Figure 6-8 on page 34 and Figure 6-9 on page 35.
2. Corrected ordering information for Section 35.3 ”Atmel AT90USB1286” on page 428,
Section 35.4 ”Atmel AT90USB1287” on page 429 andSection 35.2 ”Atmel
AT90USB647” on page 427.
3. Removed the ATmega32U6 device and updated the datasheet accordingly.
4. Updated Assembly Code Example in “Watchdog reset” on page 61.
38.11 Changes from 7593K to 7593L
1. Updated the “Ordering information” on page 426. Changed the speed from 20MHz to
16MHz.
2. Replaced ATmegaAT90USBxxxx by AT90USBxxxx through the datasheet.
3. Updated the first paragraph of “Overview” on page 307. Port A replaced by Port F.
4. Updated ADC equation in “ADC conversion result” on page 318. The equation has
1024 instead of 1023.
5. Created “Packaging Information” chapter.
6. Replaced the “QFN64” Packaging by an updated QFN64 Packaging drawing.
7. Updated “Errata” on page 434. AT90USB1286/7 has a fourth release, while
AT90USB646/7 updated with a second release.
8. In Section “Overview” on page 307, “Port A” has been replaced by “Port F” in the first
section.
9. In Section “Atmel AT90USB647” on page 427 the USB interface has been changed to
USB OTG.
10. In Section “Atmel AT90USB1286” on page 428 the USB interface has been changed to
Device.
11. In Section “Atmel AT90USB1287” on page 429 the USB interface has been changed to
Host OTG.
12. General update according to new template.i
7593L–AVR–09/12
AT90USB64X/128X
Table of contents
Features ..................................................................................................... 1
1 Pin configurations ................................................................................... 3
2 Overview ................................................................................................... 5
2.1 Block diagram ..........................................................................................................6
2.2 Pin descriptions .......................................................................................................8
3 Resources ............................................................................................... 10
4 About code examples ............................................................................ 10
5 AVR CPU core ........................................................................................ 11
5.1 Introduction ............................................................................................................11
5.2 Architectural overview ...........................................................................................11
5.3 ALU – Arithmetic Logic Unit ..................................................................................12
5.4 Status register .......................................................................................................13
5.5 General purpose register file .................................................................................14
5.6 Stack pointer .........................................................................................................15
5.7 Instruction execution timing ...................................................................................16
5.8 Reset and interrupt handling .................................................................................17
6 Atmel AVR AT90USB64/128 memories ................................................ 20
6.1 In-system re-programmable flash program memory .............................................20
6.2 SRAM data memory ..............................................................................................21
6.3 EEPROM data memory .........................................................................................24
6.4 I/O memory ............................................................................................................30
6.5 External memory interface ....................................................................................31
7 System clock and clock options .......................................................... 40
7.1 Clock systems and their distribution ......................................................................40
7.2 Clock sources ........................................................................................................41
7.3 Low power crystal oscillator ..................................................................................42
7.4 Low frequency crystal oscillator ............................................................................44
7.5 Calibrated internal RC oscillator ............................................................................45
7.6 External clock ........................................................................................................46
7.7 Clock output buffer ................................................................................................47
7.8 Timer/counter oscillator .........................................................................................47
7.9 System clock prescaler .........................................................................................47ii
7593L–AVR–09/12
AT90USB64X/128X
7.10 PLL ......................................................................................................................49
8 Power management and sleep modes ................................................. 51
8.1 Idle mode ...............................................................................................................52
8.2 ADC noise reduction mode ...................................................................................52
8.3 Power-down mode ................................................................................................52
8.4 Power-save mode .................................................................................................52
8.5 Standby mode .......................................................................................................53
8.6 Extended Standby mode .......................................................................................53
8.7 Power Reduction Register .....................................................................................54
8.8 Minimizing power consumption .............................................................................55
9 System control and reset ...................................................................... 57
9.1 Resetting the AVR .................................................................................................57
9.2 Reset sources .......................................................................................................57
9.3 Power-on reset ......................................................................................................58
9.4 External reset ........................................................................................................59
9.5 Brown-out detection ..............................................................................................60
9.6 Watchdog reset .....................................................................................................61
9.7 Internal voltage reference ......................................................................................62
9.8 Watchdog timer .....................................................................................................63
10 Interrupts ................................................................................................ 68
10.1 Interrupt vectors in AT90USB64/128 ...................................................................68
11 I/O-ports .................................................................................................. 71
11.1 Introduction ..........................................................................................................71
11.2 Ports as general digital I/O ..................................................................................72
11.3 Alternate port functions .......................................................................................76
11.4 Register description for I/O-ports ........................................................................89
12 External interrupts ................................................................................. 92
13 Timer/Counter0, Timer/Counter1, and Timer/Counter3 prescalers ... 96
13.1 Internal clock source ...........................................................................................96
13.2 Prescaler reset ....................................................................................................96
13.3 External clock source ..........................................................................................96
13.4 GTCCR – General Timer/Counter Control Register ............................................97
14 8-bit Timer/Counter0 with PWM ............................................................ 98
14.1 Overview .............................................................................................................98iii
7593L–AVR–09/12
AT90USB64X/128X
14.2 Timer/Counter clock sources ...............................................................................99
14.3 Counter unit .........................................................................................................99
14.4 Output compare unit ..........................................................................................100
14.5 Compare Match Output Unit ..............................................................................102
14.6 Modes of operation ............................................................................................103
14.7 Timer/Counter timing diagrams .........................................................................107
14.8 8-bit Timer/Counter register description ............................................................108
15 16-bit Timer/Counter (Timer/Counter1 and Timer/Counter3) ........... 115
15.1 Overview ...........................................................................................................115
15.2 Accessing 16-bit registers .................................................................................117
15.3 Timer/Counter clock sources .............................................................................120
15.4 Counter unit .......................................................................................................121
15.5 Input Capture unit ..............................................................................................122
15.6 Output Compare units .......................................................................................124
15.7 Compare Match Output unit ..............................................................................126
15.8 Modes of operation ............................................................................................127
15.9 Timer/Counter timing diagrams .........................................................................134
15.10 16-bit Timer/Counter register description ........................................................136
16 8-bit Timer/Counter2 with PWM and asynchronous operation ........ 145
16.1 Overview ...........................................................................................................145
16.2 Timer/Counter clock sources .............................................................................146
16.3 Counter unit .......................................................................................................146
16.4 Output Compare unit .........................................................................................147
16.5 Compare Match Output unit ..............................................................................149
16.6 Modes of operation ............................................................................................150
16.7 Timer/Counter timing diagrams .........................................................................154
16.8 8-bit Timer/Counter register description ............................................................156
16.9 Asynchronous operation of the Timer/Counter ..................................................161
16.10 Timer/Counter prescaler ..................................................................................164
17 Output Compare Modulator (OCM1C0A) ........................................... 166
17.1 Overview ...........................................................................................................166
17.2 Description ........................................................................................................166
18 SPI – Serial Peripheral Interface ......................................................... 168
18.1 SS Pin Functionality ..........................................................................................172
18.2 Data modes .......................................................................................................175iv
7593L–AVR–09/12
AT90USB64X/128X
19 USART ................................................................................................... 177
19.1 Overview ...........................................................................................................177
19.2 Clock generation ...............................................................................................178
19.3 Frame formats ...................................................................................................180
19.4 USART initialization ...........................................................................................181
19.5 Data transmission – The USART transmitter ....................................................182
19.6 Data reception – The USART receiver ..............................................................185
19.7 Asynchronous data reception ............................................................................189
19.8 Multi-processor Communication mode ..............................................................192
19.9 USART register description ...............................................................................193
19.10 Examples of baud rate setting .........................................................................198
20 USART in SPI mode ............................................................................. 202
20.1 Overview ...........................................................................................................202
20.2 Clock generation ...............................................................................................202
20.3 SPI data modes and timing ...............................................................................203
20.4 Frame formats ...................................................................................................203
20.5 Data transfer ......................................................................................................205
20.6 USART MSPIM register description ..................................................................207
20.7 AVR USART MSPIM vs. AVR SPI ....................................................................209
21 2-wire serial interface .......................................................................... 211
21.1 Features ............................................................................................................211
21.2 2-wire Serial Interface bus definition .................................................................211
21.3 Data transfer and frame format .........................................................................212
21.4 Multi-master bus systems, arbitration and synchronization ...............................215
21.5 Overview of the TWI module .............................................................................216
21.6 TWI register description ....................................................................................219
21.7 Using the TWI ....................................................................................................222
21.8 Transmission modes .........................................................................................225
21.9 Multi-master systems and arbitration .................................................................239
22 USB controller ...................................................................................... 241
22.1 Features ............................................................................................................241
22.2 Block diagram ....................................................................................................241
22.3 Typical application implementation ...................................................................242
22.4 General operating modes ..................................................................................246
22.5 Power modes ....................................................................................................250v
7593L–AVR–09/12
AT90USB64X/128X
22.6 Speed control ....................................................................................................251
22.7 Memory management .......................................................................................252
22.8 PAD suspend ....................................................................................................253
22.9 OTG timers customizing ....................................................................................254
22.10 Plug-in detection ..............................................................................................255
22.11 ID detection .....................................................................................................256
22.12 Registers description .......................................................................................256
22.13 USB Software Operating modes .....................................................................261
23 USB device operating modes ............................................................. 262
23.1 Introduction ........................................................................................................262
23.2 Power-on and reset ...........................................................................................262
23.3 Endpoint reset ...................................................................................................262
23.4 USB reset ..........................................................................................................263
23.5 Endpoint selection .............................................................................................263
23.6 Endpoint activation ............................................................................................263
23.7 Address setup ...................................................................................................264
23.8 Suspend, wake-up and resume .........................................................................265
23.9 Detach ...............................................................................................................265
23.10 Remote Wake-up ............................................................................................266
23.11 STALL request ................................................................................................266
23.12 CONTROL endpoint management ..................................................................267
23.13 OUT endpoint management ............................................................................268
23.14 IN endpoint management ................................................................................269
23.15 Isochronous mode ...........................................................................................271
23.16 Overflow ..........................................................................................................272
23.17 Interrupts .........................................................................................................272
23.18 Registers .........................................................................................................273
24 USB host operating modes ................................................................. 285
24.1 Pipe description .................................................................................................285
24.2 Detach ...............................................................................................................285
24.3 Power-on and reset ...........................................................................................285
24.4 Device detection ................................................................................................286
24.5 Pipe selection ....................................................................................................286
24.6 Pipe configuration ..............................................................................................286
24.7 USB reset ..........................................................................................................288vi
7593L–AVR–09/12
AT90USB64X/128X
24.8 Address setup ...................................................................................................288
24.9 Remote wake-up detection ................................................................................288
24.10 USB pipe reset ................................................................................................288
24.11 Pipe data access .............................................................................................288
24.12 Control pipe management ...............................................................................289
24.13 OUT pipe management ...................................................................................289
24.14 IN Pipe management .......................................................................................290
24.15 Interrupt system ...............................................................................................291
24.16 Registers .........................................................................................................292
25 Analog Comparator ............................................................................. 304
25.1 Analog Comparator multiplexed input ...............................................................306
26 ADC – Analog to Digital Converter ..................................................... 307
26.1 Features ............................................................................................................307
26.2 Overview ...........................................................................................................307
26.3 Operation ...........................................................................................................309
26.4 Starting a conversion .........................................................................................309
26.5 Prescaling and conversion timing ......................................................................310
26.6 Changing channel or reference selection ..........................................................313
26.7 ADC noise canceler ...........................................................................................314
26.8 ADC conversion result .......................................................................................318
26.9 ADC register description ...................................................................................321
27 JTAG interface and on-chip debug system ....................................... 327
27.1 Overview ...........................................................................................................327
27.2 TAP – Test Access Port ....................................................................................327
27.3 TAP Controller ...................................................................................................329
27.4 Using the Boundary-scan chain ........................................................................330
27.5 Using the on-chip debug system .......................................................................330
27.6 On-chip debug specific JTAG instructions .........................................................331
27.7 On-chip Debug related Register in I/O memory ................................................332
27.8 Using the JTAG programming capabilities ........................................................332
27.9 Bibliography .......................................................................................................332
28 IEEE 1149.1 (JTAG) boundary-scan ................................................... 333
28.1 Features ............................................................................................................333
28.2 System overview ...............................................................................................333
28.3 Data registers ....................................................................................................333vii
7593L–AVR–09/12
AT90USB64X/128X
28.4 Boundary-scan specific JTAG instructions ........................................................335
28.5 Boundary-scan Related Register in I/O memory ...............................................336
28.6 Boundary-scan chain .........................................................................................337
28.7 Atmel AT90USB64/128 Boundary-scan order ...................................................340
28.8 Boundary-scan description language files .........................................................342
29 Boot Loader support – read-while-write self-programming ............. 343
29.1 Boot Loader features .........................................................................................343
29.2 Application and Boot Loader flash sections ......................................................343
29.3 Read-while-write and no read-while-write flash sections ...................................343
29.4 Boot Loader lock bits .........................................................................................346
29.5 Entering the Boot Loader program ....................................................................347
29.6 Addressing the flash during self-programming ..................................................350
29.7 Self-programming the flash ...............................................................................351
30 Memory programming ......................................................................... 359
30.1 Program and data memory lock bits ..................................................................359
30.2 Fuse bits ............................................................................................................360
30.3 Signature bytes .................................................................................................362
30.4 Calibration byte .................................................................................................362
30.5 Parallel programming parameters, pin mapping, and commands .....................362
30.6 Parallel programming ........................................................................................365
30.7 Serial downloading ............................................................................................373
30.8 Serial programming pin mapping ......................................................................374
30.9 Programming via the JTAG interface ................................................................377
31 Electrical characteristics for Atmel AT90USB64/128 ....................... 390
31.1 Absolute maximum ratings* ...............................................................................390
31.2 DC characteristics .............................................................................................390
31.3 External clock drive waveforms .........................................................................392
31.4 External clock drive ...........................................................................................392
31.5 Maximum speed vs. VCC ...........................................................................................................................392
31.6 2-wire serial interface characteristics ................................................................393
31.7 SPI timing characteristics ..................................................................................395
31.8 Hardware boot entrance timing characteristics .................................................396
31.9 ADC characteristics ...........................................................................................397
31.10 External data memory timing ...........................................................................399
32 Atmel AT90USB64/128 typical characteristics ................................. 404viii
7593L–AVR–09/12
AT90USB64X/128X
32.1 Input voltage levels ............................................................................................405
32.2 Output voltage levels .........................................................................................406
32.3 Power-down supply current ...............................................................................408
32.4 Power-save supply current ................................................................................409
32.5 Idle supply current .............................................................................................410
32.6 Active supply current .........................................................................................410
32.7 Reset supply current .........................................................................................411
32.8 I/O pull-up current ..............................................................................................411
32.9 Bandgap voltage ...............................................................................................412
32.10 Internal ARef voltage .......................................................................................413
32.11 USB regulator ..................................................................................................413
32.12 BOD levels ......................................................................................................414
32.13 Watchdog timer frequency ..............................................................................416
32.14 Internal RC oscillator frequency ......................................................................416
32.15 Power-on reset ................................................................................................418
33 Register summary ................................................................................ 419
34 Instruction set summary ..................................................................... 423
35 Ordering information ........................................................................... 426
35.1 Atmel AT90USB646 ..........................................................................................426
35.2 Atmel AT90USB647 ..........................................................................................427
35.3 Atmel AT90USB1286 ........................................................................................428
35.4 Atmel AT90USB1287 ........................................................................................429
36 Packaging information ........................................................................ 430
36.1 TQFP64 .............................................................................................................430
36.2 QFN64 ...............................................................................................................432
37 Errata ..................................................................................................... 434
37.1 Atmel AT90USB1287/6 errata ...........................................................................434
37.2 Atmel AT90USB646/7 errata .............................................................................442
38 Datasheet revision history for Atmel AT90USB64/128 ..................... 445
38.1 Changes from 7593A to 7593B .........................................................................445
38.2 Changes from 7593B to 7593C .........................................................................445
38.3 Changes from 7593C to 7593D .........................................................................445
38.4 Changes from 7593D to 7593E .........................................................................445
38.5 Changes from 7593E to 7593F .........................................................................445ix
7593L–AVR–09/12
AT90USB64X/128X
38.6 Changes from 7593F to 7593G .........................................................................445
38.7 Changes from 7593G to 7593H ........................................................................445
38.8 Changes from 7593H to 7593I ..........................................................................446
38.9 Changes from 7593I to 7593J ...........................................................................446
38.10 Changes from 7593J to 7593K ........................................................................446
38.11 Changes from 7593K to 7593L .......................................................................446
Table of contents ....................................................................................... i7593L–AVR–09/12
Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131
USA
Tel: (+1)(408) 441-0311
Fax: (+1)(408) 487-2600
www.atmel.com
Atmel Asia Limited
Unit 1-5 & 16, 19/F
BEA Tower, Millennium City 5
418 Kwun Tong Road
Kwun Tong, Kowloon
HONG KONG
Tel: (+852) 2245-6100
Fax: (+852) 2722-1369
Atmel Munich GmbH
Business Campus
Parkring 4
D-85748 Garching b. Munich
GERMANY
Tel: (+49) 89-31970-0
Fax: (+49) 89-3194621
Atmel Japan
16F, Shin Osaki Kangyo Bldg.
1-6-4 Osaki Shinagawa-ku
Tokyo 104-0032
JAPAN
Tel: (+81) 3-6417-0300
Fax: (+81) 3-6417-0370
© 2012 Atmel Corporation. All rights reserved.
Atmel®, Atmel logo and combinations thereof, AVR®, AVR Studio®, and others are registered trademarks or trademarks of Atmel Corporation
or its subsidiaries. Windows® is a registered trademark of Microsoft Corporation in U.S. and or other countries. Other terms
and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to
any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL
TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY
EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT,
INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS,
BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness
of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice.
Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable
for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications
intended to support or sustain life.
Features
• High performance, low power Atmel® AVR® 8-bit microcontroller
• Advanced RISC architecture
– 131 powerful instructions – most single clock cycle execution
– 32 × 8 general purpose working registers
– Fully static operation
– Up to 20 MIPS throughput at 20MHz
– On-chip 2-cycle multiplier
• High endurance non-volatile memory segments
– 4/8/16 Kbytes of in-system self-programmable flash program memory
– 256/512/512 bytes EEPROM
– 512/1K/1Kbytes internal SRAM
– Write/erase cyles: 10,000 flash/100,000 EEPROM
– Data retention: 20 years at 85°C/100 years at 25°C()
– Optional boot code section with independent lock bits
In-system programming by on-chip boot program
True read-while-write operation
– Programming lock for software security
• QTouch® library support
– Capacitive touch buttons, sliders and wheels
– QTouch and QMatrix acquisition
– Up to 64 sense channels
• Peripheral features
– Two 8-bit timer/counters with separate prescaler and compare mode
– One 16-bit timer/counter with separate prescaler, compare mode, and capture mode
– Real time counter with separate oscillator
– Six PWM channels
– 8-channel 10-bit ADC in TQFP and QFN/MLF package
– 6-channel 10-bit ADC in PDIP Package
– Programmable serial USART
– Master/slave SPI serial interface
– Byte-oriented 2-wire serial interface (Philips I2
C compatible)
– Programmable watchdog timer with separate on-chip oscillator
– On-chip analog comparator
– Interrupt and wake-up on pin change
• Special microcontroller features
– DebugWIRE on-chip debug system
– Power-on reset and programmable brown-out detection
– Internal calibrated oscillator
– External and internal interrupt sources
– Five sleep modes: Idle, ADC noise reduction, power-save, power-down, and standby
• I/O and packages
– 23 programmable I/O lines
– 28-pin PDIP, 32-lead TQFP, 28-pad QFN/MLF and 32-pad QFN/MLF
• Operating voltage:
– 1.8V - 5.5V for Atmel ATmega48V/88V/168V
– 2.7V - 5.5V for Atmel ATmega48/88/168
• Temperature range:
– -40°C to 85°C
• Speed grade:
– ATmega48V/88V/168V: 0 - 4MHz @ 1.8V - 5.5V, 0 - 10MHz @ 2.7V - 5.5V
– ATmega48/88/168: 0 - 10MHz @ 2.7V - 5.5V, 0 - 20MHz @ 4.5V - 5.5V
• Low power consumption
– Active mode:
250µA at 1MHz, 1.8V
15µA at 32kHz, 1.8V (including oscillator)
– Power-down mode:
0.1µA at 1.8V
Note: 1. See “Data retention” on page 8 for details.
8-bit Atmel
Microcontroller
with 4/8/16K
Bytes In-System
Programmable
Flash
ATmega48/V
ATmega88/V
ATmega168/V
Rev. 2545T–AVR–05/112
2545T–AVR–05/11
ATmega48/88/168
1. Pin configurations
Figure 1-1. Pinout Atmel ATmega48/88/168.
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
(PCINT19/OC2B/INT1) PD3
(PCINT20/XCK/T0) PD4
GND
VCC
GND
VCC
(PCINT6/XTAL1/TOSC1) PB6
(PCINT7/XTAL2/TOSC2) PB7
PC1 (ADC1/PCINT9)
PC0 (ADC0/PCINT8)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK/PCINT5)
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
(PCINT1/OC1A) PB1
(PCINT2/SS/OC1B) PB2
(PCINT3/OC2A/MOSI) PB3
(PCINT4/MISO) PB4
PD2 (INT0/PCINT18)
PD1 (TXD/PCINT17)
PD0 (RXD/PCINT16)
PC6 (RESET/PCINT14)
PC5 (ADC5/SCL/PCINT13)
PC4 (ADC4/SDA/PCINT12)
PC3 (ADC3/PCINT11)
PC2 (ADC2/PCINT10)
TQFP Top View
1
2
3
4
5
6
7
8
9
10
11
12
13
14
28
27
26
25
24
23
22
21
20
19
18
17
16
15
(PCINT14/RESET) PC6
(PCINT16/RXD) PD0
(PCINT17/TXD) PD1
(PCINT18/INT0) PD2
(PCINT19/OC2B/INT1) PD3
(PCINT20/XCK/T0) PD4
VCC
GND
(PCINT6/XTAL1/TOSC1) PB6
(PCINT7/XTAL2/TOSC2) PB7
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
PC5 (ADC5/SCL/PCINT13)
PC4 (ADC4/SDA/PCINT12)
PC3 (ADC3/PCINT11)
PC2 (ADC2/PCINT10)
PC1 (ADC1/PCINT9)
PC0 (ADC0/PCINT8)
GND
AREF
AVCC
PB5 (SCK/PCINT5)
PB4 (MISO/PCINT4)
PB3 (MOSI/OC2A/PCINT3)
PB2 (SS/OC1B/PCINT2)
PB1 (OC1A/PCINT1)
PDIP
1
2
3
4
5
6
7
8
24
23
22
21
20
19
18
17
32
31
30
29
28
27
26
25
9
10
11
12
13
14
15
16
32 MLF Top View
(PCINT19/OC2B/INT1) PD3
(PCINT20/XCK/T0) PD4
GND
VCC
GND
VCC
(PCINT6/XTAL1/TOSC1) PB6
(PCINT7/XTAL2/TOSC2) PB7
PC1 (ADC1/PCINT9)
PC0 (ADC0/PCINT8)
ADC7
GND
AREF
ADC6
AVCC
PB5 (SCK/PCINT5)
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
(PCINT1/OC1A) PB1
(PCINT2/SS/OC1B) PB2
(PCINT3/OC2A/MOSI) PB3
(PCINT4/MISO) PB4
PD2 (INT0/PCINT18)
PD1 (TXD/PCINT17)
PD0 (RXD/PCINT16)
PC6 (RESET/PCINT14)
PC5 (ADC5/SCL/PCINT13)
PC4 (ADC4/SDA/PCINT12)
PC3 (ADC3/PCINT11)
PC2 (ADC2/PCINT10)
NOTE: Bottom pad should be soldered to ground.
1
2
3
4
5
6
7
21
20
19
18
17
16
15
28
27
26
25
24
23
22
8
9
10
11
12
13
14
28 MLF Top View
(PCINT19/OC2B/INT1) PD3
(PCINT20/XCK/T0) PD4
VCC
GND
(PCINT6/XTAL1/TOSC1) PB6
(PCINT7/XTAL2/TOSC2) PB7
(PCINT21/OC0B/T1) PD5
(PCINT22/OC0A/AIN0) PD6
(PCINT23/AIN1) PD7
(PCINT0/CLKO/ICP1) PB0
(PCINT1/OC1A) PB1
(PCINT2/SS/OC1B) PB2
(PCINT3/OC2A/MOSI) PB3
(PCINT4/MISO) PB4
PD2 (INT0/PCINT18)
PD1 (TXD/PCINT17)
PD0 (RXD/PCINT16)
PC6 (RESET/PCINT14)
PC5 (ADC5/SCL/PCINT13)
PC4 (ADC4/SDA/PCINT12)
PC3 (ADC3/PCINT11)
PC2 (ADC2/PCINT10)
PC1 (ADC1/PCINT9)
PC0 (ADC0/PCINT8)
GND
AREF
AVCC
PB5 (SCK/PCINT5)
NOTE: Bottom pad should be soldered to ground.3
2545T–AVR–05/11
ATmega48/88/168
1.1 Pin descriptions
1.1.1 VCC
Digital supply voltage.
1.1.2 GND
Ground.
1.1.3 Port B (PB7:0) XTAL1/XTAL2/TOSC1/TOSC2
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Depending on the clock selection fuse settings, PB6 can be used as input to the inverting Oscillator
amplifier and input to the internal clock operating circuit.
Depending on the clock selection fuse settings, PB7 can be used as output from the inverting
Oscillator amplifier.
If the Internal Calibrated RC Oscillator is used as chip clock source, PB7..6 is used as TOSC2..1
input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.
The various special features of Port B are elaborated in “Alternate functions of port B” on page
78 and “System clock and clock options” on page 27.
1.1.4 Port C (PC5:0)
Port C is a 7-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
PC5..0 output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
1.1.5 PC6/RESET
If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that the electrical characteristics
of PC6 differ from those of the other pins of Port C.
If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low level on this pin
for longer than the minimum pulse length will generate a Reset, even if the clock is not running.
The minimum pulse length is given in Table 29-3 on page 307. Shorter pulses are not guaranteed
to generate a Reset.
The various special features of Port C are elaborated in “Alternate functions of port C” on page
81.
1.1.6 Port D (PD7:0)
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up4
2545T–AVR–05/11
ATmega48/88/168
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
The various special features of Port D are elaborated in “Alternate functions of port D” on page
84.
1.1.7 AVCC
AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally
connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC
through a low-pass filter. Note that PC6..4 use digital supply voltage, VCC.
1.1.8 AREF
AREF is the analog reference pin for the A/D Converter.
1.1.9 ADC7:6 (TQFP and QFN/MLF package only)
In the TQFP and QFN/MLF package, ADC7:6 serve as analog inputs to the A/D converter.
These pins are powered from the analog supply and serve as 10-bit ADC channels.5
2545T–AVR–05/11
ATmega48/88/168
2. Overview
The Atmel ATmega48/88/168 is a low-power CMOS 8-bit microcontroller based on the AVR
enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the
ATmega48/88/168 achieves throughputs approaching 1 MIPS per MHz allowing the system
designer to optimize power consumption versus processing speed.
2.1 Block diagram
Figure 2-1. Block diagram.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the
32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
PORT D (8) PORT B (8) PORT C (7)
USART 0
8bit T/C 2
8bit T/C 0 16bit T/C 1 A/D conv.
Internal
bandgap
Analog
comp.
SPI TWI
Flash SRAM
EEPROM
Watchdog
oscillator
Watchdog
timer
Oscillator
circuits /
clock
generation
Power
supervision
POR / BOD &
RESET
GND
VCC
PROGRAM
LOGIC
debugWIRE
2
GND
AREF
AVCC
DATABUS
PD[0..7] PB[0..7] PC[0..6] ADC[6..7]
6
RESET
XTAL[1..2]
CPU6
2545T–AVR–05/11
ATmega48/88/168
architecture is more code efficient while achieving throughputs up to ten times faster than conventional
CISC microcontrollers.
The Atmel ATmega48/88/168 provides the following features: 4K/8K/16K bytes of In-System
Programmable Flash with Read-While-Write capabilities, 256/512/512 bytes EEPROM,
512/1K/1K bytes SRAM, 23 general purpose I/O lines, 32 general purpose working registers,
three flexible Timer/Counters with compare modes, internal and external interrupts, a serial programmable
USART, a byte-oriented 2-wire Serial Interface, an SPI serial port, a 6-channel 10-bit
ADC (8 channels in TQFP and QFN/MLF packages), a programmable Watchdog Timer with
internal Oscillator, and five software selectable power saving modes. The Idle mode stops the
CPU while allowing the SRAM, Timer/Counters, USART, 2-wire Serial Interface, SPI port, and
interrupt system to continue functioning. The Power-down mode saves the register contents but
freezes the Oscillator, disabling all other chip functions until the next interrupt or hardware reset.
In Power-save mode, the asynchronous timer continues to run, allowing the user to maintain a
timer base while the rest of the device is sleeping. The ADC Noise Reduction mode stops the
CPU and all I/O modules except asynchronous timer and ADC, to minimize switching noise during
ADC conversions. In Standby mode, the crystal/resonator Oscillator is running while the rest
of the device is sleeping. This allows very fast start-up combined with low power consumption.
Atmel offers the QTouch Library for embedding capacitive touch buttons, sliders and wheels
functionality into AVR microcontrollers. The patented charge-transfer signal acquisition offers
robust sensing and includes fully debounced reporting of touch keys and includes Adjacent Key
Suppression® (AKS®) technology for unambigiuous detection of key events. The easy-to-use
QTouch Suite toolchain allows you to explore, develop and debug your own touch applications.
The device is manufactured using the Atmel high density non-volatile memory technology. The
On-chip ISP Flash allows the program memory to be reprogrammed In-System through an SPI
serial interface, by a conventional non-volatile memory programmer, or by an On-chip Boot program
running on the AVR core. The Boot program can use any interface to download the
application program in the Application Flash memory. Software in the Boot Flash section will
continue to run while the Application Flash section is updated, providing true Read-While-Write
operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a
monolithic chip, the Atmel ATmega48/88/168 is a powerful microcontroller that provides a highly
flexible and cost effective solution to many embedded control applications.
The ATmega48/88/168 AVR is supported with a full suite of program and system development
tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, In-Circuit Emulators,
and Evaluation kits.
2.2 Comparison between Atmel ATmega48, Atmel ATmega88, and Atmel ATmega168
The ATmega48, ATmega88 and ATmega168 differ only in memory sizes, boot loader support,
and interrupt vector sizes. Table 2-1 summarizes the different memory and interrupt vector sizes
for the three devices.
Table 2-1. Memory size summary.
Device Flash EEPROM RAM Interrupt vector size
ATmega48 4Kbytes 256Bytes 512Bytes 1 instruction word/vector
ATmega88 8Kbytes 512Bytes 1Kbytes 1 instruction word/vector
ATmega168 16Kbytes 512Bytes 1Kbytes 2 instruction words/vector7
2545T–AVR–05/11
ATmega48/88/168
ATmega88 and ATmega168 support a real Read-While-Write Self-Programming mechanism.
There is a separate Boot Loader Section, and the SPM instruction can only execute from there.
In ATmega48, there is no Read-While-Write support and no separate Boot Loader Section. The
SPM instruction can execute from the entire Flash.8
2545T–AVR–05/11
ATmega48/88/168
3. Resources
A comprehensive set of development tools, application notes and datasheets are available for
download on http://www.atmel.com/avr.
4. Data retention
Reliability Qualification results show that the projected data retention failure rate is much less
than 1 PPM over 20 years at 85°C or 100 years at 25°C.
5. About code examples
This documentation contains simple code examples that briefly show how to use various parts of
the device. These code examples assume that the part specific header file is included before
compilation. Be aware that not all C compiler vendors include bit definitions in the header files
and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation
for more details.
For I/O Registers located in extended I/O map, “IN”, “OUT”, “SBIS”, “SBIC”, “CBI”, and “SBI”
instructions must be replaced with instructions that allow access to extended I/O. Typically
“LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”.
6. Capacitive touch sensing
The Atmel QTouch Library provides a simple to use solution to realize touch sensitive interfaces
on most Atmel AVR microcontrollers. The QTouch Library includes support for the QTouch and
QMatrix acquisition methods.
Touch sensing can be added to any application by linking the appropriate Atmel QTouch Library
for the AVR Microcontroller. This is done by using a simple set of APIs to define the touch channels
and sensors, and then calling the touch sensing API’s to retrieve the channel information
and determine the touch sensor states.
The QTouch Library is FREE and downloadable from the Atmel website at the following location:
www.atmel.com/qtouchlibrary. For implementation details and other information, refer to the
Atmel QTouch Library User Guide - also available for download from the Atmel website.9
2545T–AVR–05/11
ATmega48/88/168
7. AVR CPU core
7.1 Overview
This section discusses the AVR core architecture in general. The main function of the CPU core
is to ensure correct program execution. The CPU must therefore be able to access memories,
perform calculations, control peripherals, and handle interrupts.
7.2 Architectural overview
Figure 7-1. Block diagram of the AVR architecture.
In order to maximize performance and parallelism, the AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction
is pre-fetched from the program memory. This concept enables instructions to be executed
in every clock cycle. The program memory is In-System Reprogrammable Flash memory.
Flash
program
memory
Instruction
register
Instruction
decoder
Program
counter
Control lines
32 x 8
general
purpose
registrers
ALU
Status
and control
I/O lines
EEPROM
Data bus 8-bit
Data
SRAM
Direct addressing
Indirect addressing
Interrupt
unit
SPI
unit
Watchdog
timer
Analog
comparator
I/O module 2
I/O module 1
I/O module n10
2545T–AVR–05/11
ATmega48/88/168
The fast-access Register File contains 32 × 8-bit general purpose working registers with a single
clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical
ALU operation, two operands are output from the Register File, the operation is executed,
and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data
Space addressing – enabling efficient address calculations. One of the these address pointers
can also be used as an address pointer for look up tables in Flash program memory. These
added function registers are the 16-bit X-register, Y-register, and Z-register, described later in
this section.
The ALU supports arithmetic and logic operations between registers or between a constant and
a register. Single register operations can also be executed in the ALU. After an arithmetic operation,
the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to
directly address the whole address space. Most AVR instructions have a single 16-bit word format.
Every program memory address contains a 16-bit or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the
Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack
size is only limited by the total SRAM size and the usage of the SRAM. All user programs must
initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack
Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed
through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its control registers in the I/O space with an additional Global
Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the
Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position.
The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers,
SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data
Space locations following those of the Register File, 0x20 - 0x5F. In addition, the
ATmega48/88/168 has Extended I/O space from 0x60 - 0xFF in SRAM where only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
7.3 ALU – Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose
working registers. Within a single clock cycle, arithmetic operations between general purpose
registers or between a register and an immediate are executed. The ALU operations are divided
into three main categories – arithmetic, logical, and bit-functions. Some implementations of the
architecture also provide a powerful multiplier supporting both signed/unsigned multiplication
and fractional format. See “Instruction set summary” on page 347 for a detailed description.11
2545T–AVR–05/11
ATmega48/88/168
7.4 Status register
The Status Register contains information about the result of the most recently executed arithmetic
instruction. This information can be used for altering program flow in order to perform
conditional operations. Note that the Status Register is updated after all ALU operations, as
specified in the Instruction Set Reference. This will in many cases remove the need for using the
dedicated compare instructions, resulting in faster and more compact code.
The Status Register is not automatically stored when entering an interrupt routine and restored
when returning from an interrupt. This must be handled by software.
7.4.1 SREG – AVR Status Register
The AVR Status Register – SREG – is defined as:
• Bit 7 – I: Global interrupt enable
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt
enable control is then performed in separate control registers. If the Global Interrupt Enable
Register is cleared, none of the interrupts are enabled independent of the individual interrupt
enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by
the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by
the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit copy storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination
for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.
• Bit 5 – H: Half carry flag
The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.
• Bit 4 – S: Sign bit, S = N ⊕ V
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.
• Bit 3 – V: Two’s complement overflow flag
The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.
• Bit 2 – N: Negative flag
The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.
• Bit 1 – Z: Zero flag
The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.
Bit 7 6 5 4 3 2 1 0
0x3F (0x5F) I T H S V N Z C SREG
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 012
2545T–AVR–05/11
ATmega48/88/168
• Bit 0 – C: Carry flag
The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.
7.5 General purpose register file
The register file is optimized for the AVR enhanced RISC instruction set. In order to achieve the
required performance and flexibility, the following input/output schemes are supported by the
register file:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 7-2 shows the structure of the 32 general purpose working registers in the CPU.
Figure 7-2. AVR CPU general purpose working registers.
Most of the instructions operating on the register file have direct access to all registers, and most
of them are single cycle instructions.
As shown in Figure 7-2, each register is also assigned a data memory address, mapping them
directly into the first 32 locations of the user Data Space. Although not being physically implemented
as SRAM locations, this memory organization provides great flexibility in access of the
registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file.
7 0 Addr.
R0 0x00
R1 0x01
R2 0x02
…
R13 0x0D
General R14 0x0E
purpose R15 0x0F
working R16 0x10
registers R17 0x11
…
R26 0x1A X-register low byte
R27 0x1B X-register high byte
R28 0x1C Y-register low byte
R29 0x1D Y-register high byte
R30 0x1E Z-register low byte
R31 0x1F Z-register high byte13
2545T–AVR–05/11
ATmega48/88/168
7.5.1 The X-register, Y-register, and Z-register
The registers R26..R31 have some added functions to their general purpose usage. These registers
are 16-bit address pointers for indirect addressing of the data space. The three indirect
address registers X, Y, and Z are defined as described in Figure 7-3.
Figure 7-3. The X-, Y-, and Z-registers.
In the different addressing modes these address registers have functions as fixed displacement,
automatic increment, and automatic decrement (see the instruction set reference for details).
7.6 Stack pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing
return addresses after interrupts and subroutine calls. The Stack Pointer Register always points
to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations
to lower memory locations. This implies that a Stack PUSH command decreases the Stack
Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt
Stacks are located. This Stack space in the data SRAM must be defined by the program before
any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to
point above 0x0100, preferably RAMEND. The Stack Pointer is decremented by one when data
is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the
return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is
incremented by one when data is popped from the Stack with the POP instruction, and it is incremented
by two when data is popped from the Stack with return from subroutine RET or return
from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of
bits actually used is implementation dependent. Note that the data space in some implementations
of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register
will not be present.
15 XH XL 0
X-register 7 07 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y-register 7 07 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z-register 70 7 0
R31 (0x1F) R30 (0x1E)14
2545T–AVR–05/11
ATmega48/88/168
7.6.1 SPH and SPL – Stack pointer high and stack pointer low register
7.7 Instruction execution timing
This section describes the general access timing concepts for instruction execution. The AVR
CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the
chip. No internal clock division is used.
Figure 7-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard
architecture and the fast-access Register File concept. This is the basic pipelining concept
to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost,
functions per clocks, and functions per power-unit.
Figure 7-4. The parallel instruction fetches and instruction executions.
Figure 7-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU
operation using two register operands is executed, and the result is stored back to the destination
register.
Figure 7-5. Single cycle ALU operation.
Bit 15 14 13 12 11 10 9 8
0x3E (0x5E) SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
0x3D (0x5D) SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial value RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND RAMEND
clk
1st instruction fetch
1st instruction execute
2nd instruction fetch
2nd instruction execute
3rd instruction fetch
3rd instruction execute
4th instruction fetch
T1 T2 T3 T4
CPU
Total execution time
Register operands fetch
ALU operation execute
Result write back
T1 T2 T3 T4
clkCPU15
2545T–AVR–05/11
ATmega48/88/168
7.8 Reset and interrupt handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset
Vector each have a separate program vector in the program memory space. All interrupts are
assigned individual enable bits which must be written logic one together with the Global Interrupt
Enable bit in the Status Register in order to enable the interrupt. Depending on the Program
Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12
are programmed. This feature improves software security. See the section “Memory programming”
on page 285 for details.
The lowest addresses in the program memory space are by default defined as the Reset and
Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 56. The list also
determines the priority levels of the different interrupts. The lower the address the higher is the
priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request
0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL
bit in the MCU Control Register (MCUCR). Refer to “Interrupts” on page 56 for more information.
The Reset Vector can also be moved to the start of the Boot Flash section by programming the
BOOTRST Fuse, see “Boot loader support – Read-while-write self-programming, Atmel
ATmega88 and Atmel ATmega168” on page 269.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled.
The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector
in order to execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s)
to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is
cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is
cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt
Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the
Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the
interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during the
timed EEPROM write sequence.16
2545T–AVR–05/11
ATmega48/88/168
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed
before any pending interrupts, as shown in this example.
7.8.1 Interrupt response time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum.
After four clock cycles the program vector address for the actual interrupt handling routine
is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack.
The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If
an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed
before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt
execution response time is increased by four clock cycles. This increase comes in addition to the
start-up time from the selected sleep mode.
A return from an interrupt handling routine takes four clock cycles. During these four clock
cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is
incremented by two, and the I-bit in SREG is set.
Assembly code example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMPE ; start EEPROM write
sbi EECR, EEPE
out SREG, r16 ; restore SREG value (I-bit)
C code example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1< xxx
... ... ... ...
22 0x015 ADC ADC conversion complete
23 0x016 EE READY EEPROM ready
24 0x017 ANALOG COMP Analog comparator
25 0x018 TWI 2-wire serial interface
26 0x019 SPM READY Store program memory ready
Table 12-1. Reset and interrupt vectors in ATmega48. (Continued)
Vector no. Program address Source Interrupt definition58
2545T–AVR–05/11
ATmega48/88/168
12.3 Interrupt vectors in Atmel ATmega88
Notes: 1. When the BOOTRST fuse is programmed, the device will jump to the boot loader address at
reset, see “Boot loader support – Read-while-write self-programming, Atmel ATmega88 and
Atmel ATmega168” on page 269.
2. When the IVSEL bit in MCUCR is set, interrupt vectors will be moved to the start of the boot
flash section. The address of each Interrupt Vector will then be the address in this table added
to the start address of the boot flash section.
Table 12-3 on page 59 shows reset and interrupt vectors placement for the various combinations
of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the
Interrupt Vectors are not used, and regular program code can be placed at these locations. This
is also the case if the reset vector is in the application section while the interrupt vectors are in
the boot section or vice versa.
Table 12-2. Reset and interrupt vectors in ATmega88.
Vector no.
Program
address(2) Source Interrupt definition
1 0x000(1) RESET External pin, power-on reset, brown-out reset and watchdog system reset
2 0x001 INT0 External interrupt request 0
3 0x002 INT1 External interrupt request 1
4 0x003 PCINT0 Pin change interrupt request 0
5 0x004 PCINT1 Pin change interrupt request 1
6 0x005 PCINT2 Pin change interrupt request 2
7 0x006 WDT Watchdog time-out interrupt
8 0x007 TIMER2 COMPA Timer/Counter2 compare match A
9 0x008 TIMER2 COMPB Timer/Counter2 compare match B
10 0x009 TIMER2 OVF Timer/Counter2 overflow
11 0x00A TIMER1 CAPT Timer/Counter1 capture event
12 0x00B TIMER1 COMPA Timer/Counter1 compare match A
13 0x00C TIMER1 COMPB Timer/Coutner1 compare match B
14 0x00D TIMER1 OVF Timer/Counter1 overflow
15 0x00E TIMER0 COMPA Timer/Counter0 compare match A
16 0x00F TIMER0 COMPB Timer/Counter0 compare match B
17 0x010 TIMER0 OVF Timer/Counter0 overflow
18 0x011 SPI, STC SPI serial transfer complete
19 0x012 USART, RX USART Rx complete
20 0x013 USART, UDRE USART, data register empty
21 0x014 USART, TX USART, Tx complete
22 0x015 ADC ADC conversion complete
23 0x016 EE READY EEPROM ready
24 0x017 ANALOG COMP Analog comparator
25 0x018 TWI 2-wire serial interface
26 0x019 SPM READY Store program memory ready59
2545T–AVR–05/11
ATmega48/88/168
Note: 1. The boot reset address is shown in Table 27-6 on page 281. For the BOOTRST Fuse “1”
means unprogrammed while “0” means programmed.
The most typical and general program setup for the reset and interrupt vector addresses in
ATmega88 is:
Address Labels Code Comments
0x000 rjmp RESET ; Reset Handler
0x001 rjmp EXT_INT0 ; IRQ0 Handler
0x002 rjmp EXT_INT1 ; IRQ1 Handler
0x003 rjmp PCINT0 ; PCINT0 Handler
0x004 rjmp PCINT1 ; PCINT1 Handler
0x005 rjmp PCINT2 ; PCINT2 Handler
0x006 rjmp WDT ; Watchdog Timer Handler
0x007 rjmp TIM2_COMPA ; Timer2 Compare A Handler
0X008 rjmp TIM2_COMPB ; Timer2 Compare B Handler
0x009 rjmp TIM2_OVF ; Timer2 Overflow Handler
0x00A rjmp TIM1_CAPT ; Timer1 Capture Handler
0x00B rjmp TIM1_COMPA ; Timer1 Compare A Handler
0x00C rjmp TIM1_COMPB ; Timer1 Compare B Handler
0x00D rjmp TIM1_OVF ; Timer1 Overflow Handler
0x00E rjmp TIM0_COMPA ; Timer0 Compare A Handler
0x00F rjmp TIM0_COMPB ; Timer0 Compare B Handler
0x010 rjmp TIM0_OVF ; Timer0 Overflow Handler
0x011 rjmp SPI_STC ; SPI Transfer Complete Handler
0x012 rjmp USART_RXC ; USART, RX Complete Handler
0x013 rjmp USART_UDRE ; USART, UDR Empty Handler
0x014 rjmp USART_TXC ; USART, TX Complete Handler
0x015 rjmp ADC ; ADC Conversion Complete Handler
0x016 rjmp EE_RDY ; EEPROM Ready Handler
0x017 rjmp ANA_COMP ; Analog Comparator Handler
0x018 rjmp TWI ; 2-wire Serial Interface Handler
0x019 rjmp SPM_RDY ; Store Program Memory Ready Handler
;
0x01ARESET: ldi r16, high(RAMEND); Main program start
0x01B out SPH,r16 ; Set Stack Pointer to top of RAM
0x01C ldi r16, low(RAMEND)
0x01D out SPL,r16
0x01E sei ; Enable interrupts
0x01F xxx
Table 12-3. Reset and interrupt vectors placement in Atmel ATmega88(1).
BOOTRST IVSEL Reset address Interrupt vectors start address
1 0 0x000 0x001
1 1 0x000 Boot reset address + 0x001
0 0 Boot reset address 0x001
0 1 Boot reset address Boot reset address + 0x00160
2545T–AVR–05/11
ATmega48/88/168
When the BOOTRST fuse is unprogrammed, the boot section size set to 2Kbytes and the IVSEL
bit in the MCUCR register is set before any interrupts are enabled, the most typical and general
program setup for the reset and interrupt vector addresses in Atmel ATmega88 is:
Address Labels Code Comments
0x000 RESET: ldi r16,high(RAMEND); Main program start
0x001 out SPH,r16 ; Set Stack Pointer to top of RAM
0x002 ldi r16,low(RAMEND)
0x003 out SPL,r16
0x004 sei ; Enable interrupts
0x005 xxx
;
.org 0xC01
0xC01 rjmp EXT_INT0 ; IRQ0 Handler
0xC02 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0xC19 rjmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST fuse is programmed and the boot section size set to 2Kbytes, the most
typical and general program setup for the reset and interrupt vector addresses in ATmega88 is:
Address Labels Code Comments
.org 0x001
0x001 rjmp EXT_INT0 ; IRQ0 Handler
0x002 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x019 rjmp SPM_RDY ; Store Program Memory Ready Handler
;
.org 0xC00
0xC00 RESET: ldi r16,high(RAMEND); Main program start
0xC01 out SPH,r16 ; Set Stack Pointer to top of RAM
0xC02 ldi r16,low(RAMEND)
0xC03 out SPL,r16
0xC04 sei ; Enable interrupts
0xC05 xxx
When the BOOTRST fuse is programmed, the boot section size set to 2Kbytes and the IVSEL
bit in the MCUCR register is set before any interrupts are enabled, the most typical and general
program setup for the reset and interrupt vector addresses in ATmega88 is:
Address Labels Code Comments
;
.org 0xC00
0xC00 rjmp RESET ; Reset handler
0xC01 rjmp EXT_INT0 ; IRQ0 Handler
0xC02 rjmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0xC19 rjmp SPM_RDY ; Store Program Memory Ready Handler
;
0xC1A RESET: ldi r16,high(RAMEND); Main program start
0xC1B out SPH,r16 ; Set Stack Pointer to top of RAM61
2545T–AVR–05/11
ATmega48/88/168
0xC1C ldi r16,low(RAMEND)
0xC1D out SPL,r16
0xC1E sei ; Enable interrupts
0xC1F xxx
12.4 Interrupt vectors in Atmel ATmega168
Notes: 1. When the BOOTRST fuse is programmed, the device will jump to the boot loader address at
reset, see “Boot loader support – Read-while-write self-programming, Atmel ATmega88 and
Atmel ATmega168” on page 269.
2. When the IVSEL bit in MCUCR is set, interrupt vectors will be moved to the start of the boot
flash section. The address of each Interrupt Vector will then be the address in this table added
to the start address of the boot flash section.
Table 12-4. Reset and interrupt vectors in ATmega168.
Vector no.
Program
address(2) Source Interrupt definition
1 0x0000(1) RESET External pin, power-on reset, brown-out reset and watchdog system reset
2 0x0002 INT0 External interrupt request 0
3 0x0004 INT1 External interrupt request 1
4 0x0006 PCINT0 Pin change interrupt request 0
5 0x0008 PCINT1 Pin change interrupt request 1
6 0x000A PCINT2 Pin change interrupt request 2
7 0x000C WDT Watchdog time-out interrupt
8 0x000E TIMER2 COMPA Timer/Counter2 compare match A
9 0x0010 TIMER2 COMPB Timer/Counter2 compare match B
10 0x0012 TIMER2 OVF Timer/Counter2 overflow
11 0x0014 TIMER1 CAPT Timer/Counter1 capture event
12 0x0016 TIMER1 COMPA Timer/Counter1 compare match A
13 0x0018 TIMER1 COMPB Timer/Coutner1 compare match B
14 0x001A TIMER1 OVF Timer/Counter1 overflow
15 0x001C TIMER0 COMPA Timer/Counter0 compare match A
16 0x001E TIMER0 COMPB Timer/Counter0 compare match B
17 0x0020 TIMER0 OVF Timer/Counter0 overflow
18 0x0022 SPI, STC SPI serial transfer complete
19 0x0024 USART, RX USART Rx complete
20 0x0026 USART, UDRE USART, data register empty
21 0x0028 USART, TX USART, Tx complete
22 0x002A ADC ADC conversion complete
23 0x002C EE READY EEPROM ready
24 0x002E ANALOG COMP Analog comparator
25 0x0030 TWI 2-wire serial interface
26 0x0032 SPM READY Store program memory ready62
2545T–AVR–05/11
ATmega48/88/168
Table 12-5 shows reset and interrupt vectors placement for the various combinations of
BOOTRST and IVSEL settings. If the program never enables an interrupt source, the interrupt
vectors are not used, and regular program code can be placed at these locations. This is also
the case if the reset vector is in the application section while the interrupt vectors are in the boot
section or vice versa.
Note: 1. The boot reset address is shown in Table 27-6 on page 281. For the BOOTRST fuse “1”
means unprogrammed while “0” means programmed.
The most typical and general program setup for the reset and interrupt vector addresses in
ATmega168 is:
Address Labels Code Comments
0x0000 jmp RESET ; Reset Handler
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x0004 jmp EXT_INT1 ; IRQ1 Handler
0x0006 jmp PCINT0 ; PCINT0 Handler
0x0008 jmp PCINT1 ; PCINT1 Handler
0x000A jmp PCINT2 ; PCINT2 Handler
0x000C jmp WDT ; Watchdog Timer Handler
0x000E jmp TIM2_COMPA ; Timer2 Compare A Handler
0x0010 jmp TIM2_COMPB ; Timer2 Compare B Handler
0x0012 jmp TIM2_OVF ; Timer2 Overflow Handler
0x0014 jmp TIM1_CAPT ; Timer1 Capture Handler
0x0016 jmp TIM1_COMPA ; Timer1 Compare A Handler
0x0018 jmp TIM1_COMPB ; Timer1 Compare B Handler
0x001A jmp TIM1_OVF ; Timer1 Overflow Handler
0x001C jmp TIM0_COMPA ; Timer0 Compare A Handler
0x001E jmp TIM0_COMPB ; Timer0 Compare B Handler
0x0020 jmp TIM0_OVF ; Timer0 Overflow Handler
0x0022 jmp SPI_STC ; SPI Transfer Complete Handler
0x0024 jmp USART_RXC ; USART, RX Complete Handler
0x0026 jmp USART_UDRE ; USART, UDR Empty Handler
0x0028 jmp USART_TXC ; USART, TX Complete Handler
0x002A jmp ADC ; ADC Conversion Complete Handler
0x002C jmp EE_RDY ; EEPROM Ready Handler
0x002E jmp ANA_COMP ; Analog Comparator Handler
0x0030 jmp TWI ; 2-wire Serial Interface Handler
0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x0033RESET: ldi r16, high(RAMEND); Main program start
Table 12-5. Reset and interrupt vectors placement in Atmel ATmega168(1).
BOOTRST IVSEL Reset address Interrupt vectors start address
1 0 0x000 0x001
1 1 0x000 Boot reset address + 0x0002
0 0 Boot reset address 0x001
0 1 Boot reset address Boot reset address + 0x000263
2545T–AVR–05/11
ATmega48/88/168
0x0034 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0035 ldi r16, low(RAMEND)
0x0036 out SPL,r16
0x0037 sei ; Enable interrupts
0x0038 xxx
... ... ... ...
When the BOOTRST fuse is unprogrammed, the boot section size set to 2Kbytes and the IVSEL
bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general
program setup for the reset and interrupt vector addresses in Atmel ATmega168 is:
Address Labels Code Comments
0x0000 RESET: ldi r16,high(RAMEND); Main program start
0x0001 out SPH,r16 ; Set Stack Pointer to top of RAM
0x0002 ldi r16,low(RAMEND)
0x0003 out SPL,r16
0x0004 sei ; Enable interrupts
0x0005 xxx
;
.org 0xC02
0x1C02 jmp EXT_INT0 ; IRQ0 Handler
0x1C04 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x1C32 jmp SPM_RDY ; Store Program Memory Ready Handler
When the BOOTRST fuse is programmed and the boot section size set to 2Kbytes, the most
typical and general program setup for the reset and interrupt vector addresses in ATmega168 is:
Address Labels Code Comments
.org 0x0002
0x0002 jmp EXT_INT0 ; IRQ0 Handler
0x0004 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler
;
.org 0x1C00
0x1C00 RESET: ldi r16,high(RAMEND); Main program start
0x1C01 out SPH,r16 ; Set Stack Pointer to top of RAM
0x1C02 ldi r16,low(RAMEND)
0x1C03 out SPL,r16
0x1C04 sei ; Enable interrupts
0x1C05 xxx
When the BOOTRST fuse is programmed, the boot section size set to 2Kbytes and the IVSEL
bit in the MCUCR register is set before any interrupts are enabled, the most typical and general
program setup for the reset and interrupt vector addresses in ATmega168 is:64
2545T–AVR–05/11
ATmega48/88/168
Address Labels Code Comments
;
.org 0x1C00
0x1C00 jmp RESET ; Reset handler
0x1C02 jmp EXT_INT0 ; IRQ0 Handler
0x1C04 jmp EXT_INT1 ; IRQ1 Handler
... ... ... ;
0x1C32 jmp SPM_RDY ; Store Program Memory Ready Handler
;
0x1C33 RESET: ldi r16,high(RAMEND); Main program start
0x1C34 out SPH,r16 ; Set Stack Pointer to top of RAM
0x1C35 ldi r16,low(RAMEND)
0x1C36 out SPL,r16
0x1C37 sei ; Enable interrupts
0x1C38 xxx
12.4.1 Moving interrupts between application and boot space, Atmel ATmega88 and Atmel ATmega168
The MCU control register controls the placement of the interrupt vector table.
12.5 Register description
12.5.1 MCUCR – MCU control register
• Bit 1 – IVSEL: Interrupt vector select
When the IVSEL bit is cleared (zero), the interrupt vectors are placed at the start of the flash
memory. When this bit is set (one), the interrupt vectors are moved to the beginning of the boot
loader section of the flash. The actual address of the start of the boot flash section is determined
by the BOOTSZ fuses. Refer to the section “Boot loader support – Read-while-write self-programming,
Atmel ATmega88 and Atmel ATmega168” on page 269 for details. To avoid
unintentional changes of interrupt vector tables, a special write procedure must be followed to
change the IVSEL bit:
a. Write the interrupt vector change enable (IVCE) bit to one.
b. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled
in the cycle IVCE is set, and they remain disabled until after the instruction following the write to
IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the status
register is unaffected by the automatic disabling.
Note: If interrupt vectors are placed in the boot loader section and boot lock bit BLB02 is programmed,
interrupts are disabled while executing from the Application section. If interrupt vectors are placed
in the Application section and boot lock bit BLB12 is programmed, interrupts are disabled while
executing from the Boot Loader section. Refer to the section “Boot loader support – Read-whilewrite
self-programming, Atmel ATmega88 and Atmel ATmega168” on page 269 for details on
Boot Lock bits.
This bit is not available in Atmel ATmega48.
Bit 7 6 5 4 3 2 1 0
0x35 (0x55) – – – PUD – – IVSEL IVCE MCUCR
Read/write R R R R/W R R R/W R/W
Initial value 0 0 0 0 0 0 0 065
2545T–AVR–05/11
ATmega48/88/168
• Bit 0 – IVCE: Interrupt vector change enable
The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by
hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable
interrupts, as explained in the IVSEL description above. See code example below.
This bit is not available in Atmel ATmega48.
Assembly code example
Move_interrupts:
; Get MCUCR
in r16, MCUCR
mov r17, r16
; Enable change of Interrupt Vectors
ori r16, (1< CSn2:0 > 1). The number of system clock
cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system
clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024).
It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution.
However, care must be taken if the other Timer/Counter that shares the same prescaler
also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is
connected to.
17.0.3 External clock source
An external clock source applied to the T1/T0 pin can be used as Timer/Counter clock
(clkT1/clkT0). The T1/T0 pin is sampled once every system clock cycle by the pin synchronization
logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 17-1
shows a functional equivalent block diagram of the T1/T0 synchronization and edge detector
logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch
is transparent in the high period of the internal system clock.
The edge detector generates one clkT1/clkT0 pulse for each positive (CSn2:0 = 7) or negative
(CSn2:0 = 6) edge it detects.
Figure 17-1. T1/T0 pin sampling.
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles
from an edge has been applied to the T1/T0 pin to the counter is updated.
Tn_sync
(to clock
select logic)
Synchronization Edge detector
D Q D Q
LE
Tn D Q
clkI/O138
2545T–AVR–05/11
ATmega48/88/168
Enabling and disabling of the clock input must be done when T1/T0 has been stable for at least
one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated.
Each half period of the external clock applied must be longer than one system clock cycle to
ensure correct sampling. The external clock must be guaranteed to have less than half the system
clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses
sampling, the maximum frequency of an external clock it can detect is half the sampling frequency
(Nyquist sampling theorem). However, due to variation of the system clock frequency
and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is
recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5.
An external clock source can not be prescaled.
Figure 17-2. Prescaler for timer/counter0 and timer/counter1(1).
Note: 1. The synchronization logic on the input pins (T1/T0) is shown in Figure 17-1 on page 137.
PSRSYNC
Clear
clkT1 clkT0
T1
T0
clkI/O
Synchronization
Synchronization139
2545T–AVR–05/11
ATmega48/88/168
17.1 Register description
17.1.1 GTCCR – General timer/counter control register
• Bit 7 – TSM: Timer/counter synchronization mode
Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the
value that is written to the PSRASY and PSRSYNC bits is kept, hence keeping the corresponding
prescaler reset signals asserted. This ensures that the corresponding Timer/Counters are
halted and can be configured to the same value without the risk of one of them advancing during
configuration. When the TSM bit is written to zero, the PSRASY and PSRSYNC bits are cleared
by hardware, and the Timer/Counters start counting simultaneously.
• Bit 0 – PSRSYNC: Prescaler reset
When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally
cleared immediately by hardware, except if the TSM bit is set. Note that Timer/Counter1
and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both
timers.
Bit 7 6 5 4 3 2 1 0
0x23 (0x43) TSM – – – – – PSRASY PSRSYNC GTCCR
Read/write R/W R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0140
2545T–AVR–05/11
ATmega48/88/168
18. 8-bit Timer/Counter2 with PWM and asynchronous operation
18.1 Features • Single channel counter
• Clear timer on compare match (auto reload)
• Glitch-free, phase correct pulse width modulator (PWM)
• Frequency generator
• 10-bit clock prescaler
• Overflow and compare match interrupt sources (TOV2, OCF2A and OCF2B)
• Allows clocking from external 32kHz watch crystal independent of the I/O clock
18.2 Overview
Timer/Counter2 is a general purpose, single channel, 8-bit Timer/Counter module. A simplified
block diagram of the 8-bit Timer/Counter is shown in Figure 18-1. For the actual placement of
I/O pins, refer to “Pinout Atmel ATmega48/88/168.” on page 2. CPU accessible I/O Registers,
including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations
are listed in the “Register description” on page 153.
The PRTIM2 bit in “Minimizing power consumption” on page 41 must be written to zero to enable
Timer/Counter2 module.
Figure 18-1. 8-bit timer/counter block diagram.
Clock select
Timer/counter
DATA BUS
OCRnA
OCRnB
=
=
TCNTn
Waveform
generation
Waveform
generation
OCnA
OCnB
=
Fixed
TOP
value
Control logic
= 0
TOP BOTTOM
Count
Clear
Direction
TOVn
(Int.req.)
OCnA
(Int.req.)
OCnB
(Int.req.)
TCCRnA TCCRnB
Tn Edge
detector
(From prescaler)
clkTn141
2545T–AVR–05/11
ATmega48/88/168
18.2.1 Registers
The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit registers.
Interrupt request (shorten as Int.Req.) signals are all visible in the Timer Interrupt Flag
Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register
(TIMSK2). TIFR2 and TIMSK2 are not shown in the figure.
The Timer/Counter can be clocked internally, via the prescaler, or asynchronously clocked from
the TOSC1/2 pins, as detailed later in this section. The asynchronous operation is controlled by
the Asynchronous Status Register (ASSR). The Clock Select logic block controls which clock
source he Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive
when no clock source is selected. The output from the Clock Select logic is referred to as the
timer clock (clkT2).
The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the
Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator
to generate a PWM or variable frequency output on the Output Compare pins (OC2A and
OC2B). See “Output compare unit” on page 142. for details. The compare match event will also
set the Compare Flag (OCF2A or OCF2B) which can be used to generate an Output Compare
interrupt request.
18.2.2 Definitions
Many register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 2. However, when using the register or bit
defines in a program, the precise form must be used, that is, TCNT2 for accessing
Timer/Counter2 counter value and so on.
The definitions in Table 18-1 are also used extensively throughout the section.
18.3 Timer/counter clock sources
The Timer/Counter can be clocked by an internal synchronous or an external asynchronous
clock source. The clock source clkT2 is by default equal to the MCU clock, clkI/O. When the AS2
bit in the ASSR Register is written to logic one, the clock source is taken from the Timer/Counter
Oscillator connected to TOSC1 and TOSC2. For details on asynchronous operation, see “ASSR
– Asynchronous status register” on page 159. For details on clock sources and prescaler, see
“Timer/counter prescaler” on page 152.
18.4 Counter unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure
18-2 on page 142 shows a block diagram of the counter and its surrounding environment.
Table 18-1. Definitions.
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00).
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be the fixed value 0xFF
(MAX) or the value stored in the OCR2A Register. The assignment is dependent
on the mode of operation.142
2545T–AVR–05/11
ATmega48/88/168
Figure 18-2. Counter unit block diagram.
Signal description (internal signals):
count Increment or decrement TCNT2 by 1.
direction Selects between increment and decrement.
clear Clear TCNT2 (set all bits to zero).
clkTn Timer/Counter clock, referred to as clkT2 in the following.
top Signalizes that TCNT2 has reached maximum value.
bottom Signalizes that TCNT2 has reached minimum value (zero).
Depending on the mode of operation used, the counter is cleared, incremented, or decremented
at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source,
selected by the Clock Select bits (CS22:0). When no clock source is selected (CS22:0 = 0) the
timer is stopped. However, the TCNT2 value can be accessed by the CPU, regardless of
whether clkT2 is present or not. A CPU write overrides (has priority over) all counter clear or
count operations.
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in
the Timer/Counter Control Register (TCCR2A) and the WGM22 located in the Timer/Counter
Control Register B (TCCR2B). There are close connections between how the counter behaves
(counts) and how waveforms are generated on the Output Compare outputs OC2A and OC2B.
For more details about advanced counting sequences and waveform generation, see “Modes of
operation” on page 145.
The Timer/Counter Overflow Flag (TOV2) is set according to the mode of operation selected by
the WGM22:0 bits. TOV2 can be used for generating a CPU interrupt.
18.5 Output compare unit
The 8-bit comparator continuously compares TCNT2 with the Output Compare Register
(OCR2A and OCR2B). Whenever TCNT2 equals OCR2A or OCR2B, the comparator signals a
match. A match will set the Output Compare Flag (OCF2A or OCF2B) at the next timer clock
cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output
Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed.
Alternatively, the Output Compare Flag can be cleared by software by writing a logical
one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
according to operating mode set by the WGM22:0 bits and Compare Output mode (COM2x1:0)
bits. The max and bottom signals are used by the Waveform Generator for handling the special
cases of the extreme values in some modes of operation (“Modes of operation” on page 145).
Figure 18-3 on page 143 shows a block diagram of the Output Compare unit.
DATA BUS
TCNTn Control logic
count
TOVn
(Int.req.)
bottom top
direction
clear
TOSC1
T/C
oscillator
TOSC2
Prescaler
clkI/O
clk Tn143
2545T–AVR–05/11
ATmega48/88/168
Figure 18-3. Output compare unit, block diagram.
The OCR2x Register is double buffered when using any of the Pulse Width Modulation (PWM)
modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double
buffering is disabled. The double buffering synchronizes the update of the OCR2x Compare
Register to either top or bottom of the counting sequence. The synchronization prevents the
occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.
The OCR2x Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR2x Buffer Register, and if double buffering is disabled
the CPU will access the OCR2x directly.
18.5.1 Force output compare
In non-PWM waveform generation modes, the match output of the comparator can be forced by
writing a one to the Force Output Compare (FOC2x) bit. Forcing compare match will not set the
OCF2x Flag or reload/clear the timer, but the OC2x pin will be updated as if a real compare
match had occurred (the COM2x1:0 bits settings define whether the OC2x pin is set, cleared or
toggled).
18.5.2 Compare match blocking by TCNT2 write
All CPU write operations to the TCNT2 Register will block any compare match that occurs in the
next timer clock cycle, even when the timer is stopped. This feature allows OCR2x to be initialized
to the same value as TCNT2 without triggering an interrupt when the Timer/Counter clock is
enabled.
18.5.3 Using the output compare unit
Since writing TCNT2 in any mode of operation will block all compare matches for one timer clock
cycle, there are risks involved when changing TCNT2 when using the Output Compare channel,
independently of whether the Timer/Counter is running or not. If the value written to TCNT2
equals the OCR2x value, the compare match will be missed, resulting in incorrect waveform
generation. Similarly, do not write the TCNT2 value equal to BOTTOM when the counter is
downcounting.
OCFnx (int.req.)
= (8-bit comparator)
OCRnx
OCnx
DATA BUS
TCNTn
WGMn1:0
Waveform generator
top
FOCn
COMnX1:0
bottom144
2545T–AVR–05/11
ATmega48/88/168
The setup of the OC2x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC2x value is to use the Force Output Compare
(FOC2x) strobe bit in Normal mode. The OC2x Register keeps its value even when
changing between Waveform Generation modes.
Be aware that the COM2x1:0 bits are not double buffered together with the compare value.
Changing the COM2x1:0 bits will take effect immediately.
18.6 Compare match output unit
The Compare Output mode (COM2x1:0) bits have two functions. The Waveform Generator uses
the COM2x1:0 bits for defining the Output Compare (OC2x) state at the next compare match.
Also, the COM2x1:0 bits control the OC2x pin output source. Figure 18-4 shows a simplified
schematic of the logic affected by the COM2x1:0 bit setting. The I/O Registers, I/O bits, and I/O
pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers
(DDR and PORT) that are affected by the COM2x1:0 bits are shown. When referring to the
OC2x state, the reference is for the internal OC2x Register, not the OC2x pin.
Figure 18-4. Compare match output unit, schematic.
The general I/O port function is overridden by the Output Compare (OC2x) from the Waveform
Generator if either of the COM2x1:0 bits are set. However, the OC2x pin direction (input or output)
is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
Register bit for the OC2x pin (DDR_OC2x) must be set as output before the OC2x value is visible
on the pin. The port override function is independent of the Waveform Generation mode.
The design of the Output Compare pin logic allows initialization of the OC2x state before the output
is enabled. Note that some COM2x1:0 bit settings are reserved for certain modes of
operation. See “Register description” on page 153.
PORT
DDR
D Q
D Q
OCnx
OCnx pin
D Q Waveform
generator
COMnx1
COMnx0
0
1
DATA BUS
FOCnx
clkI/O145
2545T–AVR–05/11
ATmega48/88/168
18.6.1 Compare output mode and waveform generation
The Waveform Generator uses the COM2x1:0 bits differently in normal, CTC, and PWM modes.
For all modes, setting the COM2x1:0 = 0 tells the Waveform Generator that no action on the
OC2x Register is to be performed on the next compare match. For compare output actions in the
non-PWM modes refer to Table 18-5 on page 154. For fast PWM mode, refer to Table 18-6 on
page 155, and for phase correct PWM refer to Table 18-7 on page 155.
A change of the COM2x1:0 bits state will have effect at the first compare match after the bits are
written. For non-PWM modes, the action can be forced to have immediate effect by using the
FOC2x strobe bits.
18.7 Modes of operation
The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins,
is defined by the combination of the Waveform Generation mode (WGM22:0) and Compare Output
mode (COM2x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM2x1:0 bits control whether the PWM output
generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM2x1:0 bits control whether the output should be set, cleared, or toggled at a compare
match (See “Compare match output unit” on page 144.).
For detailed timing information refer to “Timer/counter timing diagrams” on page 149.
18.7.1 Normal mode
The simplest mode of operation is the Normal mode (WGM22:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV2) will be set in the same
timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV2 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the Normal mode, a new counter value can be written
anytime.
The Output Compare unit can be used to generate interrupts at some given time. Using the Output
Compare to generate waveforms in Normal mode is not recommended, since this will
occupy too much of the CPU time.
18.7.2 Clear timer on compare match (CTC) mode
In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to
manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter
value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence
also its resolution. This mode allows greater control of the compare match output frequency. It
also simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 18-5 on page 146. The counter value
(TCNT2) increases until a compare match occurs between TCNT2 and OCR2A, and then counter
(TCNT2) is cleared.146
2545T–AVR–05/11
ATmega48/88/168
Figure 18-5. CTC mode, timing diagram.
An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF2A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating
the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running
with none or a low prescaler value must be done with care since the CTC mode does not
have the double buffering feature. If the new value written to OCR2A is lower than the current
value of TCNT2, the counter will miss the compare match. The counter will then have to count to
its maximum value (0xFF) and wrap around starting at 0x00 before the compare match can
occur.
For generating a waveform output in CTC mode, the OC2A output can be set to toggle its logical
level on each compare match by setting the Compare Output mode bits to toggle mode
(COM2A1:0 = 1). The OC2A value will not be visible on the port pin unless the data direction for
the pin is set to output. The waveform generated will have a maximum frequency of fOC2A =
fclk_I/O/2 when OCR2A is set to zero (0x00). The waveform frequency is defined by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
As for the normal mode of operation, the TOV2 Flag is set in the same timer clock cycle that the
counter counts from MAX to 0x00.
18.7.3 Fast PWM mode
The fast Pulse Width Modulation or fast PWM mode (WGM22:0 = 3 or 7) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by
its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM.
TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7. In noninverting
Compare Output mode, the Output Compare (OC2x) is cleared on the compare match
between TCNT2 and OCR2x, and set at BOTTOM. In inverting Compare Output mode, the output
is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that uses dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
TCNTn
OCnx
(toggle)
OCnx interrupt flag set
Period 1 2 3 4
(COMnx1:0 = 1)
f
OCnx
f
clk_I/O
2 ⋅ ⋅ N ( ) 1 + OCRnx = -------------------------------------------------147
2545T–AVR–05/11
ATmega48/88/168
In fast PWM mode, the counter is incremented until the counter value matches the TOP value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
PWM mode is shown in Figure 18-6. The TCNT2 value is in the timing diagram shown as a histogram
for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT2 slopes represent compare
matches between OCR2x and TCNT2.
Figure 18-6. Fast PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches TOP. If the interrupt
is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC2x pin.
Setting the COM2x1:0 bits to two will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when WGM2:0 = 3,
and OCR2A when MGM2:0 = 7. (See Table 18-3 on page 154). The actual OC2x value will only
be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform
is generated by setting (or clearing) the OC2x Register at the compare match between
OCR2x and TCNT2, and clearing (or setting) the OC2x Register at the timer clock cycle the
counter is cleared (changes from TOP to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR2A is set equal to BOTTOM, the output will
be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR2A equal to MAX will result
in a constantly high or low output (depending on the polarity of the output set by the COM2A1:0
bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting
OC2x to toggle its logical level on each compare match (COM2x1:0 = 1). The waveform
TCNTn
OCRnx update and
TOVn interrupt flag set
Period 1 2 3
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx interrupt flag set
4 5 6 7
f
OCnxPWM
f
clk_I/O
N ⋅ 256 = ------------------148
2545T–AVR–05/11
ATmega48/88/168
generated will have a maximum frequency of foc2 = fclk_I/O/2 when OCR2A is set to zero. This feature
is similar to the OC2A toggle in CTC mode, except the double buffer feature of the Output
Compare unit is enabled in the fast PWM mode.
18.7.4 Phase correct PWM mode
The phase correct PWM mode (WGM22:0 = 1 or 5) provides a high resolution phase correct
PWM waveform generation option. The phase correct PWM mode is based on a dual-slope
operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM.
TOP is defined as 0xFF when WGM2:0 = 3, and OCR2A when MGM2:0 = 7. In noninverting
Compare Output mode, the Output Compare (OC2x) is cleared on the compare match
between TCNT2 and OCR2x while upcounting, and set on the compare match while downcounting.
In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmetric
feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
In phase correct PWM mode the counter is incremented until the counter value matches TOP.
When the counter reaches TOP, it changes the count direction. The TCNT2 value will be equal
to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown
on Figure 18-7. The TCNT2 value is in the timing diagram shown as a histogram for illustrating
the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The
small horizontal line marks on the TCNT2 slopes represent compare matches between OCR2x
and TCNT2.
Figure 18-7. Phase correct PWM mode, timing diagram.
The Timer/Counter Overflow Flag (TOV2) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC2x pin. Setting the COM2x1:0 bits to two will produce a non-inverted PWM. An inverted PWM
TOVn interrupt flag set
OCnx interrupt flag set
1 2 3
TCNTn
Period
OCnx
OCnx
(COMnx1:0 = 2)
(COMnx1:0 = 3)
OCRnx update149
2545T–AVR–05/11
ATmega48/88/168
output can be generated by setting the COM2x1:0 to three. TOP is defined as 0xFF when
WGM2:0 = 3, and OCR2A when MGM2:0 = 7 (See Table 18-4 on page 154). The actual OC2x
value will only be visible on the port pin if the data direction for the port pin is set as output. The
PWM waveform is generated by clearing (or setting) the OC2x Register at the compare match
between OCR2x and TCNT2 when the counter increments, and setting (or clearing) the OC2x
Register at compare match between OCR2x and TCNT2 when the counter decrements. The
PWM frequency for the output when using phase correct PWM can be calculated by the following
equation:
The N variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024).
The extreme values for the OCR2A Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR2A is set equal to BOTTOM, the
output will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of period 2 in Figure 18-7 on page 148 OCnx has a transition from high to low
even though there is no Compare Match. The point of this transition is to guarantee symmetry
around BOTTOM. There are two cases that give a transition without Compare Match.
• OCR2A changes its value from MAX, like in Figure 18-7 on page 148. When the OCR2A value
is MAX the OCn pin value is the same as the result of a down-counting compare match. To
ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result of an
up-counting Compare Match
• The timer starts counting from a value higher than the one in OCR2A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the way
up
18.8 Timer/counter timing diagrams
The following figures show the Timer/Counter in synchronous mode, and the timer clock (clkT2)
is therefore shown as a clock enable signal. In asynchronous mode, clkI/O should be replaced by
the Timer/Counter Oscillator clock. The figures include information on when Interrupt Flags are
set. Figure 18-8 contains timing data for basic Timer/Counter operation. The figure shows the
count sequence close to the MAX value in all modes other than phase correct PWM mode.
Figure 18-8. Timer/counter timing diagram, no prescaling.
Figure 18-9 on page 150 shows the same timing data, but with the prescaler enabled.
f
OCnxPCPWM
f
clk_I/O
N ⋅ 510 = ------------------
clkTn
(clkI/O/1)
TOVn
clkI/O
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1150
2545T–AVR–05/11
ATmega48/88/168
Figure 18-9. Timer/counter timing diagram, with prescaler (fclk_I/O/8).
Figure 18-10 shows the setting of OCF2A in all modes except CTC mode.
Figure 18-10. Timer/counter timing diagram, setting of OCF2A, with prescaler (fclk_I/O/8).
Figure 18-11 shows the setting of OCF2A and the clearing of TCNT2 in CTC mode.
Figure 18-11. Timer/counter timing diagram, clear timer on compare match mode, with prescaler
(fclk_I/O/8).
TOVn
TCNTn MAX - 1 MAX BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
OCRnx value
OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2
clkI/O
clkTn
(clkI/O/8)
OCFnx
OCRnx
TCNTn
(CTC)
TOP
TOP - 1 TOP BOTTOM BOTTOM + 1
clkI/O
clkTn
(clkI/O/8)151
2545T–AVR–05/11
ATmega48/88/168
18.9 Asynchronous operation of Timer/Counter2
When Timer/Counter2 operates asynchronously, some considerations must be taken.
• Warning: When switching between asynchronous and synchronous clocking of
Timer/Counter2, the Timer Registers TCNT2, OCR2x, and TCCR2x might be corrupted. A safe
procedure for switching clock source is:
a. Disable the Timer/Counter2 interrupts by clearing OCIE2x and TOIE2.
b. Select clock source by setting AS2 as appropriate.
c. Write new values to TCNT2, OCR2x, and TCCR2x.
d. To switch to asynchronous operation: Wait for TCN2xUB, OCR2xUB, and TCR2xUB.
e. Clear the Timer/Counter2 Interrupt Flags.
f. Enable interrupts, if needed.
• The CPU main clock frequency must be more than four times the Oscillator frequency
• When writing to one of the registers TCNT2, OCR2x, or TCCR2x, the value is transferred to a
temporary register, and latched after two positive edges on TOSC1. The user should not write
a new value before the contents of the temporary register have been transferred to its
destination. Each of the five mentioned registers have their individual temporary register, which
means that, for example, writing to TCNT2 does not disturb an OCR2x write in progress. To
detect that a transfer to the destination register has taken place, the Asynchronous Status
Register – ASSR has been implemented
• When entering Power-save or ADC Noise Reduction mode after having written to TCNT2,
OCR2x, or TCCR2x, the user must wait until the written register has been updated if
Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode
before the changes are effective. This is particularly important if any of the Output Compare2
interrupt is used to wake up the device, since the Output Compare function is disabled during
writing to OCR2x or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode
before the corresponding OCR2xUB bit returns to zero, the device will never receive a
compare match interrupt, and the MCU will not wake up
• If Timer/Counter2 is used to wake the device up from Power-save or ADC Noise Reduction
mode, precautions must be taken if the user wants to re-enter one of these modes: If reentering
sleep mode within the TOSC1 cycle, the interrupt will immidiately occur and the
device wake up again. The result is multiple interrupts and wake-ups within one TOSC1 cycle
from the first interrupt. If the user is in doubt whether the time before re-entering Power-save or
ADC Noise Reduction mode is sufficient, the following algorithm can be used to ensure that
one TOSC1 cycle has elapsed:
a. Write a value to TCCR2x, TCNT2, or OCR2x.
b. Wait until the corresponding Update Busy Flag in ASSR returns to zero.
c. Enter Power-save or ADC Noise Reduction mode.
• When the asynchronous operation is selected, the 32.768kHz Oscillator for Timer/Counter2 is
always running, except in Power-down and Standby modes. After a Power-up Reset or wakeup
from Power-down or Standby mode, the user should be aware of the fact that this Oscillator
might take as long as one second to stabilize. The user is advised to wait for at least one
second before using Timer/Counter2 after power-up or wake-up from Power-down or Standby
mode. The contents of all Timer/Counter2 Registers must be considered lost after a wake-up
from Power-down or Standby mode due to unstable clock signal upon start-up, no matter
whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin152
2545T–AVR–05/11
ATmega48/88/168
• Description of wake up from Power-save or ADC Noise Reduction mode when the timer is
clocked asynchronously: When the interrupt condition is met, the wake up process is started
on the following cycle of the timer clock, that is, the timer is always advanced by at least one
before the processor can read the counter value. After wake-up, the MCU is halted for four
cycles, it executes the interrupt routine, and resumes execution from the instruction following
SLEEP
• Reading of the TCNT2 Register shortly after wake-up from Power-save may give an incorrect
result. Since TCNT2 is clocked on the asynchronous TOSC clock, reading TCNT2 must be
done through a register synchronized to the internal I/O clock domain. Synchronization takes
place for every rising TOSC1 edge. When waking up from Power-save mode, and the I/O clock
(clkI/O) again becomes active, TCNT2 will read as the previous value (before entering sleep)
until the next rising TOSC1 edge. The phase of the TOSC clock after waking up from Powersave
mode is essentially unpredictable, as it depends on the wake-up time. The recommended
procedure for reading TCNT2 is thus as follows:
a. Write any value to either of the registers OCR2x or TCCR2x.
b. Wait for the corresponding Update Busy Flag to be cleared.
c. Read TCNT2.
During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous
timer takes 3 processor cycles plus one timer cycle. The timer is therefore advanced by at least
one before the processor can read the timer value causing the setting of the Interrupt Flag. The
Output Compare pin is changed on the timer clock and is not synchronized to the processor
clock.
18.10 Timer/counter prescaler
Figure 18-12. Prescaler for Timer/Counter2.
10-BIT T/C PRESCALER
TIMER/COUNTER2 CLOCK SOURCE
clkI/O clkT2S
TOSC1
AS2
CS20
CS21
CS22
clkT2S/8
clkT2S/64
clkT2S/128
clkT2S/1024
clkT2S/256
clkT2S/32
PSRASY 0
Clear
clkT2153
2545T–AVR–05/11
ATmega48/88/168
The clock source for Timer/Counter2 is named clkT2S. clkT2S is by default connected to the main
system I/O clock clkIO. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously
clocked from the TOSC1 pin. This enables use of Timer/Counter2 as a Real Time Counter
(RTC). When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port C. A crystal can
then be connected between the TOSC1 and TOSC2 pins to serve as an independent clock
source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal.
For Timer/Counter2, the possible prescaled selections are: clkT2S/8, clkT2S/32, clkT2S/64,
clkT2S/128, clkT2S/256, and clkT2S/1024. Additionally, clkT2S as well as 0 (stop) may be selected.
Setting the PSRASY bit in GTCCR resets the prescaler. This allows the user to operate with a
predictable prescaler.
18.11 Register description
18.11.1 TCCR2A – Timer/counter control register A
• Bits 7:6 – COM2A1:0: Compare match output A mode
These bits control the Output Compare pin (OC2A) behavior. If one or both of the COM2A1:0
bits are set, the OC2A output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2A pin
must be set in order to enable the output driver.
When OC2A is connected to the pin, the function of the COM2A1:0 bits depends on the
WGM22:0 bit setting. Table 18-2 shows the COM2A1:0 bit functionality when the WGM22:0 bits
are set to a normal or CTC mode (non-PWM).
Table 18-3 on page 154 shows the COM2A1:0 bit functionality when the WGM21:0 bits are set
to fast PWM mode.
Bit 7 6 5 4 3 2 1 0
(0xB0) COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 TCCR2A
Read/write R/W R/W R/W R/W R R R/W R/W
Initial value 0 0 0 0 0 0 0 0
Table 18-2. Compare output mode, non-PWM mode.
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 Toggle OC2A on compare match
1 0 Clear OC2A on compare match
1 1 Set OC2A on compare match154
2545T–AVR–05/11
ATmega48/88/168
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Fast PWM mode” on page 146
for more details.
Table 18-4 shows the COM2A1:0 bit functionality when the WGM22:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2A equals TOP and COM2A1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 148 for more details.
• Bits 5:4 – COM2B1:0: Compare match output B mode
These bits control the Output Compare pin (OC2B) behavior. If one or both of the COM2B1:0
bits are set, the OC2B output overrides the normal port functionality of the I/O pin it is connected
to. However, note that the Data Direction Register (DDR) bit corresponding to the OC2B pin
must be set in order to enable the output driver.
When OC2B is connected to the pin, the function of the COM2B1:0 bits depends on the
WGM22:0 bit setting. Table 18-5 shows the COM2B1:0 bit functionality when the WGM22:0 bits
are set to a normal or CTC mode (non-PWM).
Table 18-3. Compare output mode, fast PWM mode(1).
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 WGM22 = 0: Normal port operation, OC0A disconnected
WGM22 = 1: Toggle OC2A on compare match
1 0 Clear OC2A on compare match, set OC2A at BOTTOM,
(non-inverting mode)
1 1 Set OC2A on compare match, clear OC2A at BOTTOM,
(inverting mode)
Table 18-4. Compare output mode, phase correct PWM Mode(1).
COM2A1 COM2A0 Description
0 0 Normal port operation, OC2A disconnected
0 1 WGM22 = 0: Normal port operation, OC2A disconnected
WGM22 = 1: Toggle OC2A on compare match
1 0 Clear OC2A on compare match when up-counting
Set OC2A on compare match when down-counting
1 1 Set OC2A on compare match when up-counting
Clear OC2A on compare match when down-counting
Table 18-5. Compare output mode, non-PWM mode.
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected
0 1 Toggle OC2B on compare match
1 0 Clear OC2B on compare match
1 1 Set OC2B on compare match155
2545T–AVR–05/11
ATmega48/88/168
Table 18-6 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to fast PWM
mode.
Note: 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 148 for more details.
Table 18-7 shows the COM2B1:0 bit functionality when the WGM22:0 bits are set to phase correct
PWM mode.
Note: 1. A special case occurs when OCR2B equals TOP and COM2B1 is set. In this case, the Compare
Match is ignored, but the set or clear is done at TOP. See “Phase correct PWM mode” on
page 148 for more details.
• Bits 3, 2 – Res: Reserved bits
These bits are reserved bits in the Atmel ATmega48/88/168 and will always read as zero.
• Bits 1:0 – WGM21:0: Waveform generation mode
Combined with the WGM22 bit found in the TCCR2B Register, these bits control the counting
sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform
generation to be used, see Table 18-8 on page 156. Modes of operation supported by the
Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode,
and two types of Pulse Width Modulation (PWM) modes (see “Modes of operation” on page
145).
Table 18-6. Compare output mode, fast PWM mode(1).
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected
0 1 Reserved
1 0 Clear OC2B on compare match, set OC2B at BOTTOM,
(non-inverting mode)
1 1 Set OC2B on compare match, clear OC2B at BOTTOM,
(invertiing mode)
Table 18-7. Compare output mode, phase correct PWM mode(1).
COM2B1 COM2B0 Description
0 0 Normal port operation, OC2B disconnected
0 1 Reserved
1 0 Clear OC2B on compare match when up-counting
Set OC2B on compare match when down-counting
1 1 Set OC2B on compare match when up-counting
Clear OC2B on compare match when down-counting156
2545T–AVR–05/11
ATmega48/88/168
Notes: 1. MAX= 0xFF
2. BOTTOM= 0x00
18.11.2 TCCR2B – Timer/counter control register B
• Bit 7 – FOC2A: Force output compare A
The FOC2A bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2A bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC2A output is
changed according to its COM2A1:0 bits setting. Note that the FOC2A bit is implemented as a
strobe. Therefore it is the value present in the COM2A1:0 bits that determines the effect of the
forced compare.
A FOC2A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2A as TOP.
The FOC2A bit is always read as zero.
• Bit 6 – FOC2B: Force output compare B
The FOC2B bit is only active when the WGM bits specify a non-PWM mode.
However, for ensuring compatibility with future devices, this bit must be set to zero when
TCCR2B is written when operating in PWM mode. When writing a logical one to the FOC2B bit,
an immediate Compare Match is forced on the Waveform Generation unit. The OC2B output is
changed according to its COM2B1:0 bits setting. Note that the FOC2B bit is implemented as a
strobe. Therefore it is the value present in the COM2B1:0 bits that determines the effect of the
forced compare.
Table 18-8. Waveform generation mode bit description.
Mode WGM2 WGM1 WGM0
Timer/counter
mode of
operation TOP
Update of
OCRx at
TOV flag
set on(1)(2)
0 0 0 0 Normal 0xFF Immediate MAX
10 0 1 PWM,
phase correct 0xFF TOP BOTTOM
2 0 1 0 CTC OCRA Immediate MAX
3 0 1 1 Fast PWM 0xFF BOTTOM MAX
4 1 0 0 Reserved – – –
51 0 1 PWM,
phase correct OCRA TOP BOTTOM
6 1 1 0 Reserved – – –
7 1 1 1 Fast PWM OCRA BOTTOM TOP
Bit 7 6 5 4 3 2 1 0
(0xB1) FOC2A FOC2B – – WGM22 CS22 CS21 CS20 TCCR2B
Read/write W W R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0157
2545T–AVR–05/11
ATmega48/88/168
A FOC2B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using
OCR2B as TOP.
The FOC2B bit is always read as zero.
• Bits 5:4 – Res: Reserved bits
These bits are reserved bits in the Atmel ATmega48/88/168 and will always read as zero.
• Bit 3 – WGM22: Waveform generation mode
See the description in the “TCCR2A – Timer/counter control register A” on page 153.
• Bit 2:0 – CS22:0: Clock select
The three Clock Select bits select the clock source to be used by the Timer/Counter, see Table
18-9.
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the
counter even if the pin is configured as an output. This feature allows software control of the
counting.
18.11.3 TCNT2 – Timer/counter register
The Timer/Counter Register gives direct access, both for read and write operations, to the
Timer/Counter unit 8-bit counter. Writing to the TCNT2 Register blocks (removes) the Compare
Match on the following timer clock. Modifying the counter (TCNT2) while the counter is running,
introduces a risk of missing a Compare Match between TCNT2 and the OCR2x Registers.
18.11.4 OCR2A – Output compare register A
Table 18-9. Clock select bit description.
CS22 CS21 CS20 Description
0 0 0 No clock source (timer/counter stopped)
0 0 1 clkT2S/(no prescaling)
0 1 0 clkT2S/8 (from prescaler)
0 1 1 clkT2S/32 (from prescaler)
1 0 0 clkT2S/64 (from prescaler)
1 0 1 clkT2S/128 (from prescaler)
1 1 0 clkT2S/256 (from prescaler)
1 1 1 clkT2S/1024 (from prescaler)
Bit 7 6 5 4 3 2 1 0
(0xB2) TCNT2[7:0] TCNT2
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0xB3) OCR2A[7:0] OCR2A
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0158
2545T–AVR–05/11
ATmega48/88/168
The Output Compare Register A contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2A pin.
18.11.5 OCR2B – Output compare register B
The Output Compare Register B contains an 8-bit value that is continuously compared with the
counter value (TCNT2). A match can be used to generate an Output Compare interrupt, or to
generate a waveform output on the OC2B pin.
18.11.6 TIMSK2 – Timer/Counter2 interrupt mask register
• Bit 2 – OCIE2B: Timer/Counter2 output compare match B interrupt enable
When the OCIE2B bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match B interrupt is enabled. The corresponding interrupt is executed
if a compare match in Timer/Counter2 occurs, that is, when the OCF2B bit is set in the
Timer/Counter 2 Interrupt Flag Register – TIFR2.
• Bit 1 – OCIE2A: Timer/Counter2 output compare match A interrupt enable
When the OCIE2A bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Compare Match A interrupt is enabled. The corresponding interrupt is executed
if a compare match in Timer/Counter2 occurs, that is, when the OCF2A bit is set in the
Timer/Counter 2 Interrupt Flag Register – TIFR2.
• Bit 0 – TOIE2: Timer/Counter2 overflow interrupt enable
When the TOIE2 bit is written to one and the I-bit in the Status Register is set (one), the
Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an
overflow in Timer/Counter2 occurs, that is, when the TOV2 bit is set in the Timer/Counter2 Interrupt
Flag Register – TIFR2.
18.11.7 TIFR2 – Timer/Counter2 interrupt flag register
• Bit 2 – OCF2B: Output compare flag 2 B
The OCF2B bit is set (one) when a compare match occurs between the Timer/Counter2 and the
data in OCR2B – Output Compare Register2. OCF2B is cleared by hardware when executing
the corresponding interrupt handling vector. Alternatively, OCF2B is cleared by writing a logic
one to the flag. When the I-bit in SREG, OCIE2B (Timer/Counter2 Compare match Interrupt
Enable), and OCF2B are set (one), the Timer/Counter2 Compare match Interrupt is executed.
Bit 7 6 5 4 3 2 1 0
(0xB4) OCR2B[7:0] OCR2B
Read/write R/W R/W R/W R/W R/W R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
(0x70) – – – – – OCIE2B OCIE2A TOIE2 TIMSK2
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0
Bit 7 6 5 4 3 2 1 0
0x17 (0x37) – – – – – OCF2B OCF2A TOV2 TIFR2
Read/write R R R R R R/W R/W R/W
Initial value 0 0 0 0 0 0 0 0159
2545T–AVR–05/11
ATmega48/88/168
• Bit 1 – OCF2A: Output compare flag 2 A
The OCF2A bit is set (one) when a compare match occurs between the Timer/Counter2 and the
data in OCR2A – Output Compare Register2. OCF2A is cleared by hardware when executing
the corresponding interrupt handling vector. Alternatively, OCF2A is cleared by writing a logic
one to the flag. When the I-bit in SREG, OCIE2A (Timer/Counter2 Compare match Interrupt
Enable), and OCF2A are set (one), the Timer/Counter2 Compare match Interrupt is executed.
• Bit 0 – TOV2: Timer/Counter2 overflow flag
The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware
when executing the corresponding interrupt handling vector. Alternatively, TOV2 is cleared
by writing a logic one to the flag. When the SREG I-bit, TOIE2A (Timer/Counter2 Overflow Interrupt
Enable), and TOV2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In
PWM mode, this bit is set when Timer/Counter2 changes counting direction at 0x00.
18.11.8 ASSR – Asynchronous status register
• Bit 7 – RES: Reserved bit
This bit is reserved and will always read as zero.
• Bit 6 – EXCLK: Enable external clock input
When EXCLK is written to one, and asynchronous clock is selected, the external clock input buffer
is enabled and an external clock can be input on Timer Oscillator 1 (TOSC1) pin instead of a
32kHz crystal. Writing to EXCLK should be done before asynchronous operation is selected.
Note that the crystal Oscillator will only run when this bit is zero.
• Bit 5 – AS2: Asynchronous Timer/Counter2
When AS2 is written to zero, Timer/Counter2 is clocked from the I/O clock, clkI/O. When AS2 is
written to one, Timer/Counter2 is clocked from a crystal Oscillator connected to the Timer Oscillator
1 (TOSC1) pin. When the value of AS2 is changed, the contents of TCNT2, OCR2A,
OCR2B, TCCR2A and TCCR2B might be corrupted.
• Bit 4 – TCN2UB: Timer/Counter2 update busy
When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set.
When TCNT2 has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value.
• Bit 3 – OCR2AUB: Output compare Register2 update busy
When Timer/Counter2 operates asynchronously and OCR2A is written, this bit becomes set.
When OCR2A has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2A is ready to be updated with a new value.
• Bit 2 – OCR2BUB: Output compare Register2 update busy
When Timer/Counter2 operates asynchronously and OCR2B is written, this bit becomes set.
When OCR2B has been updated from the temporary storage register, this bit is cleared by hardware.
A logical zero in this bit indicates that OCR2B is ready to be updated with a new value.
Bit 7 6 5 4 3 2 1 0
(0xB6) – EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB ASSR
Read/write R R/W R/W R R R R R
Initial value 0 0 0 0 0 0 0 0160
2545T–AVR–05/11
ATmega48/88/168
• Bit 1 – TCR2AUB: Timer/counter control Register2 update busy
When Timer/Counter2 operates asynchronously and TCCR2A is written, this bit becomes set.
When TCCR2A has been updated from the temporary storage register, this bit is cleared by
hardware. A logical zero in this bit indicates that TCCR2A is ready to be updated with a new
value.
• Bit 0 – TCR2BUB: Timer/counter control Register2 update busy
When Timer/Counter2 operates asynchronously and TCCR2B is written, this bit becomes set.
When TCCR2B has been updated from the temporary storage register, this bit is cleared by
hardware. A logical zero in this bit indicates that TCCR2B is ready to be updated with a new
value.
If a write is performed to any of the five Timer/Counter2 Registers while its update busy flag is
set, the updated value might get corrupted and cause an unintentional interrupt to occur.
The mechanisms for reading TCNT2, OCR2A, OCR2B, TCCR2A and TCCR2B are different.
When reading TCNT2, the actual timer value is read. When reading OCR2A, OCR2B, TCCR2A
and TCCR2B the value in the temporary storage register is read.
18.11.9 GTCCR – General timer/counter control register
• Bit 1 – PSRASY: Prescaler reset Timer/Counter2
When this bit is one, the Timer/Counter2 prescaler will be reset. This bit is normally cleared
immediately by hardware. If the bit is written when Timer/Counter2 is operating in asynchronous
mode, the bit will remain one until the prescaler has been reset. The bit will not be cleared by
hardware if the TSM bit is set. Refer to the description of the “Bit 7 – TSM: Timer/counter synchronization
mode” on page 139 for a description of the Timer/Counter Synchronization mode.
Bit 7 6 5 4 3 2 1 0
0x23 (0x43) TSM – – – – – PSRASY PSRSYNC GTCCR
Read/write R/W R R R R R R/W R/W
Initial value 0 0 0 0 0 0 0 0161
2545T–AVR–05/11
ATmega48/88/168
19. SPI – Serial peripheral interface
19.1 Features • Full-duplex, three-wire synchronous data transfer
• Master or slave operation
• LSB first or MSB first data transfer
• Seven programmable bit rates
• End of transmission interrupt flag
• Write collision flag protection
• Wake-up from idle mode
• Double speed (CK/2) master SPI mode
19.2 Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
Atmel ATmega48/88/168 and peripheral devices or between several AVR devices.
The USART can also be used in Master SPI mode, see “USART in SPI mode” on page 199. The
PRSPI bit in “Minimizing power consumption” on page 41 must be written to zero to enable SPI
module.162
2545T–AVR–05/11
ATmega48/88/168
Figure 19-1. SPI block diagram(1).
Note: 1. Refer to Figure 1-1 on page 2, and Table 14-3 on page 78 for SPI pin placement.
The interconnection between Master and Slave CPUs with SPI is shown in Figure 19-2 on page
163. The system consists of two shift Registers, and a Master clock generator. The SPI Master
initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave.
Master and Slave prepare the data to be sent in their respective shift Registers, and the Master
generates the required clock pulses on the SCK line to interchange data. Data is always shifted
from Master to Slave on the Master Out – Slave In, MOSI, line, and from Slave to Master on the
Master In – Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave
by pulling high the Slave Select, SS, line.
When configured as a Master, the SPI interface has no automatic control of the SS line. This
must be handled by user software before communication can start. When this is done, writing a
byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight
bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of
Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an
interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or
signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be
kept in the Buffer Register for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin
until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission SPI2X SPI2X
DIVIDER
/2/4/8/16/32/64/128163
2545T–AVR–05/11
ATmega48/88/168
Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt
is requested. The Slave may continue to place new data to be sent into SPDR before reading
the incoming data. The last incoming byte will be kept in the Buffer Register for later use.
Figure 19-2. SPI master-slave interconnection.
The system is single buffered in the transmit direction and double buffered in the receive direction.
This means that bytes to be transmitted cannot be written to the SPI Data Register before
the entire shift cycle is completed. When receiving data, however, a received character must be
read from the SPI Data Register before the next character has been completely shifted in. Otherwise,
the first byte is lost.
In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure
correct sampling of the clock signal, the minimum low and high periods should be:
Low periods: Longer than 2 CPU clock cycles.
High periods: Longer than 2 CPU clock cycles.
When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden
according to Table 19-1. For more details on automatic port overrides, refer to “Alternate port
functions” on page 76.
Note: See “Alternate functions of port B” on page 78 for a detailed description of how to define the direction
of the user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a
simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction
Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the
actual data direction bits for these pins. For example if MOSI is placed on pin PB3, replace
DD_MOSI with DDB3 and DDR_SPI with DDRB.
Table 19-1. SPI pin overrides(Note:).
Pin Direction, master SPI Direction, slave SPI
MOSI User defined Input
MISO Input User defined
SCK User defined Input
SS User defined Input
SHIFT
ENABLE164
2545T–AVR–05/11
ATmega48/88/168
Note: 1. See ”About code examples” on page 8.
Assembly code example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi r17,(1<>8);
UBRR0L = (unsigned char)ubrr;
Enable receiver and transmitter */
UCSR0B = (1<> 1) & 0x01;
return ((resh << 8) | resl);
}184
2545T–AVR–05/11
ATmega48/88/168
20.7.3 Receive complete flag and interrupt
The USART Receiver has one flag that indicates the Receiver state.
The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive buffer.
This flag is one when unread data exist in the receive buffer, and zero when the receive
buffer is empty (that is, does not contain any unread data). If the Receiver is disabled (RXENn =
0), the receive buffer will be flushed and consequently the RXCn bit will become zero.
When the Receive Complete Interrupt Enable (RXCIEn) in UCSRnB is set, the USART Receive
Complete interrupt will be executed as long as the RXCn Flag is set (provided that global interrupts
are enabled). When interrupt-driven data reception is used, the receive complete routine
must read the received data from UDRn in order to clear the RXCn Flag, otherwise a new interrupt
will occur once the interrupt routine terminates.
20.7.4 Receiver error flags
The USART Receiver has three Error Flags: Frame Error (FEn), Data OverRun (DORn) and
Parity Error (UPEn). All can be accessed by reading UCSRnA. Common for the Error Flags is
that they are located in the receive buffer together with the frame for which they indicate the
error status. Due to the buffering of the Error Flags, the UCSRnA must be read before the
receive buffer (UDRn), since reading the UDRn I/O location changes the buffer read location.
Another equality for the Error Flags is that they can not be altered by software doing a write to
the flag location. However, all flags must be set to zero when the UCSRnA is written for upward
compatibility of future USART implementations. None of the Error Flags can generate interrupts.
The Frame Error (FEn) Flag indicates the state of the first stop bit of the next readable frame
stored in the receive buffer. The FEn Flag is zero when the stop bit was correctly read (as one),
and the FEn Flag will be one when the stop bit was incorrect (zero). This flag can be used for
detecting out-of-sync conditions, detecting break conditions and protocol handling. The FEn
Flag is not affected by the setting of the USBSn bit in UCSRnC since the Receiver ignores all,
except for the first, stop bits. For compatibility with future devices, always set this bit to zero
when writing to UCSRnA.
The Data OverRun (DORn) Flag indicates data loss due to a receiver buffer full condition. A
Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting
in the Receive Shift Register, and a new start bit is detected. If the DORn Flag is set there
was one or more serial frame lost between the frame last read from UDRn, and the next frame
read from UDRn. For compatibility with future devices, always write this bit to zero when writing
to UCSRnA. The DORn Flag is cleared when the frame received was successfully moved from
the Shift Register to the receive buffer.
The Parity Error (UPEn) Flag indicates that the next frame in the receive buffer had a Parity
Error when received. If Parity Check is not enabled the UPEn bit will always be read zero. For
compatibility with future devices, always set this bit to zero when writing to UCSRnA. For more
details see “Parity bit calculation” on page 176 and “Parity checker” on page 184.
20.7.5 Parity checker
The Parity Checker is active when the high USART Parity mode (UPMn1) bit is set. Type of Parity
Check to be performed (odd or even) is selected by the UPMn0 bit. When enabled, the Parity
Checker calculates the parity of the data bits in incoming frames and compares the result with
the parity bit from the serial frame. The result of the check is stored in the receive buffer together
with the received data and stop bits. The Parity Error (UPEn) Flag can then be read by software
to check if the frame had a Parity Error.185
2545T–AVR–05/11
ATmega48/88/168
The UPEn bit is set if the next character that can be read from the receive buffer had a Parity
Error when received and the Parity Checking was enabled at that point (UPMn1 = 1). This bit is
valid until the receive buffer (UDRn) is read.
20.7.6 Disabling the receiver
In contrast to the Transmitter, disabling of the Receiver will be immediate. Data from ongoing
receptions will therefore be lost. When disabled (that is, the RXENn is set to zero) the Receiver
will no longer override the normal function of the RxDn port pin. The Receiver buffer FIFO will be
flushed when the Receiver is disabled. Remaining data in the buffer will be lost
20.7.7 Flushing the receive buffer
The receiver buffer FIFO will be flushed when the Receiver is disabled, that is, the buffer will be
emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal
operation, due to for instance an error condition, read the UDRn I/O location until the RXCn Flag
is cleared. The following code example shows how to flush the receive buffer.
Note: 1. See ”About code examples” on page 8.
20.8 Asynchronous data reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data
reception. The clock recovery logic is used for synchronizing the internally generated baud rate
clock to the incoming asynchronous serial frames at the RxDn pin. The data recovery logic samples
and low pass filters each incoming bit, thereby improving the noise immunity of the
Receiver. The asynchronous reception operational range depends on the accuracy of the internal
baud rate clock, the rate of the incoming frames, and the frame size in number of bits.
20.8.1 Asynchronous clock recovery
The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 20-5
on page 186 illustrates the sampling process of the start bit of an incoming frame. The sample
rate is 16 times the baud rate for Normal mode, and eight times the baud rate for Double Speed
mode. The horizontal arrows illustrate the synchronization variation due to the sampling process.
Note the larger time variation when using the Double Speed mode (U2Xn = 1) of
operation. Samples denoted zero are samples done when the RxDn line is idle (that is, no communication
activity).
Assembly code example(1)
USART_Flush:
sbis UCSRnA, RXCn
ret
in r16, UDRn
rjmp USART_Flush
C code example(1)
void USART_Flush( void )
{
unsigned char dummy;
while ( UCSRnA & (1< 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck >= 12MHz
High: > 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck >= 12MHz
VCC
GND
XTAL1
SCK
MISO
MOSI
RESET
+1.8V - 5.5V
AVCC
+1.8V - 5.5V(2)299
2545T–AVR–05/11
ATmega48/88/168
28.8.1 Serial programming pin mapping
28.8.2 Serial programming algorithm
When writing serial data to the Atmel ATmega48/88/168, data is clocked on the rising edge of
SCK.
When reading data from the ATmega48/88/168, data is clocked on the falling edge of SCK. See
Figure 28-9 on page 302 for timing details.
To program and verify the ATmega48/88/168 in the serial programming mode, the following
sequence is recommended (See Serial Programming Instruction set in Table 28-17 on page
300):
1. Power-up sequence:
Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
the programmer can not guarantee that SCK is held low during power-up. In this
case, RESET must be given a positive pulse of at least two CPU clock cycles duration
after SCK has been set to “0”.
2. Wait for at least 20ms and enable serial programming by sending the Programming
Enable serial instruction to pin MOSI.
3. The serial programming instructions will not work if the communication is out of synchronization.
When in sync. the second byte (0x53), will echo back when issuing the third
byte of the Programming Enable instruction. Whether the echo is correct or not, all four
bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a
positive pulse and issue a new Programming Enable command.
4. The Flash is programmed one page at a time. The memory page is loaded one byte at a
time by supplying the 6 LSB of the address and data together with the Load Program
Memory Page instruction. To ensure correct loading of the page, the data low byte must
be loaded before data high byte is applied for a given address. The Program Memory
Page is stored by loading the Write Program Memory Page instruction with the 7 MSB of
the address. If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH before
issuing the next page (see Table 28-16 on page 300). Accessing the serial programming
interface before the Flash write operation completes can result in incorrect programming.
5. A: The EEPROM array is programmed one byte at a time by supplying the address and
data together with the appropriate Write instruction. An EEPROM memory location is first
automatically erased before new data is written. If polling (RDY/BSY) is not used, the
user must wait at least tWD_EEPROM before issuing the next byte (see Table 28-16 on page
300). In a chip erased device, no 0xFFs in the data file(s) need to be programmed.
B: The EEPROM array is programmed one page at a time. The Memory page is loaded
one byte at a time by supplying the 6 LSB of the address and data together with the Load
EEPROM Memory Page instruction. The EEPROM Memory Page is stored by loading
the Write EEPROM Memory Page Instruction with the 7 MSB of the address. When using
EEPROM page access only byte locations loaded with the Load EEPROM Memory Page
instruction is altered. The remaining locations remain unchanged. If polling (RDY/BSY) is
not used, the used must wait at least tWD_EEPROM before issuing the next byte (See Table
Table 28-15. Pin mapping serial programming.
Symbol Pins I/O Description
MOSI PB3 I Serial Data in
MISO PB4 O Serial Data out
SCK PB5 I Serial Clock300
2545T–AVR–05/11
ATmega48/88/168
28-16 on page 300). In a chip erased device, no 0xFF in the data file(s) need to be
programmed.
6. Any memory location can be verified by using the Read instruction which returns the content
at the selected address at serial output MISO.
7. At the end of the programming session, RESET can be set high to commence normal
operation.
8. Power-off sequence (if needed):
Set RESET to “1”.
Turn VCC power off.
28.8.3 Serial programming instruction set
Table 28-17 and Figure 28-8 on page 302 describes the instruction set.
Table 28-16. Typical wait delay before writing the next flash or EEPROM location.
Symbol Minimum wait delay
tWD_FLASH 4.5ms
tWD_EEPROM 3.6ms
tWD_ERASE 9.0ms
Table 28-17. Serial programming instruction set (hexadecimal values).
Instruction/operation
Instruction format
Byte 1 Byte 2 Byte 3 Byte 4
Programming enable $AC $53 $00 $00
Chip erase (program memory/EEPROM) $AC $80 $00 $00
Poll RDY/BSY $F0 $00 $00 data byte out
Load instructions
Load extended address byte(1) $4D $00 Extended adr $00
Load program memory page, high byte $48 $00 adr LSB high data byte in
Load program memory page, low byte $40 $00 adr LSB low data byte in
Load EEPROM memory page (page access) $C1 $00 0000 000aa data byte in
Read instructions
Read program memory, high byte $28 adr MSB adr LSB high data byte out
Read program memory, low byte $20 adr MSB adr LSB low data byte out
Read EEPROM memory $A0 0000 00aa aaaa aaaa data byte out
Read lock bits $58 $00 $00 data byte out
Read signature byte $30 $00 0000 000aa data byte out
Read fuse bits $50 $00 $00 data byte out
Read fuse high bits $58 $08 $00 data byte out
Read extended fuse bits $50 $08 $00 data byte out
Read calibration byte $38 $00 $00 data byte out301
2545T–AVR–05/11
ATmega48/88/168
Notes: 1. Not all instructions are applicable for all parts.
2. a = address.
3. Bits are programmed ‘0’, unprogrammed ‘1’.
4. To ensure future compatibility, unused fuses and lock bits should be unprogrammed (‘1’).
5. Refer to the correspondig section for fuse and lock bits, calibration and signature bytes and page size.
6. Instructions accessing program memory use a word address. This word may be random within the page range.
7. See htt://www.atmel.com/avr for application notes regarding programming and programmers.
If the LSB in RDY/BSY data byte out is ‘1’, a programming operation is still pending. Wait until
this bit returns ‘0’ before the next instruction is carried out.
Within the same page, the low data byte must be loaded prior to the high data byte.
After data is loaded to the page buffer, program the EEPROM page, see Figure 28-8.
Write instructions(6)
Write program memory page $4C adr MSB adr LSB $00
Write EEPROM memory $C0 0000 00aa aaaa aaaa data byte in
Write EEPROM memory page (page access) $C2 0000 00aa aaaa aa00 $00
Write lock bits $AC $E0 $00 data byte in
Write fuse bits $AC $A0 $00 data byte in
Write fuse high bits $AC $A8 $00 data byte in
Write extended fuse bits $AC $A4 $00 data byte in
Table 28-17. Serial programming instruction set (hexadecimal values). (Continued)
Instruction/operation
Instruction format
Byte 1 Byte 2 Byte 3 Byte 4302
2545T–AVR–05/11
ATmega48/88/168
Figure 28-8. Serial programming instruction example.
28.8.4 SPI serial programming characteristics
Figure 28-9. Serial programming waveforms.
For characteristics of the SPI module see “SPI timing characteristics” on page 309.
Byte 1 Byte 2 Byte 3 Byte 4
Adr MSB Adr LSB
Bit 15 B 0
Serial programming instruction
Program memory/
EEPROM memory
Page 0
Page 1
Page 2
Page N-1
Page buffer
Write program memory page/
Write EEPROM memory page
Load program memory page (high/low byte)/
Load EEPROM memory page (page access)
Byte 1 Byte 2 Byte 3 Byte 4
Bit 15 B 0
Adr MSB Adr LSB
Page offset
Page number
Adr MSB Adr LSB
MSB
MSB
LSB
LSB
SERIAL CLOCK INPUT
(SCK)
SERIAL DATA INPUT
(MOSI)
(MISO)
SAMPLE
SERIAL DATA OUTPUT303
2545T–AVR–05/11
ATmega48/88/168
29. Electrical characteristics
29.1 Absolute maximum ratings*
29.2 DC characteristics
Operating temperature................................... -55°C to +125°C *NOTICE: Stresses beyond those listed under “Absolute
Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and
functional operation of the device at these or
other conditions beyond those indicated in the
operational sections of this specification is not
implied. Exposure to absolute maximum rating
conditions for extended periods may affect
device reliability.
Storage temperature...................................... -65°C to +150°C
Voltage on any pin except RESET
with respect to ground .................................-0.5V to VCC+0.5V
Voltage on RESET with respect to ground ......-0.5V to +13.0V
Maximum operating voltage.............................................. 6.0V
DC current per I/O pin.................................................. 40.0mA
DC current VCC and GND pins .................................. 200.0mA
TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted).
Symbol Parameter Condition Minimum Typical Maximum Units
VIL
Input low voltage, except
XTAL1 and RESET pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
-0.5
-0.5
0.2VCC(1)
0.3VCC(1)
V
VIH
Input high voltage, except
XTAL1 and RESET pins
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.7VCC(2)
0.6VCC(2)
VCC + 0.5
VCC + 0.5
VIL1
Input low voltage,
XTAL1 pin VCC = 1.8V - 5.5V -0.5 0.1VCC(1)
VIH1
Input high voltage,
XTAL1 pin
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.8VCC(2)
0.7VCC(2)
VCC + 0.5
VCC + 0.5
VIL2
Input low voltage,
RESET pin VCC = 1.8V - 5.5V -0.5 0.2VCC(1)
VIH2
Input high voltage,
RESET pin VCC = 1.8V - 5.5V 0.9VCC(2) VCC + 0.5
VIL3
Input low voltage,
RESET pin as I/O
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
-0.5
-0.5
0.2VCC(1)
0.3VCC(1)
VIH3
Input high voltage,
RESET pin as I/O
VCC = 1.8V - 2.4V
VCC = 2.4V - 5.5V
0.7VCC(2)
0.6VCC(2)
VCC + 0.5
VCC + 0.5
VOL
Output low voltage(3),
RESET pin as I/O
I
OL = 20mA, VCC = 5V
IOL = 6mA, VCC = 3V
0.7
0.5
VOH
Output high voltage(4),
RESET pin as I/O
I
OH = -20mA, VCC = 5V
I
OH = -10mA, VCC = 3V
4.2
2.3
IIL
Input leakage
current I/O pin
VCC = 5.5V, pin low
(absolute value) 1
µA
I
IH
Input leakage
current I/O pin
VCC = 5.5V, pin high
(absolute value) 1
RRST Reset pull-up resistor 30 60
kΩ
RPU I/O pin pull-up resistor 20 50304
2545T–AVR–05/11
ATmega48/88/168
Notes: 1. “Max” means the highest value where the pin is guaranteed to be read as low
2. “Min” means the lowest value where the pin is guaranteed to be read as high
3. Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
ATmega48/88/168:
1] The sum of all IOL, for ports C0 - C5, ADC7, ADC6 should not exceed 100mA.
2] The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3] The sum of all IOL, for ports D0 - D4, RESET should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
ATmega48/88/168:
1] The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA.
2] The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 150mA.
If IIOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current
greater than the listed test condition.
5. Values with “Minimizing power consumption” on page 41 enabled (0xFF).
ICC
Power supply current(5)
Active 1MHz, VCC = 2V
(Atmel ATmega48/88/168V) 0.55
mA
Active 4MHz, VCC = 3V
(Atmel ATmega48/88/168L) 3.5
Active 8MHz, VCC = 5V
(Atmel ATmega48/88/168) 12
Idle 1MHz, VCC = 2V
(ATmega48/88/168V) 0.25 0.5
Idle 4MHz, VCC = 3V
(ATmega48/88/168L) 1.5
Idle 8MHz, VCC = 5V
(ATmega48/88/168) 5.5
Power-down mode
WDT enabled, VCC = 3V 8 15
µA
WDT disabled, VCC = 3V 1 2
VACIO
Analog comparator
input offset voltage
VCC = 5V
Vin = VCC/2 10 40 mV
IACLK
Analog comparator
input leakage current
VCC = 5V
Vin = VCC/2 -50 50 nA
t
ACID
Analog comparator
propagation delay
VCC = 2.7V
VCC = 4.0V
750
500 ns
TA = -40°C to 85°C, VCC = 1.8V to 5.5V (unless otherwise noted). (Continued)
Symbol Parameter Condition Minimum Typical Maximum Units305
2545T–AVR–05/11
ATmega48/88/168
29.3 Speed grades
Maximum frequency is dependent on VCC. As shown in Figure 29-1 and Figure 29-2, the Maximum
Frequency vs. VCC curve is linear between 1.8V < VCC < 2.7V and between 2.7V < VCC <
4.5V.
Figure 29-1. Maximum frequency vs. VCC, Atmel ATmega48V/88V/168V.
Figure 29-2. Maximum frequency vs. VCC, ATmega48/88/168.
10MHz
4MHz
1.8V 2.7V 5.5V
Safe operating area
20MHz
10MHz
2.7V 4.5V 5.5V
Safe operating area306
2545T–AVR–05/11
ATmega48/88/168
29.4 Clock characteristics
29.4.1 Calibrated internal RC oscillator accuracy
Notes: 1. Voltage range for Atmel ATmega48V/88V/168V.
2. Voltage range for Atmel ATmega48/88/168.
29.4.2 External clock drive waveforms
Figure 29-3. External clock drive waveforms.
29.4.3 External clock drive
Table 29-1. Calibration accuracy of internal RC oscillator.
Frequency VCC Temperature Calibration accuracy
Factory calibration 8.0MHz 3V 25°C ±10%
User calibration 7.3MHz - 8.1MHz 1.8V - 5.5V(1)
2.7V - 5.5V(2) -40°C - 85°C ±1%
VIL1
VIH1
Table 29-2. External clock drive.
Symbol Parameter
VCC = 1.8V - 5.5V VCC = 2.7V - 5.5V VCC = 4.5V - 5.5V
Min. Max. Min. Max. Min. Max. Units
1/tCLCL
Oscillator
frequency 0 4 0 10 0 20 MHz
tCLCL Clock period 250 100 50
tCHCX High time 100 40 20 ns
tCLCX Low time 100 40 20
tCLCH Rise time 2.0 1.6 0.5
μs
tCHCL Fall time 2.0 1.6 0.5
ΔtCLCL
Change in period
from one clock
cycle to the next
2 2 2%307
2545T–AVR–05/11
ATmega48/88/168
29.5 System and reset characteristics
Note: 1. The power-on reset will not work unless the supply voltage has been below VPOT (falling).
Notes: 1. VBOT may be below nominal minimum operating voltage for some devices. For devices where this is the case, the device is
tested down to VCC = VBOT during the production test. This guarantees that a brown-out reset will occur before VCC drops to
a voltage where correct operation of the microcontroller is no longer guaranteed. The test is performed using
BODLEVEL = 110 and BODLEVEL = 101 for Atmel ATmega48V/88V/168V, and BODLEVEL = 101 and BODLEVEL = 100
for Atmel ATmega48/88/168.
Table 29-3. Reset, brown-out and internal voltage characteristics.
Symbol Parameter Condition Min. Typ. Max. Units
VPOT
Power-on reset threshold voltage (rising) 0.7 1.0 1.4
V
Power-on reset threshold voltage (falling)(1) 0.05 0.9 1.3
VPONSR Power-on slope rate 0.01 4.5 V/ms
VRST RESET pin threshold voltage 0.2VCC 0.9VCC V
tRST Minimum pulse width on RESET pin 2.5 µs
VHYST Brown-out detector hysteresis 50 mV
tBOD Min pulse width on brown-out reset 2 µs
VBG Bandgap reference voltage VCC = 2.7
TA = 25°C 1.0 1.1 1.2 V
t
BG Bandgap reference start-up time VCC = 2.7
TA = 25°C 40 70 µs
I
BG Bandgap reference current consumption VCC = 2.7
TA = 25°C 10 µA
Table 29-4. BODLEVEL fuse coding(1).
BODLEVEL 2:0 Fuses Min. VBOT Typ. VBOT Max. VBOT Units
111 BOD disabled
110 1.7 1.8 2.0
101 2.5 2.7 2.9 V
100 4.1 4.3 4.5
011
Reserved
010
001
000308
2545T–AVR–05/11
ATmega48/88/168
29.6 2-wire serial interface characteristics
Table 29-5 describes the requirements for devices connected to the 2-wire Serial Bus. The Atmel ATmega48/88/168 2-wire
Serial Interface meets or exceeds these requirements under the noted conditions.
Timing symbols refer to Figure 29-4 on page 309.
Notes: 1. In ATmega48/88/168, this parameter is characterized and not 100% tested.
2. Required only for fSCL > 100kHz.
Table 29-5. 2-wire serial bus requirements.
Symbol Parameter Condition Min. Max. Units
VIL Input low-voltage -0.5 0.3VCC
V
VIH Input high-voltage 0.7VCC VCC + 0.5
Vhys(1) Hysteresis of schmitt trigger inputs 0.05VCC(2) –
VOL(1) Output low-voltage 3mA sink current 0 0.4
tr
(1) Rise time for both SDA and SCL 20 + 0.1Cb
(3)(2) 300
tof ns (1) Output fall time from VIHmin to VILmax 10pF < Cb < 400pF(3) 20 + 0.1Cb
(3)(2) 250
tSP(1) Spikes suppressed by input filter 0 50(2)
Ii Input current each I/O pin 0.1VCC < Vi
< 0.9VCC -10 10 µA
Ci
(1) Capacitance for each I/O pin – 10 pF
fSCL SCL clock frequency fCK(4) > max(16fSCL, 250kHz)(5) 0 400 kHz
Rp Value of pull-up resistor
fSCL ≤ 100kHz
fSCL > 100kHz
tHD;STA Hold time (repeated) START condition
fSCL ≤ 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tLOW Low period of the SCL clock
fSCL ≤ 100kHz 4.7 –
fSCL > 100kHz 1.3 –
tHIGH High period of the SCL clock
fSCL ≤ 100kHz 4.0 –
fSCL > 100kHz 0.6 –
tSU;STA Setup time for a repeated START condition
fSCL ≤ 100kHz 4.7 –
fSCL > 100kHz 0.6 –
tHD;DAT Data hold time
fSCL ≤ 100kHz 0 3.45
fSCL > 100kHz 0 0.9
tSU;DAT Data setup time
fSCL ≤ 100kHz 250 –
ns
fSCL > 100kHz 100 –
tSU;STO Setup time for STOP condition
fSCL ≤ 100kHz 4.0 –
µs
fSCL > 100kHz 0.6 –
tBUF
Bus free time between a STOP and START
condition
fSCL ≤ 100kHz 4.7 –
fSCL > 100kHz 1.3 –
VCC – 0.4V
3mA ---------------------------- 1000ns
Cb
-----------------
Ω
VCC – 0.4V
3mA ---------------------------- 300ns
Cb
--------------309
2545T–AVR–05/11
ATmega48/88/168
3. Cb = capacitance of one bus line in pF.
4. fCK = CPU clock frequency.
5. This requirement applies to all Atmel ATmega48/88/168 2-wire Serial Interface operation. Other devices connected to the 2-
wire Serial Bus need only obey the general fSCL requirement.
Figure 29-4. 2-wire serial bus timing.
29.7 SPI timing characteristics
See Figure 29-5 on page 310 and Figure 29-6 on page 310 for details.
Note: 1. In SPI programming mode the minimum SCK high/low period is:
- 2 tCLCL for fCK < 12MHz
- 3 tCLCL for fCK > 12MHz
t
SU;STA
t
LOW
t
HIGH
t
LOW
t
of
t
HD;STA t
HD;DAT t
SU;DAT t
SU;STO
t
BUF
SCL
SDA
t
r
Table 29-6. SPI timing parameters.
Description Mode Minimum Typical Maximum
1 SCK period Master See Table 19-5
on page 169
ns
2 SCK high/low Master 50% duty cycle
3 Rise/fall time Master 3.6
4 Setup Master 10
5 Hold Master 10
6 Out to SCK Master 0.5 • tsck
7 SCK to out Master 10
8 SCK to out high Master 10
9 SS low to out Slave 15
10 SCK period Slave 4 • tck
11 SCK high/low(1) Slave 2 • tck
12 Rise/fall time Slave 1600
13 Setup Slave 10
14 Hold Slave tck
15 SCK to out Slave 15
16 SCK to SS high Slave 20
17 SS high to tri-state Slave 10
18 SS low to SCK Slave 20310
2545T–AVR–05/11
ATmega48/88/168
Figure 29-5. SPI interface timing requirements (master mode).
Figure 29-6. SPI interface timing requirements (slave mode).
MOSI
(Data output)
SCK
(CPOL = 1)
MISO
(Data input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
6 1
2 2
4 5 3
7 8
MISO
(Data output)
SCK
(CPOL = 1)
MOSI
(Data input)
SCK
(CPOL = 0)
SS
MSB LSB
MSB LSB
...
...
10
11 11
13 14 12
15 17
9
X
16311
2545T–AVR–05/11
ATmega48/88/168
29.8 ADC characteristics
Note: 1. AVCC absolute min./max.: 1.8V/5.5V
Table 29-7. ADC characteristics.
Symbol Parameter Condition Minimum Typical Maximum Units
Resolution 10 Bits
Absolute accuracy (Including
INL, DNL, quantization error,
gain and offset error)
VREF = 4V, VCC = 4V,
ADC clock = 200kHz 2
LSB
VREF = 4V, VCC = 4V,
ADC clock = 1MHz 4.5
VREF = 4V, VCC = 4V,
ADC clock = 200kHz
Noise reduction mode
2
VREF = 4V, VCC = 4V,
ADC clock = 1MHz
Noise reduction mode
4.5
Integral non-linearity (INL) VREF = 4V, VCC = 4V,
ADC clock = 200kHz 0.5
Differential non-linearity (DNL) VREF = 4V, VCC = 4V,
ADC clock = 200kHz 0.25
Gain error VREF = 4V, VCC = 4V,
ADC clock = 200kHz 2
Offset error VREF = 4V, VCC = 4V,
ADC clock = 200kHz 2
Conversion time Free running conversion 13 260 µs
Clock frequency 50 1000 kHz
AVCC(1) Analog supply voltage VCC - 0.3 VCC + 0.3
VREF Reference voltage 1.0 AVCC V
VIN Input voltage GND VREF
Input bandwidth 38.5 kHz
VINT Internal voltage reference 1.0 1.1 1.2 V
RREF Reference input resistance 32 kΩ
RAIN Analog input resistance 100 MΩ312
2545T–AVR–05/11
ATmega48/88/168
29.9 Parallel programming characteristics
Figure 29-7. Parallel programming timing, including some general timing requirements.
Figure 29-8. Parallel programming timing, loading sequence with timing requirements(1).
Note: 1. The timing requirements shown in Figure 29-7 (that is, tDVXH, tXHXL, and tXLDX) also apply to
loading operation.
Data & contol
(DATA, XA0/1, BS1, BS2)
XTAL1 t
XHXL
t
WLWH
t
DVXH t
XLDX
t
PLWL
t
WLRH
WR
RDY/BSY
PAGEL t
PHPL
t
PLBX t
BVPH
t
XLWL
t
WLBX
tBVWL
WLRL
XTAL1
PAGEL
t XLXH PLXH t t
XLPH
DATA ADDR0 (low byte) DATA (low byte) DATA (high byte) ADDR1 (low byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
LOAD DATA
(LOW BYTE)
LOAD DATA
(HIGH BYTE)
LOAD DATA LOAD ADDRESS
(LOW BYTE)313
2545T–AVR–05/11
ATmega48/88/168
Figure 29-9. Parallel programming timing, reading sequence (within the same page) with timing
requirements(1).
Note: 1. The timing requirements shown in Figure 29-7 on page 312 (that is, tDVXH, tXHXL, and tXLDX)
also apply to reading operation.
Table 29-8. Parallel programming characteristics, VCC = 5V ±10%.
Symbol Parameter Min. Typ. Max. Units
VPP Programming enable voltage 11.5 12.5 V
IPP Programming enable current 250 µA
tDVXH Data and control valid before XTAL1 high 67
ns
tXLXH XTAL1 low to XTAL1 high 200
tXHXL XTAL1 pulse width high 150
tXLDX Data and control hold after XTAL1 low 67
tXLWL XTAL1 low to WR low 0
tXLPH XTAL1 low to PAGEL high 0
tPLXH PAGEL low to XTAL1 high 150
tBVPH BS1 valid before PAGEL high 67
tPHPL PAGEL pulse width high 150
tPLBX BS1 hold after PAGEL low 67
tWLBX BS2/1 hold after WR low 67
tPLWL PAGEL low to WR low 67
tBVWL BS1 valid to WR low 67
tWLWH WR pulse width low 150
tWLRL WR low to RDY/BSY low 0 1 µs
tWLRH WR low to RDY/BSY high(1) 3.7 4.5
ms
tWLRH_CE WR low to RDY/BSY high for chip erase(2) 7.5 9
XTAL1
OE
DATA ADDR0 (low byte) DATA (low byte) DATA (high byte) ADDR1 (low byte)
BS1
XA0
XA1
LOAD ADDRESS
(LOW BYTE)
READ DATA
(LOW BYTE)
READ DATA
(HIGH BYTE)
LOAD ADDRESS
(LOW BYTE)
t
BVDV
t
OLDV
t
XLOL
t
OHDZ314
2545T–AVR–05/11
ATmega48/88/168
Notes: 1. tWLRH is valid for the write flash, write EEPROM, write fuse bits and write lock bits commands.
2. tWLRH_CE is valid for the chip erase command.
t
XLOL XTAL1 low to OE low 0
ns
t
BVDV BS1 valid to DATA valid 0 250
tOLDV OE low to DATA valid 250
t
OHDZ OE high to DATA tri-stated 250
Table 29-8. Parallel programming characteristics, VCC = 5V ±10%. (Continued)
Symbol Parameter Min. Typ. Max. Units315
2545T–AVR–05/11
ATmega48/88/168
30. Typical characteristics
The following charts show typical behavior. These figures are not tested during manufacturing.
All current consumption measurements are performed with all I/O pins configured as inputs and
with internal pull-ups enabled. A square wave generator with rail-to-rail output is used as clock
source.
All Active- and Idle current consumption measurements are done with all bits in the PRR register
set and thus, the corresponding I/O modules are turned off. Also the Analog Comparator is disabled
during these measurements. Table 30-1 on page 321 and Table 30-2 on page 321 show
the additional current consumption compared to ICC Active and ICC Idle for every I/O module controlled
by the Power Reduction Register. See “Power reduction register” on page 41 for details.
The power consumption in Power-down mode is independent of clock selection.
The current consumption is a function of several factors such as: operating voltage, operating
frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature.
The dominating factors are operating voltage and frequency.
The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where
CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin.
The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to
function properly at frequencies higher than the ordering code indicates.
The difference between current consumption in Power-down mode with Watchdog Timer
enabled and Power-down mode with Watchdog Timer disabled represents the differential current
drawn by the Watchdog Timer.
30.1 Active supply current
Figure 30-1. Active supply current vs. frequency (0.1MHz - 1.0MHz).
5.5V
5.0V
4.5V
4.0V
3.3V
2.7V
1.8V
0
0.2
0.4
0.6
0.8
1
1.2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)316
2545T–AVR–05/11
ATmega48/88/168
Figure 30-2. Active supply current vs. frequency (1MHz - 24MHz).
Figure 30-3. Active supply current vs. VCC (internal RC oscillator, 128kHz).
0
2
4
6
8
10
12
14
16
18
0 4 8 12 16 20 24
Frequency (MHz)
ICC (mA)
2.7V
1.8V
3.3V
4.0V
4.5V
5.0V
5.5V
,
85°C
25°C
-40°C
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)317
2545T–AVR–05/11
ATmega48/88/168
Figure 30-4. Active supply current vs. VCC (internal RC oscillator, 1MHz).
Figure 30-5. Active supply current vs. VCC (internal RC oscillator, 8MHz).
,
85°C
25°C
-40°C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
,
85°C
25°C
-40°C
0
1
2
3
4
5
6
7
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)318
2545T–AVR–05/11
ATmega48/88/168
Figure 30-6. Active supply current vs. VCC (32kHz external oscillator).
30.2 Idle supply current
Figure 30-7. Idle supply current vs. frequency (0.1MHz - 1.0MHz).
25°C
0
10
20
30
40
50
60
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
5.5V
5.0V
4.5V
4.0V
3.3V
2.7V
1.8V
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)319
2545T–AVR–05/11
ATmega48/88/168
Figure 30-8. Idle supply current vs. frequency (1MHz - 24MHz).
Figure 30-9. Idle supply current vs. VCC (internal RC oscillator, 128kHz).
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
0 4 8 12 16 20 24
Frequency (MHz)
ICC (mA)
2.7V
1.8V
3.3V
4.0V
4.5V
5.0V
5.5V
85°C
25°C
-40°C
0
0.005
0.01
0.015
0.02
0.025
0.03
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)320
2545T–AVR–05/11
ATmega48/88/168
Figure 30-10. Idle supply current vs. VCC (internal RC oscillator, 1MHz).
Figure 30-11. Idle supply current vs. VCC (internal RC oscillator, 8MHz).
,
85°C
25°C
-40°C
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
,
85°C
25°C
-40°C
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)321
2545T–AVR–05/11
ATmega48/88/168
Figure 30-12. Idle supply current vs. VCC (32kHz external oscillator).
30.3 Supply current of I/O modules
The tables and formulas below can be used to calculate the additional current consumption for
the different I/O modules in Active and Idle mode. The enabling or disabling of the I/O modules
are controlled by the Power Reduction Register. See “Power reduction register” on page 41 for
details.
25°C
0
5
10
15
20
25
30
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
Table 30-1. Additional current consumption for the different I/O modules (absolute values).
PRR bit Typical numbers
VCC = 2V, F = 1MHz VCC = 3V, F = 4MHz VCC = 5V, F = 8MHz
PRUSART0 8.0µA 51µA 220µA
PRTWI 12µA 75µA 315µA
PRTIM2 11µA 72µA 300µA
PRTIM1 5.0µA 32µA 130µA
PRTIM0 4.0µA 24µA 100µA
PRSPI 15µA 95µA 400µA
PRADC 12µA 75µA 315µA
Table 30-2. Additional current consumption (percentage) in active and idle mode.
PRR bit
Additional current consumption
compared to active with external clock
(see Figure 30-1 on page 315 and
Figure 30-2 on page 316)
Additional current consumption
compared to Idle with external clock
(see Figure 30-7 on page 318 and
Figure 30-8 on page 319)
PRUSART0 3.3% 18%
PRTWI 4.8% 26%
PRTIM2 4.7% 25%322
2545T–AVR–05/11
ATmega48/88/168
It is possible to calculate the typical current consumption based on the numbers from Table 30-2
on page 321 for other VCC and frequency settings than listed in Table 30-1 on page 321.
30.3.0.1 Example 1
Calculate the expected current consumption in idle mode with USART0, TIMER1, and TWI
enabled at VCC = 3.0V and F = 1MHz. From Table 30-2 on page 321, third column, we see that
we need to add 18% for the USART0, 26% for the TWI, and 11% for the TIMER1 module. Reading
from Figure 30-7 on page 318, we find that the idle current consumption is ~0.075mA at VCC
= 3.0V and F = 1MHz. The total current consumption in idle mode with USART0, TIMER1, and
TWI enabled, gives:
30.3.0.2 Example 2
Same conditions as in example 1, but in active mode instead. From Table 30-2 on page 321,
second column we see that we need to add 3.3% for the USART0, 4.8% for the TWI, and 2.0%
for the TIMER1 module. Reading from Figure 30-1 on page 315, we find that the active current
consumption is ~0.42mA at VCC = 3.0V and F = 1MHz. The total current consumption in idle
mode with USART0, TIMER1, and TWI enabled, gives:
30.3.0.3 Example 3
All I/O modules should be enabled. Calculate the expected current consumption in active mode
at VCC = 3.6V and F = 10MHz. We find the active current consumption without the I/O modules
to be ~ 4.0mA (from Figure 30-2 on page 316). Then, by using the numbers from Table 30-2 on
page 321 - second column, we find the total current consumption:
PRTIM1 2.0% 11%
PRTIM0 1.6% 8.5%
PRSPI 6.1% 33%
PRADC 4.9% 26%
Table 30-2. Additional current consumption (percentage) in active and idle mode. (Continued)
PRR bit
Additional current consumption
compared to active with external clock
(see Figure 30-1 on page 315 and
Figure 30-2 on page 316)
Additional current consumption
compared to Idle with external clock
(see Figure 30-7 on page 318 and
Figure 30-8 on page 319)
ICCtotal ≈ ≈ 0.075mA • ( ) 1 0.18 0.26 0.11 +++ 0.116mA
ICCtotal ≈ ≈ 0.42mA • ( ) 1 0.033 0.048 0.02 +++ 0.46mA
ICCtotal ≈ ≈ 4.0mA • ( ) 1 0.033 0.048 0.047 0.02 0.016 0.061 0.049 + + + ++ + + 5.1mA323
2545T–AVR–05/11
ATmega48/88/168
30.4 Power-down supply current
Figure 30-13. Power-down supply current vs. VCC (watchdog timer disabled).
Figure 30-14. Power-down supply current vs. VCC (watchdog timer enabled).
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C
0
2
4
6
8
10
12
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)324
2545T–AVR–05/11
ATmega48/88/168
30.5 Power-save supply current
Figure 30-15. Power-save supply current vs. VCC (watchdog timer disabled).
30.6 Standby supply current
Figure 30-16. Standby supply current vs. VCC (low power crystal oscillator).
25°C
0
2
4
6
8
10
12
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
6MHz Xtal
6MHz Res.
4MHz Xtal
4MHz Res.
455kHz Res.
32kHz Xtal
2MHz Xtal
2MHz Res.
1MHz Res.
0
20
40
60
80
100
120
140
160
180
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)325
2545T–AVR–05/11
ATmega48/88/168
Figure 30-17. Standby supply current vs. VCC (full swing crystal oscillator).
30.7 Pin pull-up
Figure 30-18. I/O pin pull-up resistor current vs. input voltage (VCC = 5V).
6MHz Xtal
(ckopt)
4MHz Xtal
(ckopt)
2MHz Xtal
(ckopt)
16MHz Xtal
12MHz Xtal
0
50
100
150
200
250
300
350
400
450
500
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C 25°C
-40°C
0
20
40
60
80
100
120
140
160
0123456
VOP (V)
IOP (µA)326
2545T–AVR–05/11
ATmega48/88/168
Figure 30-19. I/O pin pull-up resistor current vs. input voltage (VCC = 2.7V).
Figure 30-20. Reset pull-up resistor current vs. reset pin voltage (VCC = 5V).
85°C 25°C
-40°C
0
10
20
30
40
50
60
70
80
90
0 0.5 1 1.5 2 2.5 3
VOP (V)
IOP (µA)
0
20
40
60
80
100
120
0123456
VRESET (V)
IRESET (µA)
-40°C 25°C
85°C327
2545T–AVR–05/11
ATmega48/88/168
Figure 30-21. Reset pull-up resistor current vs. reset pin voltage (VCC = 2.7V).
30.8 Pin driver strength
Figure 30-22. I/O pin source current vs. output voltage (VCC = 5V).
-40°C
0
10
20
30
40
50
60
70
0 0.5 1 1.5 2 2.5 3
VRESET (V)
IRESET (µA)
25°C
85°C
85°C
25°C
-40°C
0
10
20
30
40
50
60
70
80
90
0123456
VOH (V)
IOH (mA)328
2545T–AVR–05/11
ATmega48/88/168
Figure 30-23. I/O pin source current vs. output voltage (VCC = 2.7V).
Figure 30-24. I/O pin source current vs. output voltage (VCC = 1.8V).
85°C
25°C
-40°C
0
5
10
15
20
25
30
35
0 0.5 1 1.5 2 2.5 3
VOH (V)
IOH (mA)
85°C
25°C -40°C
0
1
2
3
4
5
6
7
8
9
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOH (V)
IOH (mA)329
2545T–AVR–05/11
ATmega48/88/168
Figure 30-25. I/O pin sink current vs. output voltage (VCC = 5V).
Figure 30-26. I/O pin sink current vs. output voltage (VCC = 2.7V).
85°C
25°C
0
10
20
30
40
50
60
70
80
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
5
10
15
20
25
30
35
40
0 0.5 1 1.5 2 2.5
VOL (V)
IOL (mA)330
2545T–AVR–05/11
ATmega48/88/168
Figure 30-27. I/O pin sink current vs. output voltage (VCC = 1.8V).
30.9 Pin thresholds and hysteresis
Figure 30-28. I/O pin input threshold voltage vs. VCC (VIH, I/O pin read as '1').
85°C
25°C
-40°C
0
2
4
6
8
10
12
14
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
VOL (V)
IOL (mA)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)331
2545T–AVR–05/11
ATmega48/88/168
Figure 30-29. I/O pin input threshold voltage vs. VCC (VIL, I/O pin read as '0').
Figure 30-30. I/O pin input hystreresis vs. Vcc.
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.1
0.2
0.3
0.4
0.5
0.6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input hysteresis (V)332
2545T–AVR–05/11
ATmega48/88/168
Figure 30-31. Reset input threshold voltage vs. VCC (VIH, reset pin read as '1').
Figure 30-32. Reset input threshold voltage vs. VCC (VIL, reset pin read as '0').
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)
85°C
25°C
-40°C
0
0.5
1
1.5
2
2.5
3
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Threshold (V)333
2545T–AVR–05/11
ATmega48/88/168
Figure 30-33. Reset input pin hysteresis vs. VCC.
30.10 BOD thresholds and analog comparator offset
Figure 30-34. BOD thresholds vs. temperature (BODLEVEL is 4.3V).
VIL
0
100
200
300
400
500
600
2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Input hysteresis (mV)
4.2
4.25
4.3
4.35
4.4
4.45
4.5
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
Threshold (V)
Rising Vcc
Falling Vcc334
2545T–AVR–05/11
ATmega48/88/168
Figure 30-35. BOD thresholds vs. temperature (BODLEVEL is 2.7V).
Figure 30-36. BOD thresholds vs. temperature (BODLEVEL is 1.8V).
2.6
2.65
2.7
2.75
2.8
2.85
2.9
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
Threshold (V)
Rising Vcc
Falling Vcc
1.76
1.78
1.8
1.82
1.84
1.86
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
Threshold (V)
Rising Vcc
Falling Vcc335
2545T–AVR–05/11
ATmega48/88/168
Figure 30-37. Bandgap voltage vs. VCC.
Figure 30-38. Analog comparator offset voltage vs. common mode voltage (VCC = 5V).
-40°C
85°C
1.08
1.085
1.09
1.095
1.1
1.5 2 2.5 3 3.5 4 4.5 5 5.5 6
VCC (V)
Bandgap voltage (V)
-40°C
85°C
0
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
0.009
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Common Mode Voltage (V)
Analog comparator offset voltage (V)336
2545T–AVR–05/11
ATmega48/88/168
Figure 30-39. Analog comparator offset voltage vs. common mode voltage (VCC = 2.7V).
30.11 Internal oscillator speed
Figure 30-40. Watchdog oscillator frequency vs. VCC.
-40°C
85°C
0
0.5
1
1.5
2
2.5
3
3.5
4
0 0.5 1 1.5 2 2.5
Common Mode Voltage (V)
Analog comparator offset voltage
(mV)
85°C
25°C
-40°C
95
100
105
110
115
120
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (kHz)337
2545T–AVR–05/11
ATmega48/88/168
Figure 30-41. Calibrated 8MHz RC oscillator frequency vs. temperature.
Figure 30-42. Calibrated 8MHz RC oscillator frequency vs. VCC.
5.0V
2.7V
1.8V
7.4
7.5
7.6
7.7
7.8
7.9
8
8.1
8.2
8.3
8.4
-50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
Temperature (°C)
FRC (MHz)
85°C
25°C
-40°C
7.4
7.6
7.8
8
8.2
8.4
8.6
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
FRC (MHz)338
2545T–AVR–05/11
ATmega48/88/168
Figure 30-43. Calibrated 8MHz RC oscillator frequency vs. osccal value.
30.12 Current consumption of peripheral units
Figure 30-44. Brownout detector current vs. VCC.
85°C
25°C
-40°C
3.5
5.5
7.5
9.5
11.5
13.5
0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL VALUE
FRC (MHz)
85°C
25°C
-40°C
18
20
22
24
26
28
30
32
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)339
2545T–AVR–05/11
ATmega48/88/168
Figure 30-45. ADC current vs. VCC (AREF = AVCC).
Figure 30-46. AREF external reference current vs. VCC.
85°C
25°C
-40°C
150
200
250
300
350
400
450
500
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C
0
20
40
60
80
100
120
140
160
180
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)340
2545T–AVR–05/11
ATmega48/88/168
Figure 30-47. Analog comparator current vs. VCC.
Figure 30-48. Programming current vs. VCC.
85°C
25°C
-40°C
0
20
40
60
80
100
120
140
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (µA)
85°C
25°C
-40°C
0
2
4
6
8
10
12
14
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)
85°C
25°C
-40°C
0
2
4
6
8
10
12
14
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
ICC (mA)341
2545T–AVR–05/11
ATmega48/88/168
30.13 Current consumption in reset and reset pulse width
Figure 30-49. Reset supply current vs. VCC (0.1MHz - 1.0MHz, excluding current through the
reset pull-up).
Figure 30-50. Reset supply current vs. VCC (1MHz - 24MHz, excluding current through the reset
pull-up).
5.5V
5.0V
4.5V
4.0V
3.3V
2.7V
1.8V
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Frequency (MHz)
ICC (mA)
,
0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
0 4 8 12 16 20 24
Frequency (MHz)
ICC (mA)
2.7V
1.8V
3.3V
4.0V
4.5V
5.0V
5.5V342
2545T–AVR–05/11
ATmega48/88/168
Figure 30-51. Reset pulse width vs. VCC.
85°C
25°C
-40°C
0
500
1000
1500
2000
2500
1.5 2 2.5 3 3.5 4 4.5 5 5.5
VCC (V)
Pulsewidth (ns)343
2545T–AVR–05/11
ATmega48/88/168
31. Register summary
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page
(0xFF) Reserved – – – – – – – –
(0xFE) Reserved – – – – – – – –
(0xFD) Reserved – – – – – – – –
(0xFC) Reserved – – – – – – – –
(0xFB) Reserved – – – – – – – –
(0xFA) Reserved – – – – – – – –
(0xF9) Reserved – – – – – – – –
(0xF8) Reserved – – – – – – – –
(0xF7) Reserved – – – – – – – –
(0xF6) Reserved – – – – – – – –
(0xF5) Reserved – – – – – – – –
(0xF4) Reserved – – – – – – – –
(0xF3) Reserved – – – – – – – –
(0xF2) Reserved – – – – – – – –
(0xF1) Reserved – – – – – – – –
(0xF0) Reserved – – – – – – – –
(0xEF) Reserved – – – – – – – –
(0xEE) Reserved – – – – – – – –
(0xED) Reserved – – – – – – – –
(0xEC) Reserved – – – – – – – –
(0xEB) Reserved – – – – – – – –
(0xEA) Reserved – – – – – – – –
(0xE9) Reserved – – – – – – – –
(0xE8) Reserved – – – – – – – –
(0xE7) Reserved – – – – – – – –
(0xE6) Reserved – – – – – – – –
(0xE5) Reserved – – – – – – – –
(0xE4) Reserved – – – – – – – –
(0xE3) Reserved – – – – – – – –
(0xE2) Reserved – – – – – – – –
(0xE1) Reserved – – – – – – – –
(0xE0) Reserved – – – – – – – –
(0xDF) Reserved – – – – – – – –
(0xDE) Reserved – – – – – – – –
(0xDD) Reserved – – – – – – – –
(0xDC) Reserved – – – – – – – –
(0xDB) Reserved – – – – – – – –
(0xDA) Reserved – – – – – – – –
(0xD9) Reserved – – – – – – – –
(0xD8) Reserved – – – – – – – –
(0xD7) Reserved – – – – – – – –
(0xD6) Reserved – – – – – – – –
(0xD5) Reserved – – – – – – – –
(0xD4) Reserved – – – – – – – –
(0xD3) Reserved – – – – – – – –
(0xD2) Reserved – – – – – – – –
(0xD1) Reserved – – – – – – – –
(0xD0) Reserved – – – – – – – –
(0xCF) Reserved – – – – – – – –
(0xCE) Reserved – – – – – – – –
(0xCD) Reserved – – – – – – – –
(0xCC) Reserved – – – – – – – –
(0xCB) Reserved – – – – – – – –
(0xCA) Reserved – – – – – – – –
(0xC9) Reserved – – – – – – – –
(0xC8) Reserved – – – – – – – –
(0xC7) Reserved – – – – – – – –
(0xC6) UDR0 USART I/O data register 190
(0xC5) UBRR0H USART baud rate register high 194
(0xC4) UBRR0L USART baud rate register low 194
(0xC3) Reserved – – – – – – – –
(0xC2) UCSR0C UMSEL01 UMSEL00 UPM01 UPM00 USBS0 UCSZ01 /UDORD0 UCSZ00 / UCPHA0 UCPOL0 192/207
(0xC1) UCSR0B RXCIE0 TXCIE0 UDRIE0 RXEN0 TXEN0 UCSZ02 RXB80 TXB80 191
(0xC0) UCSR0A RXC0 TXC0 UDRE0 FE0 DOR0 UPE0 U2X0 MPCM0 190344
2545T–AVR–05/11
ATmega48/88/168
(0xBF) Reserved – – – – – – – –
(0xBE) Reserved – – – – – – – –
(0xBD) TWAMR TWAM6 TWAM5 TWAM4 TWAM3 TWAM2 TWAM1 TWAM0 – 239
(0xBC) TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN – TWIE 236
(0xBB) TWDR 2-wire serial interface data register 238
(0xBA) TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE 239
(0xB9) TWSR TWS7 TWS6 TWS5 TWS4 TWS3 – TWPS1 TWPS0 238
(0xB8) TWBR 2-wire serial interface bit rate register 236
(0xB7) Reserved – – – – – – –
(0xB6) ASSR – EXCLK AS2 TCN2UB OCR2AUB OCR2BUB TCR2AUB TCR2BUB 159
(0xB5) Reserved – – – – – – – –
(0xB4) OCR2B Timer/Counter2 output compare register B 158
(0xB3) OCR2A Timer/Counter2 output compare register A 157
(0xB2) TCNT2 Timer/Counter2 (8-bit) 157
(0xB1) TCCR2B FOC2A FOC2B – – WGM22 CS22 CS21 CS20 156
(0xB0) TCCR2A COM2A1 COM2A0 COM2B1 COM2B0 – – WGM21 WGM20 153
(0xAF) Reserved – – – – – – – –
(0xAE) Reserved – – – – – – – –
(0xAD) Reserved – – – – – – – –
(0xAC) Reserved – – – – – – – –
(0xAB) Reserved – – – – – – – –
(0xAA) Reserved – – – – – – – –
(0xA9) Reserved – – – – – – – –
(0xA8) Reserved – – – – – – – –
(0xA7) Reserved – – – – – – – –
(0xA6) Reserved – – – – – – – –
(0xA5) Reserved – – – – – – – –
(0xA4) Reserved – – – – – – – –
(0xA3) Reserved – – – – – – – –
(0xA2) Reserved – – – – – – – –
(0xA1) Reserved – – – – – – – –
(0xA0) Reserved – – – – – – – –
(0x9F) Reserved – – – – – – – –
(0x9E) Reserved – – – – – – – –
(0x9D) Reserved – – – – – – – –
(0x9C) Reserved – – – – – – – –
(0x9B) Reserved – – – – – – – –
(0x9A) Reserved – – – – – – – –
(0x99) Reserved – – – – – – – –
(0x98) Reserved – – – – – – – –
(0x97) Reserved – – – – – – – –
(0x96) Reserved – – – – – – – –
(0x95) Reserved – – – – – – – –
(0x94) Reserved – – – – – – – –
(0x93) Reserved – – – – – – – –
(0x92) Reserved – – – – – – – –
(0x91) Reserved – – – – – – – –
(0x90) Reserved – – – – – – – –
(0x8F) Reserved – – – – – – – –
(0x8E) Reserved – – – – – – – –
(0x8D) Reserved – – – – – – – –
(0x8C) Reserved – – – – – – – –
(0x8B) OCR1BH Timer/Counter1 - output compare register B high byte 134
(0x8A) OCR1BL Timer/Counter1 - output compare register B low byte 134
(0x89) OCR1AH Timer/Counter1 - output compare register A high byte 134
(0x88) OCR1AL Timer/Counter1 - output compare register A low byte 134
(0x87) ICR1H Timer/Counter1 - input capture register high byte 135
(0x86) ICR1L Timer/Counter1 - input capture register low byte 135
(0x85) TCNT1H Timer/Counter1 - counter register high byte 134
(0x84) TCNT1L Timer/Counter1 - counter register low byte 134
(0x83) Reserved – – – – – – – –
(0x82) TCCR1C FOC1A FOC1B – – – – – – 133
(0x81) TCCR1B ICNC1 ICES1 – WGM13 WGM12 CS12 CS11 CS10 132
(0x80) TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 – – WGM11 WGM10 130
(0x7F) DIDR1 – – – – – – AIN1D AIN0D 243
(0x7E) DIDR0 – – ADC5D ADC4D ADC3D ADC2D ADC1D ADC0D 259
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page345
2545T–AVR–05/11
ATmega48/88/168
(0x7D) Reserved – – – – – – – –
(0x7C) ADMUX REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 255
(0x7B) ADCSRB – ACME – – – ADTS2 ADTS1 ADTS0 258
(0x7A) ADCSRA ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 256
(0x79) ADCH ADC data register high byte 258
(0x78) ADCL ADC data register low byte 258
(0x77) Reserved – – – – – – – –
(0x76) Reserved – – – – – – – –
(0x75) Reserved – – – – – – – –
(0x74) Reserved – – – – – – – –
(0x73) Reserved – – – – – – – –
(0x72) Reserved – – – – – – – –
(0x71) Reserved – – – – – – – –
(0x70) TIMSK2 – – – – – OCIE2B OCIE2A TOIE2 158
(0x6F) TIMSK1 – – ICIE1 – – OCIE1B OCIE1A TOIE1 135
(0x6E) TIMSK0 – – – – – OCIE0B OCIE0A TOIE0 106
(0x6D) PCMSK2 PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 PCINT18 PCINT17 PCINT16 70
(0x6C) PCMSK1 – PCINT14 PCINT13 PCINT12 PCINT11 PCINT10 PCINT9 PCINT8 70
(0x6B) PCMSK0 PCINT7 PCINT6 PCINT5 PCINT4 PCINT3 PCINT2 PCINT1 PCINT0 70
(0x6A) Reserved – – – – – – – –
(0x69) EICRA – – – – ISC11 ISC10 ISC01 ISC00 67
(0x68) PCICR – – – – – PCIE2 PCIE1 PCIE0
(0x67) Reserved – – – – – – – –
(0x66) OSCCAL Oscillator calibration register 37
(0x65) Reserved – – – – – – – –
(0x64) PRR PRTWI PRTIM2 PRTIM0 – PRTIM1 PRSPI PRUSART0 PRADC 41
(0x63) Reserved – – – – – – – –
(0x62) Reserved – – – – – – – –
(0x61) CLKPR CLKPCE – – – CLKPS3 CLKPS2 CLKPS1 CLKPS0 37
(0x60) WDTCSR WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 53
0x3F (0x5F) SREG I T H S V N Z C 11
0x3E (0x5E) SPH – – – – – (SP10) 5. SP9 SP8 13
0x3D (0x5D) SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 13
0x3C (0x5C) Reserved – – – – – – – –
0x3B (0x5B) Reserved – – – – – – – –
0x3A (0x5A) Reserved – – – – – – – –
0x39 (0x59) Reserved – – – – – – – –
0x38 (0x58) Reserved – – – – – – – –
0x37 (0x57) SPMCSR SPMIE (RWWSB)5. – (RWWSRE)5. BLBSET PGWRT PGERS SELFPRGEN 283
0x36 (0x56) Reserved – – – – – – – –
0x35 (0x55) MCUCR – – – PUD – – IVSEL IVCE
0x34 (0x54) MCUSR – – – – WDRF BORF EXTRF PORF
0x33 (0x53) SMCR – – – – SM2 SM1 SM0 SE 39
0x32 (0x52) Reserved – – – – – – – –
0x31 (0x51) Reserved – – – – – – – –
0x30 (0x50) ACSR ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0 242
0x2F (0x4F) Reserved – – – – – – – –
0x2E (0x4E) SPDR SPI data register 170
0x2D (0x4D) SPSR SPIF WCOL – – – – – SPI2X 169
0x2C (0x4C) SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 168
0x2B (0x4B) GPIOR2 General purpose I/O register 2 26
0x2A (0x4A) GPIOR1 General purpose I/O register 1 26
0x29 (0x49) Reserved – – – – – – – –
0x28 (0x48) OCR0B Timer/Counter0 output compare register B
0x27 (0x47) OCR0A Timer/Counter0 output compare register A
0x26 (0x46) TCNT0 Timer/Counter0 (8-bit)
0x25 (0x45) TCCR0B FOC0A FOC0B – – WGM02 CS02 CS01 CS00
0x24 (0x44) TCCR0A COM0A1 COM0A0 COM0B1 COM0B0 – – WGM01 WGM00
0x23 (0x43) GTCCR TSM – – – – – PSRASY PSRSYNC 139/160
0x22 (0x42) EEARH (EEPROM address register high byte) 5. 22
0x21 (0x41) EEARL EEPROM address register low byte 22
0x20 (0x40) EEDR EEPROM data register 22
0x1F (0x3F) EECR – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE 22
0x1E (0x3E) GPIOR0 General purpose I/O register 0 26
0x1D (0x3D) EIMSK – – – – – – INT1 INT0 68
0x1C (0x3C) EIFR – – – – – – INTF1 INTF0 68
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page346
2545T–AVR–05/11
ATmega48/88/168
Note: 1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses
should never be written.
2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these
registers, the value of single bits can be checked by using the SBIS and SBIC instructions.
3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI
instructions will only operate on the specified bit, and can therefore be used on registers containing such Status Flags. The
CBI and SBI instructions work with registers 0x00 to 0x1F only.
4. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used. When addressing I/O
Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. The Atmel
ATmega48/88/168 is a complex microcontroller with more peripheral units than can be supported within the 64 location
reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the
ST/STS/STD and LD/LDS/LDD instructions can be used.
5. Only valid for ATmega88/168
0x1B (0x3B) PCIFR – – – – – PCIF2 PCIF1 PCIF0
0x1A (0x3A) Reserved – – – – – – – –
0x19 (0x39) Reserved – – – – – – – –
0x18 (0x38) Reserved – – – – – – – –
0x17 (0x37) TIFR2 – – – – – OCF2B OCF2A TOV2 158
0x16 (0x36) TIFR1 – – ICF1 – – OCF1B OCF1A TOV1 136
0x15 (0x35) TIFR0 – – – – – OCF0B OCF0A TOV0
0x14 (0x34) Reserved – – – – – – – –
0x13 (0x33) Reserved – – – – – – – –
0x12 (0x32) Reserved – – – – – – – –
0x11 (0x31) Reserved – – – – – – – –
0x10 (0x30) Reserved – – – – – – – –
0x0F (0x2F) Reserved – – – – – – – –
0x0E (0x2E) Reserved – – – – – – – –
0x0D (0x2D) Reserved – – – – – – – –
0x0C (0x2C) Reserved – – – – – – – –
0x0B (0x2B) PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1 PORTD0 88
0x0A (0x2A) DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0 88
0x09 (0x29) PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0 88
0x08 (0x28) PORTC – PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1 PORTC0 87
0x07 (0x27) DDRC – DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0 87
0x06 (0x26) PINC – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 87
0x05 (0x25) PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0 87
0x04 (0x24) DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0 87
0x03 (0x23) PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0 87
0x02 (0x22) Reserved – – – – – – – –
0x01 (0x21) Reserved – – – – – – – –
0x0 (0x20) Reserved – – – – – – – –
Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page347
2545T–AVR–05/11
ATmega48/88/168
32. Instruction set summary
Mnemonics Operands Description Operation Flags #Clocks
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add two registers Rd ← Rd + Rr Z, C, N, V, H 1
ADC Rd, Rr Add with carry two registers Rd ← Rd + Rr + C Z, C, N, V, H 1
ADIW Rdl,K Add immediate to word Rdh:Rdl ← Rdh:Rdl + K Z, C, N, V, S 2
SUB Rd, Rr Subtract two registers Rd ← Rd - Rr Z, C, N, V, H 1
SUBI Rd, K Subtract constant from register Rd ← Rd - K Z, C, N, V, H 1
SBC Rd, Rr Subtract with carry two registers Rd ← Rd - Rr - C Z, C, N, V, H 1
SBCI Rd, K Subtract with carry constant from reg. Rd ← Rd - K - C Z, C, N, V, H 1
SBIW Rdl,K Subtract immediate from Word Rdh:Rdl ← Rdh:Rdl - K Z, C, N, V, S 2
AND Rd, Rr Logical AND registers Rd ← Rd • Rr Z, N, V 1
ANDI Rd, K Logical AND register and constant Rd ← Rd • K Z, N, V 1
OR Rd, Rr Logical OR registers Rd ← Rd v Rr Z, N, V 1
ORI Rd, K Logical OR register and constant Rd ← Rd v K Z, N, V 1
EOR Rd, Rr Exclusive OR registers Rd ← Rd ⊕ Rr Z, N, V 1
COM Rd One’s complement Rd ← 0xFF − Rd Z, C, N, V 1
NEG Rd Two’s complement Rd ← 0x00 − Rd Z, C, N, V, H 1
SBR Rd,K Set bit(s) in register Rd ← Rd v K Z, N, V 1
CBR Rd,K Clear bit(s) in register Rd ← Rd • (0xFF - K) Z, N, V 1
INC Rd Increment Rd ← Rd + 1 Z, N, V 1
DEC Rd Decrement Rd ← Rd − 1 Z, N, V 1
TST Rd Test for zero or minus Rd ← Rd • Rd Z, N, V 1
CLR Rd Clear register Rd ← Rd ⊕ Rd Z, N, V 1
SER Rd Set register Rd ← 0xFF None 1
MUL Rd, Rr Multiply unsigned R1:R0 ← Rd x Rr Z, C 2
MULS Rd, Rr Multiply signed R1:R0 ← Rd x Rr Z, C 2
MULSU Rd, Rr Multiply signed with unsigned R1:R0 ← Rd x Rr Z, C 2
FMUL Rd, Rr Fractional multiply unsigned R1:R0 ← (Rd x Rr) << 1 Z, C 2
FMULS Rd, Rr Fractional multiply signed R1:R0 ← (Rd x Rr) << 1 Z, C 2
FMULSU Rd, Rr Fractional multiply signed with unsigned R1:R0 ← (Rd x Rr) << 1 Z, C 2
BRANCH INSTRUCTIONS
RJMP k Relative jump PC ← PC + k + 1 None 2
IJMP Indirect jump to (Z) PC ← Z None 2
JMP(1) k Direct jump PC ← k None 3
RCALL k Relative subroutine call PC ← PC + k + 1 None 3
ICALL Indirect call to (Z) PC ← Z None 3
CALL(1) k Direct subroutine call PC ← k None 4
RET Subroutine return PC ← STACK None 4
RETI Interrupt return PC ← STACK I 4
CPSE Rd,Rr Compare, skip if equal if (Rd = Rr) PC ← PC + 2 or 3 None 1/2/3
CP Rd,Rr Compare Rd − Rr Z, N, V, C, H 1
CPC Rd,Rr Compare with carry Rd − Rr − C Z, N, V, C, H 1
CPI Rd,K Compare register with immediate Rd − K Z, N, V, C, H 1
SBRC Rr, b Skip if bit in register cleared if (Rr(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBRS Rr, b Skip if bit in register is set if (Rr(b)=1) PC ← PC + 2 or 3 None 1/2/3
SBIC P, b Skip if bit in I/O register cleared if (P(b)=0) PC ← PC + 2 or 3 None 1/2/3
SBIS P, b Skip if bit in I/O register is set if (P(b)=1) PC ← PC + 2 or 3 None 1/2/3
BRBS s, k Branch if status flag set if (SREG(s) = 1) then PC←PC+k + 1 None 1/2
BRBC s, k Branch if status flag cleared if (SREG(s) = 0) then PC←PC+k + 1 None 1/2
BREQ k Branch if equal if (Z = 1) then PC ← PC + k + 1 None 1/2
BRNE k Branch if not equal if (Z = 0) then PC ← PC + k + 1 None 1/2
BRCS k Branch if carry set if (C = 1) then PC ← PC + k + 1 None 1/2
BRCC k Branch if carry cleared if (C = 0) then PC ← PC + k + 1 None 1/2
BRSH k Branch if same or higher if (C = 0) then PC ← PC + k + 1 None 1/2
BRLO k Branch if lower if (C = 1) then PC ← PC + k + 1 None 1/2
BRMI k Branch if minus if (N = 1) then PC ← PC + k + 1 None 1/2
BRPL k Branch if plus if (N = 0) then PC ← PC + k + 1 None 1/2
BRGE k Branch if greater or equal, signed if (N ⊕ V= 0) then PC ← PC + k + 1 None 1/2
BRLT k Branch if less than zero, signed if (N ⊕ V= 1) then PC ← PC + k + 1 None 1/2
BRHS k Branch if half carry flag set if (H = 1) then PC ← PC + k + 1 None 1/2
BRHC k Branch if half carry flag cleared if (H = 0) then PC ← PC + k + 1 None 1/2
BRTS k Branch if T flag set if (T = 1) then PC ← PC + k + 1 None 1/2
BRTC k Branch if T flag cleared if (T = 0) then PC ← PC + k + 1 None 1/2
BRVS k Branch if overflow flag is set if (V = 1) then PC ← PC + k + 1 None 1/2
BRVC k Branch if overflow flag is cleared if (V = 0) then PC ← PC + k + 1 None 1/2348
2545T–AVR–05/11
ATmega48/88/168
BRIE k Branch if interrupt enabled if ( I = 1) then PC ← PC + k + 1 None 1/2
BRID k Branch if interrupt disabled if ( I = 0) then PC ← PC + k + 1 None 1/2
BIT AND BIT-TEST INSTRUCTIONS
SBI P,b Set bit in I/O register I/O(P,b) ← 1 None 2
CBI P,b Clear bit in I/O register I/O(P,b) ← 0 None 2
LSL Rd Logical shift left Rd(n+1) ← Rd(n), Rd(0) ← 0 Z, C, N, V 1
LSR Rd Logical shift right Rd(n) ← Rd(n+1), Rd(7) ← 0 Z, C, N, V 1
ROL Rd Rotate left through carry Rd(0)←C,Rd(n+1)← Rd(n),C←Rd(7) Z, C, N, V 1
ROR Rd Rotate right through carry Rd(7)←C,Rd(n)← Rd(n+1),C←Rd(0) Z, C, N, V 1
ASR Rd Arithmetic shift right Rd(n) ← Rd(n+1), n=0..6 Z, C, N, V 1
SWAP Rd Swap nibbles Rd(3..0)←Rd(7..4),Rd(7..4)←Rd(3..0) None 1
BSET s Flag set SREG(s) ← 1 SREG(s) 1
BCLR s Flag clear SREG(s) ← 0 SREG(s) 1
BST Rr, b Bit store from register to T T ← Rr(b) T 1
BLD Rd, b Bit load from T to register Rd(b) ← T None 1
SEC Set carry C ← 1 C1
CLC Clear carry C ← 0 C 1
SEN Set negative flag N ← 1 N1
CLN Clear negative flag N ← 0 N 1
SEZ Set zero flag Z ← 1 Z1
CLZ Clear zero flag Z ← 0 Z 1
SEI Global interrupt enable I ← 1 I1
CLI Global interrupt disable I ← 0 I 1
SES Set signed test flag S ← 1 S1
CLS Clear signed test flag S ← 0 S 1
SEV Set Twos complement overflow V ← 1 V1
CLV Clear Twos complement overflow V ← 0 V 1
SET Set T in SREG T ← 1 T1
CLT Clear T in SREG T ← 0 T 1
SEH Set half carry flag in SREG H ← 1 H1
CLH Clear half carry flag in SREG H ← 0 H 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Move between registers Rd ← Rr None 1
MOVW Rd, Rr Copy register Word Rd+1:Rd ← Rr+1:Rr None 1
LDI Rd, K Load immediate Rd ← K None 1
LD Rd, X Load indirect Rd ← (X) None 2
LD Rd, X+ Load indirect and post-inc. Rd ← (X), X ← X + 1 None 2
LD Rd, - X Load indirect and pre-dec. X ← X - 1, Rd ← (X) None 2
LD Rd, Y Load indirect Rd ← (Y) None 2
LD Rd, Y+ Load indirect and post-inc. Rd ← (Y), Y ← Y + 1 None 2
LD Rd, - Y Load indirect and pre-dec. Y ← Y - 1, Rd ← (Y) None 2
LDD Rd,Y+q Load indirect with displacement Rd ← (Y + q) None 2
LD Rd, Z Load indirect Rd ← (Z) None 2
LD Rd, Z+ Load indirect and post-inc. Rd ← (Z), Z ← Z+1 None 2
LD Rd, -Z Load indirect and pre-dec. Z ← Z - 1, Rd ← (Z) None 2
LDD Rd, Z+q Load indirect with displacement Rd ← (Z + q) None 2
LDS Rd, k Load direct from SRAM Rd ← (k) None 2
ST X, Rr Store indirect (X) ← Rr None 2
ST X+, Rr Store indirect and post-inc. (X) ← Rr, X ← X + 1 None 2
ST - X, Rr Store indirect and pre-dec. X ← X - 1, (X) ← Rr None 2
ST Y, Rr Store indirect (Y) ← Rr None 2
ST Y+, Rr Store indirect and post-inc. (Y) ← Rr, Y ← Y + 1 None 2
ST - Y, Rr Store indirect and pre-dec. Y ← Y - 1, (Y) ← Rr None 2
STD Y+q,Rr Store indirect with displacement (Y + q) ← Rr None 2
ST Z, Rr Store indirect (Z) ← Rr None 2
ST Z+, Rr Store indirect and post-inc. (Z) ← Rr, Z ← Z + 1 None 2
ST -Z, Rr Store indirect and pre-dec. Z ← Z - 1, (Z) ← Rr None 2
STD Z+q,Rr Store indirect with displacement (Z + q) ← Rr None 2
STS k, Rr Store direct to SRAM (k) ← Rr None 2
LPM Load program memory R0 ← (Z) None 3
LPM Rd, Z Load program memory Rd ← (Z) None 3
LPM Rd, Z+ Load program memory and post-inc Rd ← (Z), Z ← Z+1 None 3
SPM Store program memory (Z) ← R1:R0 None -
IN Rd, P In port Rd ← P None 1
OUT P, Rr Out port P ← Rr None 1
PUSH Rr Push register on stack STACK ← Rr None 2
Mnemonics Operands Description Operation Flags #Clocks349
2545T–AVR–05/11
ATmega48/88/168
Note: 1. These instructions are only available in Atmel ATmega168.
POP Rd Pop register from stack Rd ← STACK None 2
MCU CONTROL INSTRUCTIONS
NOP No operation None 1
SLEEP Sleep (See specific descr. for sleep function) None 1
WDR Watchdog reset (See specific descr. for WDR/timer) None 1
BREAK Break For on-chip debug only None N/A
Mnemonics Operands Description Operation Flags #Clocks350
2545T–AVR–05/11
ATmega48/88/168
33. Ordering information
33.1 Atmel ATmega48
Note: 1. This device can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information
and minimum quantities.
2. Pb-free packaging alternative, complies to the European Directive for Restriction of Hazardous Substances (RoHS directive).
Also Halide free and fully Green.
3. See Figure 29-1 on page 305 and Figure 29-2 on page 305.
4. NiPdAu lead finish.
5. Tape & Reel.
Speed (MHz) Power supply Ordering code(2) Package(1) Operational range
10(3) 1.8V - 5.5V
ATmega48V-10AUR(5)
ATmega48V-10MUR(5)
ATmega48V-10AU
ATmega48V-10MMU
ATmega48V-10MMUR(5)
ATmega48V-10MMH(4)
ATmega48V-10MMHR(4)(5)
ATmega48V-10MU
ATmega48V-10PU