scieee AI-readable full text Open interactive document viewer

Estudi de possibles aplicacions de blockchain en el disseny de projectes d'enginyeria de la construcció

Colomé Diaz, Adrià

Abstract

Són cada vegada més les construccions que es realitzen a través d’un model BIM, en el que interactuen totes les parts implicades en el procés constructiu, i cada vegada més les aplicacions de la tecnologia Blockchain a tot tipus de sectors; és per això que en aquest projecte es presenta un cas d’aplicació de la tecnologia Blockchain a BIM. Aquest projecte es centra més concretament en la sisena dimensió de BIM (manteniment i gestió del cicle de vida), és per això que es presenta un cas d’aplicació en el que s’estudiarà la viabilitat i el potencial de l'ús de contractes intel·ligents automàtics de Ethereum en operacions de manteniment elèctric en edificis. En particular, el document aborda les oportunitats d’instal·lar sistemes sensorials connectats en una xarxa IoT (Internet of Things) de generació automàtica de contractes intel·ligents i actualitzacions automàtiques del model BIM, per a millorar l'eficiència operativa, augmentar la satisfacció del client i reduir els costos operatius per a les empreses proveïdores del manteniment. A través de l'avaluació d'un estudi de cas existent, aquest document presenta un argument per a l'ús de la tecnologia de llibre major distribuït per a resoldre la gestió automatitzada basada en contractes intel·ligents de tals operacions. A més, el document proposa un sistema hardware de detecció de tot tipus d’averies elèctriques en un Smart Building. I un algoritme per a la generació automàtica d’un contracte intel·ligent que s’executa a partir d’aquesta senyal booleana de detecció de falla. L'enfocament proposat ofereix millores respecte als sistemes convencionals de gestió del manteniment que podrien suposar un estalvi de costos i una millora dels processos. Com a resultat, aquest document proporciona una avaluació exhaustiva dels beneficis potencials, consideracions i desafiaments associats amb la utilització de contractes intel·ligents automàtics de Ethereum per a les operacions de manteniment elèctric en edificis. Amb la relació evident que tenen aquests dos conceptes amb BIM i Smart Building.

Full text

- Projecte d’ap licació de tec nologia Blockchai n a dissenys de con strucció basats en B IM – - Annexo s - Estudi de possibles aplicacions de blockchain en el disseny de projectes d'enginyeria de l a construcció Document: Annexos Autor/Autora : Adrià Colomé Director/Directo ra - Codi rector/Co directora: Lluis Gil Marcel Macarulla Titulaci ó: Grau en Enginyeria en Tecnolo gies Industrials Convocatòria: Tardor  2018 Microchip Technology Inc. Data Sheet Co mplete DS40002061A-page 1 Features  High Perform ance, Low Power A VR ® 8-Bit Microcon troller Fam ily  Advanced RISC Architecture  131 Powerful In structions – Mo st Single Clock Cycle Execution  32 x 8 G eneral Purp ose Working Regis ters  Fully S tatic Operation  Up to 20 MIPS Throughpu t at 20MHz  On-chip 2-cycle Multiplier  High Endura nce Non-volatile Memory Segmen ts  4/8/16/3 2KBytes of In-System Self-Progr ammable F lash prog ram me mory  256/512/512/1KBytes EEPROM  512/1K/1K/2KBytes Internal SRAM  W rite/Erase Cycles: 10, 000 Flash/100,000 EEPROM  Data retention: 20 year s at 85° C/100 years at 25°C (1)  Optional Boot Code Section with In dependent Lo ck Bits  In-System Programming by On-chip Boot Program  T rue Read-While-W rite Operation  Program ming Lock for Software Security  QT ouch ® lib rary su pport  Capacitive touch buttons, sliders an d wheels  QT ouch and QMatrix™ acquisition  Up to 64 sense channels  Peripher al Features  T wo 8 -bit T imer/Counters with Sep arate Pr escaler and Comp are Mode  One 16-bit T imer/Cou nter with Separ ate Prescaler , Compar e Mode, and Captur e Mode megaA VR ® Data Sheet A Tmega48A/P A/88A/P A/168A/P A/328/P Introduction The A Tmega48A/P A/88A/P A/168A/P A/328/P is a low powe r , CMOS 8-bit microcontroll ers based on the AV R ® enha nced RISC architecture. By executing instr uct ions in a single clock cycle, the devices achieve CPU throughput approaching one million instructions per second (MIPS) per mega hertz, allowing the sys- tem designer to optimize powe r c onsump tion versus pr ocessing speed.  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 2 A Tmega48A/P A/88A/P A/168A/P A/328/P  Real T ime Counter wit h Sep arate Oscillator  Six PWM Channels  8-channel 10-bit ADC in TQFP an d QFN/MLF pa ckage  T emperature Mea surement  6-channel 10-bit ADC in PD IP Package  T emperature Mea surement  Programmab le Serial USAR T  Master/Slave SPI Serial Interfac e  Byte-oriented 2-wire Seri al Interface (Philips I 2 C comp atible)  Programmable W atchdog T imer with Separate On-chip Oscillator  On-chip Analog Comp arator  Interrupt and W ake-u p on Pin Change  S p ecial Microc ontroller Features  Power-on Reset and Prog rammable Brown -out Detection  Internal Calibrated Oscillator  External and In ternal Inter rupt Sources  Six Sleep Modes: Id le, ADC Noise Reduction , Power-save, Power-down, S tand by , and Extended S tandby  I/O and Packages  23 Programma ble I/O Lines  28-pin PDIP , 32-le ad TQFP , 28-pad QFN/MLF and 32-p ad QFN/MLF  Operating V olt age:  1.8 - 5.5V  T emperature Rang e:  -40°C to 85° C  S peed Grad e:  0 - [email protected] - 5.5V , 0 - 1 0MHz@2. 7 - 5.5.V , 0 - 20MHz @ 4.5 - 5.5V  Power Consumption at 1MHz, 1.8V , 25°C  Active M ode: 0.2m A  Power-down Mo de: 0.1µA • Power-s ave Mod e: 0.75µA ( Including 32 kHz RTC)  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 3 A Tmega48A/P A/88A/P A/168A/P A/328/P T able of Content s 1 Pin Configurations ........ ........ ......... ........ ......... ........ ........ ............ ........ ........ ......... ........ ....... 12 1.1 Pin Descriptions ......... ............. ............. ............. ................ ............. ............. ..... 13 2O v e r v i e w .......... ......... ........ ........... ......... ........ ......... ........ ........ ......... ........ ......... ........ ........ .... ...... 15 2.1 Block Diagram ........ ............. ............. ............ ............. ............. ............. ............ 15 2.2 Comparison Between Processors ............. ................ ............. ............. ............ 16 3 Resources ......... ......... ........ ........ ............ ........ ........ ......... ........ ......... ........ ........ ......... ........ ..... .. 1 7 4 Data Retention ........... ......... ........ ......... ........... ........ ......... ........ ........ ......... ........ ......... ........ .... 17 5 About Code Examples ........... ......... ........ ........ ......... ........ ......... ........ ........ ......... ........ ....... 17 6 Capacitive Touch Sensing ........... ........ ........ ......... ........ ......... ........ ........... ......... ........ .... 17 7 AVR CPU Core .............. ......... ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... ........ .... 18 7.1 Overview .......... ............. ............. ............. ............. ............. ............. ............. ..... 18 7.2 ALU – Arithmetic Logic U nit ................. ............. ................ ............. ............. ..... 19 7.3 Status Register ....... ............. ............. ............ ............. ............. ............. ............ 19 7.4 General Purpose Register File ............ ............. ................ ............. ............. ..... 20 7.5 Stack Pointer ................... ............. ............. ............. ............. ............. ............. .. 22 7.6 Instruction Execution Timing ............ ................ ............. ............. ............ ......... 23 7.7 Reset and Interrupt Handling ..... ............. ................ ............. ............. ............. .. 23 8 AVR Memories .............. ......... ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... ........ .... 26 8.1 Overview .......... ............. ............. ............. ............. ............. ............. ............. ..... 26 8.2 In-System Reprogrammable Flash Program Memory ................ ................ ..... 26 8.3 SRAM Data Memory ............... ............. ............. ............. ............. ............ ......... 28 8.4 EEPROM Data Memo ry ............... ................ ................. ............. ............ ......... 29 8.5 I/O Memory ......... ............. ............. ............. ............. ................ ............. ............ 30 8.6 Register D escription .................. ............. ............. ............. ............. ............. ..... 31 9 System Clock and Clock Options ............ ......... ........ ......... ........ ........ ......... ........ ....... 36 9.1 Clock Systems and their Distribution ... ...... .......... ............. ............. ............. ..... 36 9.2 Clock Sources ........... ............. ............. ............. ............. ............. ............ ......... 37 9.3 Low Power Crystal Oscillat or ............... ............. ............. ............. ............ ......... 38 9.4 Full Swing C rystal Oscillator ......... ............. ............. ............. ............. ............... 39 9.5 Low Frequency Cryst al Oscillator ..... ............ ............. ............. ................ ......... 42 9.6 Calibrated Internal RC Oscillator ............ ................ ............. ............. ............. .. 43 9.7 128kHz Internal Os cillator ................ ............ ............. ............. ............. ............ 43  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 4 A Tmega48A/P A/88A/P A/168A/P A/328/P 9.8 External Clock .... ............. ................. ............ ............. ............. ............. ............ 44 9.9 Clock Output Buffer ......... ............. .......... ............. ............. ............. ............. ..... 45 9.10 Timer/Counter Oscillat or .. ............. ....... ... ............. ............. .......... ............ ......... 45 9.11 System Clock Prescaler ......... ............. ............. ............. ............. ............ ......... 45 9.12 Register Des cription ........ ............. ............. ............. ............. ............. ............. .. 46 10 Power Management and Sleep Modes .......... ........ ......... ........ ........ ......... ........ ....... 48 10.1 Sleep Modes . ............. ............. ............. ............. ................ ............. ............. ..... 48 10.2 BOD Disable (1) ....... ............. ............. ............ ............. ............. ............. ............ 49 10.3 Idle Mode ... ............. ............. ............. ............ ............. ............. ............. ............ 49 10.4 ADC Noise Reduction Mode ................ ... .......... ............. ............. ......... ............ 49 10.5 Power-down Mode .................. ............. ............. ............. ................ ............. ..... 49 10.6 Power-save Mode ................ ............. ............ ............. ................. ............ ......... 50 10.7 Standby Mode ................. ............. ............. ............. ............. ............. ............. .. 50 10.8 Extended Standby Mode ........ ............. ............. ................ ............. ............. ..... 51 10.9 Power Reduction Register ...... ............. ................ ............. ............. ............. ..... 51 10.10 Minimizing Power Consumption .......... ......... ............. ............. ............. ............ 51 10.11 Register Des cription ........ ............. ............. ............. ............. ............. ............. .. 53 11 System Control and Reset ........... ........ ........ ......... ........ ......... ........ ........ ......... ........... .... 56 11.1 Resetting the AVR ............... ............. ............ ............. ............. ............. ............ 56 11.2 Reset Sources .............. ................ ....... ... ............. ............. ............. ............. ..... 56 11.3 Power-on Reset .. ............. ................. ............ ............. ............. ............. ............ 57 11.4 External Reset ........... ............. ............. ................ ............. ............. ............. ..... 58 11.5 Brown-out Detection ..... ............. ............. ................ ............. ............. ............. .. 58 11.6 Watchdog System Reset ........ ............. ................ ............. ............. ............. ..... 59 11.7 Internal Voltage Refere nce ........... .......... ............. ............. ............. ............. ..... 59 11.8 Watchdog Timer ........ ................ ............. ............. ............. ............. ............. ..... 60 11.9 Register Description ............ ............. ............ ............. ............. ............. ............ 63 12 Interrupts ...... ......... ........ ............ ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... ....... .. ... 66 12.1 Interrupt Vector s in ATmega48A and ATmega48PA ..... ................ ............. ..... 66 12.2 Interrupt Vector s in ATmega88A and ATmega88PA ..... ................ ............. ..... 68 12.3 Interrupt Vector s in A Tmega168A and ATmega168PA .............. ................ ..... 71 12.4 Interrupt Vector s in A Tmega328 and ATmega328P ...................... ............. ..... 74 12.5 Register Description ............ ............. ............ ............. ............. ............. ............ 77 13 External Interrupts .............. ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... ........... . 79 13.1 Pin Change Interrupt Timing ............. ................ ............. ............. ............ ......... 79  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 5 A Tmega48A/P A/88A/P A/168A/P A/328/P 13.2 Register Description ............ ............. ............ ............. ............. ............. ............ 80 14 I/O-Ports ........... ......... ........ ......... ........ ........... ......... ........ ........ ......... ........ ......... ........ ........ ... ....... 84 14.1 Overview ............. ............. ............. ............. ............. ............. ............. ............. .. 84 14.2 Ports as General Digital I/O .... ............. ................ ............. ............. ............. ..... 85 14.3 Alternate Port Functions ............... ............. ............. ................ ............. ............ 89 14.4 Register Description ............ ............. ............ ............. ............. ............. .......... 100 15 8-bit Timer/Counter0 with PWM ..... ......... ........ ........ ............ ........ ........ ......... ........ ..... 102 15.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 102 15.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 102 15.3 Timer/Counter Clock S ources .......... ................ ............. ............. ............ ....... 103 15.4 Counter Unit ........... ...... ....... ............. ............ .......... ............. ............. ............. 103 15.5 Output Compare Unit .............. ............. ............. ............. ............. ................ ... 104 15.6 Compare Match Output Unit ......... ............. ................ ............. ............. .......... 106 15.7 Modes of Operat ion ................ ............. ............. ............. ............. ............ ....... 107 15.8 Timer/Counter Timing Diagrams ............ ............. ............. ............. ............. ... 111 15.9 Register Description ............ ............. ............ ............. ............. ............. .......... 113 16 16-bit Timer/Counter1 with PWM ........ ........ ......... ........ ........ ............ ........ ........ ........ 120 16.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 120 16.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 120 16.3 Accessing 16-bit Registers ..... ............. ................ ............. ............. ............. ... 122 16.4 Timer/Counter Clock S ources .......... ................ ............. ............. ............ ....... 125 16.5 Counter Unit ........... ...... ....... ............. ............ .......... ............. ............. ............. 125 16.6 Input Capture Unit ........ .......... ............. ............. ............. ............. ............ ....... 126 16.7 Output Compare Units ......... ............. ............ ................. ............. ............ ....... 12 8 16.8 Compare Match Output Unit ......... ............. ................ ............. ............. .......... 130 16.9 Modes of Operat ion ................ ............. ............. ............. ............. ............ ....... 131 16.10 Timer/Counter Timing Diagrams ...... ......... ............. .......... ............. ............. ... 138 16.11 Register Des cription ........ ............. ............. ............. ............. ............. ............. 140 17 Timer/Counter0 and Ti mer/Counter1 Prescalers .......... ......... ........ ........ ........ 147 17.1 Internal Clock Source ... ....... ............. ............ ............. ............. ............. .......... 147 17.2 Prescaler Reset ............ ............. ............. ............. ............. ............. ............. ... 147 17.3 External Clock Source ..... ................. ............ ............. ............. ............. .......... 147 17.4 Register Description ............ ............. ............ ............. ............. ............. .......... 149 18 8-bit Timer/Counter2 with PW M and Asynchronous Operation ...... ..... 150 18.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 150  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 6 A Tmega48A/P A/88A/P A/168A/P A/328/P 18.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 150 18.3 Timer/Counter Clock S ources .......... ................ ............. ............. ............ ....... 151 18.4 Counter Unit ........... ...... ....... ............. ............ .......... ............. ............. ............. 151 18.5 Output Compare Unit .............. ............. ............. ............. ............. ................ ... 152 18.6 Compare Match Output Unit ......... ............. ................ ............. ............. .......... 154 18.7 Modes of Operat ion ................ ............. ............. ............. ............. ............ ....... 155 18.8 Timer/Counter Timing Diagrams ............ ............. ............. ............. ............. ... 159 18.9 Asynchronous Operation of Timer/Co unter2 ............. ............. ................ ....... 160 18.10 Timer/Counter Prescaler .............. .... ...... ............. ............. ............. ............. ... 161 18.11 Register Des cription ........ ............. ............. ............. ............. ............. ............. 162 19 SPI – Serial Peripheral Interface .......... ........ ......... ........ ........ ......... ........ ......... .......... 169 19.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 169 19.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 169 19.3 SS Pin Func tionality .................. ............. ................ ............. ............. ............. 174 19.4 Data Modes ............ ............. ............. ............ ................. ............. ............ ....... 174 19.5 Register Description ............ ............. ............ ............. ............. ............. .......... 176 20 USART0 ......... ............ ........ ......... ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... .... ...... 179 20.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 179 20.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 179 20.3 Clock Generation ................. ............. ............ ................. ............. ............ ....... 180 20.4 Frame Formats ................ ............. ............. ............. ............. ............. ............. 183 20.5 USART Initialization ...... ............. ............. ............. ............. ............. ............. ... 184 20.6 Data Transmission – The USART Tran smitter ....... ............. ............. ............. 185 20.7 Data Reception – The USART Receiv er ... ............. ............. ............. ............. 188 20.8 Asynchronous Data Reception ......... ... ............. ............. ............. ............ ....... 192 20.9 Multi-processor Communication Mode ... ............. ............. ............. ............. ... 195 20.10 Examples of Baud Rate Setting ........ ...... ............. ............. ............. ......... ....... 196 20.11 Register Des cription ........ ............. ............. ............. ............. ............. ............. 200 21 USART in SP I Mode ............ ........ ........ ......... ........ ......... ........... ........ ......... ........ ........ ........ 205 21.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 205 21.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 205 21.3 Clock Generation ................. ............. ............ ................. ............. ............ ....... 205 21.4 SPI Data Modes and Timing ... ................ ............. ............. ............. ............. ... 20 6 21.5 Frame Formats ................ ............. ............. ............. ............. ............. ............. 206 21.6 Data Transfer ................... ............. ............. ............. ............. ............. ............. 209  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 7 A Tmega48A/P A/88A/P A/168A/P A/328/P 21.7 AVR USART MSPIM vs. AVR SPI ................... ............. ................ ............. ... 211 21.8 Register Description ............ ............. ............ ............. ............. ............. .......... 212 22 2-wire Seri al Interface ............... ........ ......... ........ ......... ........ ........ ......... ........ ......... ........ .. 215 22.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 215 22.2 2-wire Serial Interface Bus Definition ..... ............. ............. ............. ............. ... 215 22.3 Data Transfer and Fram e Format . ............. ............. ............. ............. ............. 216 22.4 Multi-master Bus Systems, Arbitratio n and Synchronization ............ ............. 21 9 22.5 Overview of the TWI Module ............ ............ ................. ............. ............ ....... 22 1 22.6 Using the TWI ............... ............. ............. ............. ............. ................ ............. 223 22.7 Transmission Modes ....... ............. ................ ............. ............. ............. .......... 225 22.8 Multi-master Systems and Arbitration ..... ................ ............. ............. ............. 238 22.9 Register Description ............ ............. ............ ............. ............. ............. .......... 239 23 Analog Comparator ............ ........ ........ ......... ........ ......... ........ ........ ......... ........ ......... ........ .. 243 23.1 Overview ............. ............. ............. ............. ............. ............. ............. ............. 243 23.2 Analog Comparator Mult iplexed Input ....... ............. ............. ................ .......... 243 23.3 Register Description ............ ............. ............ ............. ............. ............. .......... 244 24 Analog-to-Digital Converter ............. ......... ........ ........ ......... ........ ......... ........ ........ ........ 246 24.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 246 24.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 246 24.3 Starting a Conversion ............. ................ ............. ............. ............. ................ 248 24.4 Prescaling and Conversion Timing ............... ............. ............. ................ ....... 249 24.5 Changing Channel or Reference Sele ction .. ............. .......... ............. ............. 251 24.6 ADC Noise Canceler ....... ............. ............. ............. ............. ................ .......... 252 24.7 ADC Conversion Result ............. ............. ............. ............. ............. ............. ... 256 24.8 Temperature Measurement .......... ............. ................ ............. ............. .......... 256 24.9 Register Description ............ ............. ............ ............. ............. ............. .......... 257 25 debugWIRE On-chip Debug System ...... ......... ........ ......... ........ ........... ......... ........ .. 262 25.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 262 25.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 262 25.3 Physical Interface ......... ............. ............. ............. ............. ............. ................ 26 2 25.4 Software Break Points ..... ............. ............. ............. ............. ............. ............. 263 25.5 Limitations of debugWIRE ................ ............ ............. ................. ............ ....... 263 25.6 Register Description ............ ............. ............ ............. ............. ............. .......... 263 26 Self-Programming the Flash, ATmega 48A/48PA ............... ........ ......... ........ .. 264 26.1 Overview ............. ............. ............. ............. ............. ............. ............. ............. 264  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 8 A Tmega48A/P A/88A/P A/168A/P A/328/P 26.2 Addressing the Flash During Self-P rogramming .... ............. ............. ............. 265 26.3 Register Description ............ ............. ............ ............. ............. ............. .......... 270 27 Boot Loader Support – Read-W hile-Write Self-Programming .......... ..... 272 27.1 Features ....... ............. ............. ............. ............. ................ ............. ............. ... 272 27.2 Overview ............. ............. ............. ............. ............. ............. ............. ............. 272 27.3 Application and Boot Loader Flash Sections .... ................ ................ ............. 272 27.4 Read-While-Write and No Read-While-Write Flash Sections ........... ............. 273 27.5 Boot Loader Lock Bits ..... ................. ............ ............. ............. ............. .......... 275 27.6 Entering the Boot Loader Program ... ............ .......... ............. ............. ............. 276 27.7 Addressing the Flash During Self-P rogramming .... ............. ............. ............. 277 27.8 Self-Programming the Flash ............. ... ............. ............. ............. ............ ....... 278 27.9 Register Description ............ ............. ............ ............. ............. ............. .......... 287 28 Memory Programming ........... ......... ........ ........ ......... ........ ......... ........ ........ ......... ........ ..... 289 28.1 Program And Data Memory Lock Bits .......... ............. ................. ............ ....... 28 9 28.2 Fuse Bits .......... ............. ............. ............. ............. ............. ............. ......... ....... 290 28.3 Signature Bytes ......... ............. ............. ............. ............. ................ ............. ... 293 28.4 Calibration Byte ...... ............. ............. ............ ............. ............. ............. .......... 293 28.5 Page Size ........ ............. ............. ............. ............. ............. ............. ................ 294 28.6 Parallel Programming Parameters, Pin Mapping, and Commands ..... .......... 294 28.7 Parallel Programming ................ ................ ............. ............. ............. ............. 296 28.8 Serial Downloading .................... ....... ... ......... ............. ............. ............. .......... 303 29 Electrical Characteristics – (T A = -40°C to 85°C) ............. ........ ......... ........ ..... 308 29.1 Absolute Maximum Rati ngs* ............ ............ ............. ............. ............. .......... 308 29.2 DC Characteristics ........... ............. .... ......... ............. .......... ............. ............. ... 308 29.3 Speed Grades ........ ................ ............. ............. ............. ............. ............ ....... 312 29.4 Clock Characteristics ....... ............. ............. ............. ............. ................ .......... 313 29.5 System and Reset Characteristics ... ............ ............. .......... ............. ............. 314 29.6 SPI Timing Characteristics ..... .......... ... ......... ............. ............. ............. .......... 315 29.7 Two-wire Serial Interface Characterist ics ......... ............. ......... ............. .......... 317 29.8 ADC Characteristics .. ................ ....... ...... .......... ............. ............. ............ ....... 319 29.9 Parallel Programming Characteristics .... ............. ................ ............. ............. 320 30 Electrical Characteristi cs (TA = -40°C to 105°C) ........ ......... ........ ......... ........ .. 322 30.1 Absolute Maximum Rati ngs* ............ ............ ............. ............. ............. .......... 322 30.2 DC Characteristics ........... ............. .... ......... ............. .......... ............. ............. ... 322 31 Typical Characteristics – (T A = -40°C to 85°C) .... ........ ............ ........ ........ ........ 326 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 15 2. Overview The ATmega48A/PA/8 8A/PA/168 A/PA/328/P is a lo w-power CMOS 8- bi t microcontroll er based on the AVR enhanced RISC architecture. By executing powerf ul instructions in a single cloc k cycle, the ATmega48A/PA/88A/PA/1 68A/ PA/328/P achiev es throughputs appr oaching 1 MIPS pe r MHz allowing the system designer to optimize power consumptio n versus processing speed. 2.1 Block Diagram Figure 2-1 . Block Diagram The AVR core combines a rich in struction set with 32 ge neral purpo se working registers. All the 32 reg isters are directly co nnected to the Arit hmetic Logic Unit (ALU), allowing two independent regist ers to be accessed in one single instruction executed in one clock cycle. The resulti ng architecture is more code efficient while achieving throughputs up to ten tim es faster th an conventional CISC microcontrollers. POR T C (7) POR T B (8) POR T D (8) USAR T 0 8bit T/C 2 16bit T/C 1 8bit T/C 0 A/D Conv . Inter nal Bandgap Analog Comp . SPI TWI SRAM Flash EEPROM W atchdog Oscillator W atchdog Timer Oscillator Circuits / Clock Generation Po w e r Super vision POR / BOD & RESET VCC GND PROGRAM LOGIC debugWIRE 2 GND AREF AV C C D ATA B U S ADC[6..7] PC[0..6] PB[0..7] PD[0..7] 6 RESET XT AL[1..2] CPU A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 16 The ATmega48A/PA/88A/PA/168A/PA/3 28/P provides the following featur es: 4K /8Kbytes of In-Syst em Programmable Flash with Re ad-While-Write capabilitie s, 256/512/512/1K bytes EEPROM, 512/1K /1K/2Kbytes SRAM, 23 general purpose I/O lines, 3 2 general purpo se working registe rs, three flexible Timer/Co unters with compare modes, internal an d external interrupts, a seri al programmab le USART, a by te-o riented 2-wire Seria l Interface, an SPI serial port, a 6-channe l 10-bit ADC (8 channels in TQFP and QFN/MLF packages) , a programmable Watchdog Ti mer with internal Oscillator, and five soft ware selectable power s aving modes. The Idle mode stops the CPU while allowin g the SRAM, Timer/Counters, USART, 2-wire Serial Interface, SPI port, and interr upt system to continue func tioni ng. The Power- down mode sa ves th e register conten ts but freezes the Oscillator, disabling all othe r chip functions until the nex t interrupt or hardware reset. In Power-save mode, the asynchronous timer co ntinues to run, allowing the user to maintain a timer base while the rest of th e device is sleeping. The ADC Noise Reduction mod e stops the CPU and all I/O modules except asynchronous timer and ADC, to minimize switching noise dur ing ADC conversions. In Standby mode , the crystal/resona tor Oscillator is running while the rest of th e device is sleeping. This allows very fast start- up combined with low power consum ption. Microchip offers the QTou ch library for embedd ing capaciti ve touch buttons, sliders an d wheels functionality into AVR ® microcon trollers. The patented charge-tran sfer signal acquisition offers robust s ensing and inc ludes fully debounce d reporting of touch keys and includes Adjace nt Key Suppression ™ (AKS ™ ) techno logy for unambiguou s detectio n of key events. The easy-t o-use QT ouch Suite toolcha in allows you to explore, deve lop and debug yo ur own touch ap plications. The device is manufactu red using Microchip ’s high dens ity non-volatile memory te chnology. The On-ch ip ISP Flash allows the pr ogram memory to be reprogramm ed In-System through an SPI serial interface, by a conventional non-volatile mem ory programmer, or by an On-chip Boot pro gram running on the AVR core. The Boot program can use any interface to do wnload the application program in th e Application Flash memory. Software in the Boot Flash section will continue to run while the Applic ation Flash section is updated, providing true Read -While-W rite operation. By combining a n 8-bit RISC CP U with In-Syst em Self-Progr ammable F lash on a monolithic ch ip, the ATmega48A /PA/88A/PA/16 8A/PA/328/ P is a powerful microc ontroller that provides a highly flexible and cost effective soluti on to many embedded control applications. The ATmega48A/PA/88A/PA/168A/PA/3 28/P AVR is supported with a full suite of prog ram and system developm ent tools includ ing: C Compilers, Ma cro A ssemblers, Program Debugge r/Simulators, In-Circuit Emulators, and Eva luation kits. 2.2 Comp arison Between Processors The ATmega48A/PA/88A/PA/168A/ PA/328/P differ only in memory sizes, b oot loader support, a nd interr upt vector sizes. Table 2- 1 summarize s the different me mory and int errupt vector sizes for the devices. T able 2-1. Memory Size Summary Device Flash EEPROM RAM Interrupt V ector Size A Tmega48A 4KBytes 256Bytes 512Byte s 1 instruction word/vector A Tmega48P A 4KBytes 256Bytes 512Bytes 1 instruction word/vector A Tmega88A 8KBytes 512Bytes 1KBytes 1 instruction word/vector A Tmega88P A 8KBytes 512Bytes 1KBytes 1 instruction word/vector A Tmega168A 16KBytes 5 12Bytes 1KBytes 2 instruction words/vector A Tmega168P A 16KBytes 512Bytes 1KBytes 2 instruction words/vector A Tmega328 32KBytes 1KBytes 2KBytes 2 instruction words/vector A Tmega328P 32KBytes 1KBytes 2KBytes 2 instruction words/vector A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 17 ATmega48A/PA/88A/PA/1 68A/ PA/328/P support a real Read-While-Write Self-Pr ogramming mechanism. There is a separate Boot Loade r Section, and the SPM instr uction can only execute from there. In ATmega 48A/48PA there is no Read-While -Write support and no s eparate Boot Lo ader Section. The SPM instructio n can execute from th e entire Flash 3. Resources A compre hensive set o f developm ent tools, application notes and data sheets are availa ble for download on www.microchip.com Note: 1. 4. Dat a Retention Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years a t 85°C or 100 years at 25°C. 5. About Code Examples This documentation contains simple cod e examples that briefly show how to use various parts of th e device. These code examples assume tha t the part speci fic header file is included before compilation. Be awar e that no t all C compiler vendors include bit definitions in the head er files and interrupt h andling in C is compiler dependent. Conf irm with the C compiler documentation for mor e details. For I/O Registers located in extended I/O map, “IN”, “OUT ”, “SBIS”, “SBIC”, “CBI”, and “SBI” inst ructions must be replaced with instructions that allow access to exte nded I/O. Typically “LDS” and “STS” combined with “SBRS”, “SBRC”, “SBR”, and “CBR”. 6. Cap acitive T o uch Sensing The QTouch Li brary provides a simple to use solution to realize touch sensitive interfac es on most AVR microcontr ollers. The QTouch Libra ry incl udes support for th e QTouch and QM atrix ™ acquisition methods. Touch sensing can be added to any application by linking th e appropriate QTo uch Library for the AVR Microcontr oller. This is done by using a sim ple set of APIs to define the touch cha nnels and sen sors, and the n calling the touch sensing APIs to retr ieve the channel inform ation and determi ne the touch sensor states. The QTouch Li brary is FREE and downloadable from the Microchip website at the following location http://www.microchip.com. For implementation details and other information, refer to the QTouch Library User Guide - also available for download from the Micro chip website. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 18 7. A VR CPU Core 7.1 Overview This section dis cusses the AVR core ar chitecture in general. The main functio n of the CPU core is to ensur e correct p rogram execution. T he CPU mu st theref ore be ab le to ac cess memor ies, perfo rm calculat ions, contro l periphera ls, and handle in terrupts. Figure 7-1. Block Diagram of the A VR Architecture In order to maximize perfor mance and parallelism , t he AVR uses a Harvard archite cture – with separate memories and buses for progra m and data. Instructions in the progr am memory are exe cuted with a single level pipelining . While one instruction is be ing executed, the next instructio n is pre-fetche d from the program memory. This conc ept enab les instruc tions to be executed in every c lock cycle . The prog ram memo ry is In-S ystem Reprogramma ble Flash memory. The fast -access Regis ter File cont ains 32 x 8-bit gene ral purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) oper ati on. In a typical ALU operation, two 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 n A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 19 operand s are output from the Regi ster File, the oper at ion is executed, and the result is stored back in the Register File – in one clock cyc le. Six of the 32 regis ters can be us ed as three 16 -bit indi rect addre ss register po inters for Data Space ad dressing – enabling efficient addr ess calculations. One of the th ese address pointe rs can also be used as an addr ess pointer for look up ta bles in Flash program memory. Thes e added functi on registers are the 16-b it X-, Y-, and Z- register, describe d later in this section. The ALU supports arithmetic and logi c operations betw een register s or betwee n a constant and a register. Single register operations can also be executed in the AL U. After an arithmetic opera ti on, the Status Register is updated to re flect information about the re sult of the oper ation. Program flo w is provided b y conditional and unconditional jum p and call instructions, able to dir ectly address the whole add ress space. Most AVR in structions have a si ngle 16-b it word format. Every program me mory addre ss contains a 16- or 32- bit instruction. Program Flash me mory space is divide d in two sections , th e Boot Program section and the App lication Program section. Bo th sections have ded icated Lock bits for wr ite and rea d/write pr otection. The SPM instr uction th at writes into the Applic ation Flash memory section must reside in th e Boot Program section. During inte rrupts and su broutine ca lls, the retu rn addre ss Prog ram Counte r (PC) is stored on the Stac k. The Stack is effectively allocated in the genera l data SRAM, and consequen tly 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 su broutine s or interrupts ar e execut ed). The Stac k Pointer (SP) is read/ write acces sible in the I/O spa ce. The data SRAM can easily be accessed throu gh the five different addressin g modes supported in the AVR architecture. The memo ry spaces in the AVR architec ture are a ll linear an d regula r memor y maps. A flexible interr upt modul e has its control re gisters in the I/O sp ace with an ad ditional Glob al Interrupt En able bit in the Status Register. All inte rrupts ha ve a separate In terrup t Vector in th e Interrupt Vector table . The interru pts have priority in accor dance with their Inte rrupt Vector position . The low er the Inte rrupt Vec tor addr ess, the higher the p riority. The I/O memor y space con tains 64 ad dresses for CPU peri pheral functions as Co ntrol Registers, SPI, and other I/O functions. The I/O Memory c an be ac cessed directly, or as the Data Space locations following tho se of the Register File, 0x20 - 0x5F. I n addition , the ATm e ga48A/PA/88A/PA/168A/ PA/328/P has Extended I/O sp ace from 0x6 0 - 0xFF in SRAM wher e only the ST /S TS/STD and LD/LDS/LDD instructions can be used. 7.2 ALU – Arithmetic Logic Unit The high- performance AVR ALU op erates in direct con necti on with all the 32 general purpo se working re gisters. Within a single clock cycle, arithmetic operatio ns betwe en general purpo se registers or betwe en a register and an immed iate are ex ecuted . The ALU opera tions are d ivided into three main categor ies – arithmet ic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigne d multiplicatio n and fractional fo rmat. See the “Instr uction Set” section for a detailed description . 7.3 S t atus Regist er The Status Register contains info rmati on abou t the result of the most recent ly executed arithmetic instruction. This information can be used for altering progra m flow in order to perfor m conditional oper ations. Note that the Status Register is updated after all ALU operations, as specified in the Instructio n Set Reference. This will in many cases remo ve the need for using the dedicated co mpare instructions , resulting in faster and more compact code. The Statu s Register is not auto matically stor ed when en tering an interrupt routin e and restored when returning from an interrup t. This must be handled by software. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 20 7.3.1 S REG – A VR St atu s Regist er The AVR Status Register – SREG – is defined as: • Bit 7 – I: Gl obal Interru pt Enable The Global Interrupt Enable bit must be set for the inte rrupts to be enabled. The individual inter rupt enable control is then perfor med in separa te contro l registers. If the Global Interr upt Enable Reg ister is cleared , none o f the interrupts are en abled independe nt of the individu al interrupt enable settings. The I-bi t is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can al so be set and cleared by the application with the SEI and CLI instru ctions, as described in the instruct ion set refe rence. • Bit 6 – T : Bit Copy Storage The Bit Copy instructions BLD (B it LoaD) and BST (Bit STore) use the T-bit as so urce or destinat ion for the operated bi t. A bit from a register in the Register File ca n 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 Fl ag The Half Carry Flag H indicates a Ha lf Carry in some arithmetic oper ations. Half Carry Is useful in BCD arithmetic. See the “Instruction Set Descr iption” for deta iled inform ation. • Bit 4 – S: Sign Bi t, S = N  V The S-bit is always an exclu sive or between the Neg a tive Flag N and the Two’s Complement Over flow Flag V. See the “Instruction Se t Description” for detailed infor mation. • Bit 3 – V : T wo’ s Complement Overflow Flag The Two’s Complemen t Overflow Flag V supports two’ s comp lement arithmetic. See the “Instr uction Set Description” for det ailed information. • Bit 2 – N: Negative Flag The Negative Flag N indicates a ne gative result in an ar ithmetic or logic operation. See the “Instruction Set Description” for det ailed information. • Bit 1 – Z: Zero Flag The Zero Flag Z ind icates a zer o result in an arith metic or logic operation. See the “Instru ction Set Description” for detailed information. • Bit 0 – C: Carry Flag The Carry Flag C indicates a car ry in an arithmetic or lo gic operatio n. See the “Instruction Set Descri ption” for detailed information. 7.4 General Purpose Register File The Register File is optimized for the AVR Enhanced RI SC instruction se t. In order to achi eve the require d performance and flexibility, the following input/output schemes are supported by the Register File:  One 8-bit output operan d and one 8-bi t result input B i t 76543 210 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 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 21  T wo 8-bit output opera nds and one 8-b it result input  T wo 8-bit output opera nds and on e 16-bit result inp ut  One 16-bit output op erand and one 16-b it result input Figure 7- 2 shows the structure of the 32 general pu rpose working registers in the CPU. Figure 7-2 . AVR CPU Ge neral Purpose Working Registers Most of the instructions oper ating on t he Register File have direct access to all re gisters, and most of them are single cycle instructions. As shown in Figure 7-2 , each regist er is also ass igned a d ata memo ry addre ss, mapping them dir ectly into the first 32 lo cations of the user Data Space. Although no t being ph ysically imple mented as SRAM locations , this memory organization provides great flexibility in access of the registers, as the X- , Y- and Z-point er registers can be set to index any register in the file. 7.4.1 The X-register , Y -register , and Z-register The register s R26...R31 have some added fu nctions to th eir genera l purpose usage. Th ese register s are 16-bit address pointers fo r indirect add ressing of the data space. Th e three indirect add ress registers X, Y, and Z are defined as described in Figure 7- 3 . Figure 7-3. The X-, Y -, and Z-reg isters In the differen t addressing mo des these address r egisters have functions as fixed displacement, automatic increment, a nd automatic de crement (see th e instruct ion set referenc e for details). 70 A d d r . R0 0x00 R1 0x01 R2 0x02 … R13 0x0D Gene ral R14 0x 0E Purpose R15 0x0F Working R16 0x10 Registers R17 0x11 … R26 0x1A X-regist er Low Byte R27 0x1B X-register High Byte R28 0x1C Y -register Low Byt e R29 0x1D Y- register High Byte R30 0x 1E Z-regi ster Low By te R31 0x1F Z-register High Byte 15 XH XL 0 X-regist er 7 0 7 0 R27 (0x1B) R26 (0x1A) 15 YH YL 0 Y-regist er 7 0 7 0 R29 (0x1 D) R28 (0x 1C) 15 ZH ZL 0 Z-register 7 0 7 0 R31 (0x1F) R30 (0x1E) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 22 7.5 S t ack Pointer The Stack is mainly used for stor ing tempora ry data, for sto ring local varia bles and for sto ring return addr esses after interrupts an d subroutine calls. Note that th e Stack is implem ented as g rowing from higher to lower memory loca tions. The Stack Pointer Reg ister alwa ys point s to the top of the Stack. The Stack Po inter points to the data SRAM Stack area where th e Subroutine and Interrupt Stacks ar e 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 ca lls are executed or interrupts are ena bled. Initial Stack Pointer value equals the last addr ess of the in ternal SRAM a nd the Stack Pointer must be set to point above start of the SRAM, see Table 8- 3 on page 28 . See Table 7- 1 for Stack Poin ter deta ils. The AVR Stack Po inter is implemented as two 8-bit register s in the I/O space. The number o f bits act ually used is implementati on depende nt. Note that the data space in some implementations of t he AVR architecture is so small that only SPL is needed. In this c ase, the SPH Register will not be present. 7.5.1 SPH and SPL – S t ack Pointer High and S t ack Pointer Low Register T ab le 7-1. St ack Pointer instru ctions Instruction St ack poin ter Descrip tion PUSH Decremented by 1 Dat a is pushed onto the stack CALL ICAL L RCALL Decremented by 2 Return address is push ed onto the st ack with a subro utine call or interrupt POP Incremented by 1 Data is poppe d from the stack RET RETI Incremented by 2 Return add ress is popped from the stack with return from subroutine or re turn from interrupt B i t 1 51 41 31 21 11 0 9 8 0x3E (0 x5E) SP15 SP14 SP13 SP12 SP1 1 SP10 SP9 SP8 SPH 0x3D (0x5D) S P7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL 76543210 Read/Wri te 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 RAM END RAMEND RAM END RAMEND RAMEND RAMEND RAMEND RAMEND RAM END RAMEND RAMEND R AMEND RAMEND RAMEND A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 23 7.6 Instruction Execution Ti ming This section describes the ge neral access timing concep ts for instruction execution. The AVR CPU is driven by the CPU clock clk CPU , directly generated fro m the selected clock source for the chip. No internal clock division is used. Figure 7 -4 shows the par allel instruction fetches an d instructi on ex ecutions enabled by the Harva rd archite cture and the fast-a ccess Register File concept. This is the basic pipelinin g concept to obtain up to 1 MIPS per MHz with the correspond ing unique resu lts for functions per cost, functions per clocks, and functions per power-unit. Figure 7-4. The Par allel Instruction Fetches and Instr uction Executions Figure 7- 5 shows the internal timing concept for the Register File. In a single clock cycle a n ALU oper ation using two register operand s is executed, and the result is stored ba ck to the destination r egister. Figure 7-5. Single Cycle ALU Operation 7.7 Reset and Interrupt Handling The AVR provides several di fferent interru pt sources. The se interrupts an d the separate Reset Vector each have a separate p rogram vector in the prog ram memory spa ce. All interrupts are assign ed individual enabl e bits which must be written logic one together with the Global In terrupt Enable bi t in the Status Register in order to enable th e interrup t. Dependin g on the Program Co unter va lue, interrupts may be automatically disa bled when Boot Lock bits BLB0 2 or BLB12 are prog rammed. This feature improves software security. See the secti on ”Memory Pro gramming” on page 289 for details. The lowest addr esses in the pro gram memory space are by default de fined as the Rese t and Interrupt Vector s. The complete list of vectors is shown in ”Interrupts” on p age 66 . The list also determines the priority levels of the different interr upts. The lower the address the higher is the priority level. RESET has the hig hest priority, and next is INT0 – the Exte rnal Interrupt Reques t 0. The In terrupt Vectors can be moved to th e start of the Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR ). Refer to ”Interrupts” on page 66 for more information. The Reset Vector can also be moved to the start of the Boot Flash section by 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 T otal Ex ecution T ime Register Operands F etch ALU Operation Ex ecute Result W rite Bac k T1 T2 T3 T4 clk CPU A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 24 program ming the BOOTRST Fuse, see ”Boot Load er Support – Re ad-While-Write Self-Pro gramming” on pag e 272 . When an interrup t occurs, the Global Inter rupt Enable I-bit is clea red and all interrup ts are disabled. The user software can write logic one to the I-bit to enable ne sted inter rupts. All enabled interr upts can th en interrup t the current interrupt routine. The I-bit is automatically set w hen a Return from Interrupt instruc tion – RETI – is execute d. There are b asically two types of interrupts. The first type is triggered by an event that sets the Interr upt Flag. For these interr upts, the Prog ram Counter is vectored to the ac tual Interrupt Vector in order to execute the interr upt handling routine, and hard ware clea rs the correspo nding Inter rupt Fla g. Interr upt Flag s can also be cleare d by writing a logic on e to the flag bit position (s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cl eared, the Interrupt Flag will be set an d remembered until the interrupt is enabled, or th e flag is cleared by software. Similarl y, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, th e corres ponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is se t, and will then be execut ed by order of priority. The second type of inte rrupts will trigger as long as the interrupt c ondition is present. Th ese interrupts do not necessarily have Interrupt Flag s. If the interrupt cond itio n disappears before the interrupt is enabled , the interrupt will no t be triggered. When the AVR exits from an interrupt, it will always return to the ma in program and ex ecute one more instruct ion before any pe nd ing interrupt is served. Note that the Status Register is no t automatically stored when entering an interrupt routine, nor re stored when returning from an inter rupt routine. This must be handled by software. When using the CLI instruction to dis able interrupts, the interrupts will be i mmediately disabled. No interrupt will be executed af ter the CLI instruction, even if it oc curs simultaneously with the CL I instruction. The following example shows how this can be us ed to avoid interrupts during the ti med EEPROM write sequence. When using the SEI instruct ion to enable interr upts, the instruction following SEI will be executed before any pending in terrupts, as shown in this example. Assembly Code Example in r16, SREG ; store SREG value cli ; disable interrupts during tim ed 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 durin g timed sequence */ _CLI(); EECR |= (1<<EEMPE); /* star t EEPROM write */ EECR |= (1<<EEPE); SREG = cSREG; / * restore SREG value (I-bit) */ A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 31 8.6 Register Description 8.6.1 EEARH and EEARL – The EEPROM Address Register • Bit s [15:10] – Reserved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit s 9:0 – EEAR[9:0]: EEPROM Address The EEPROM Address Register s – EE ARH and EEARL specify the EEPROM address in the 256/512/512/1Kbytes EEPR OM space. The EEPROM data bytes are addressed linearl y between 0 and 255/511/511/10 23. The initial value of EEAR is undefined. A proper value must be written befo re the EEPROM may be accessed. Note: 1. EEAR9 and EEAR8 are unused bits in A Tmeg a 48A/48P A and must always be written to zero. 8.6.2 EEDR – The EEP ROM Dat a Register • Bit s 7:0 – EEDR[7:0]: EEPROM Data For the EEPROM write operation, the EED R Register contai ns the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM re ad operation, the EEDR co ntains the data read out from the EEPROM at the address given by EEAR. 8.6.3 EECR – The EEP ROM Control Register • Bit s 7:6 – Res erved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit s 5, 4 – EEPM1 and EEPM0: EEPROM Programming Mode Bit s The EEPROM Programming mode bit sett ing defines which progra mming action that w ill be triggered when writing EEPE. It is possible to prog ram data in one atomic opera tion (erase the old value and program the ne w value) or to split the Erase and Write oper ations in two di fferent o perations. The Programming times for the differen t modes are shown in Table 8-1 . While EEPE is set, any write to EEPM n will be ignored. D uring reset, the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming. B i t 1 51 41 31 21 1 1 0 9 8 0x22 (0 x42) –––––– E E A R 9 (1) EEAR8 (1) EEARH 0x21 (0 x41) EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL 765432 1 0 R e a d / W r i t e RRRRRR R R / W R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 000000 0 X XXXXXX X X B i t 7654321 0 0x20 (0 x40) MSB LSB EEDR 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 B i t 76543 2 10 0x1F (0x3F) – – EEPM1 EEPM0 EERIE EEMPE EEPE EERE EECR Read/Write R R R/W R /W R/W R/W R/W R/W Initial Value 0 0 X X 0 0 X 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 32 • Bit 3 – EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready In terrup t if the I bit in SREG is se t. Writing EERIE to zero disables the interrup t. The EEPROM Ready interrupt generates a constant in terrupt when EEPE is cleared. The interrupt will not be generated during EEPROM write or SPM. • Bit 2 – EEMPE: EEPROM Master Write Enable The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written. When EEMPE is set, setting EEPE within four clock cycl es will write data to the EEPROM at the selected address If EEMPE is zero, setting EEPE will have no effect. W hen EEMPE has been written to one by software, hardware clears the bit to zero after four clock cycl es. See the descri ption of the EEPE bit for an EEPROM write procedure. • Bit 1 – EEPE: EEPROM Wr ite Enable The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. W h en address and data are correctly set up, the EEPE bit must be written to one to writ e the value into the EEPROM. The EEMP E bit must be written to one before a logica l one is written to EEPE, otherwise no EEPROM write ta kes place. The following procedur e should be followed when writing the EEPR OM (the order of steps 3 and 4 is not essential): 1. W ait until EEPE becomes zero. 2. W ait until SPMEN in SPMCSR becomes zero. 3. W rite new EEPROM address to EEAR (optional). 4. W rite new EEPROM data to EEDR (optional). 5. Wr ite a logical one to the EE MPE bi t while writing a ze ro to EEPE in EECR. 6. Within four clock cycles after setting EEMPE, write a logical one to EEPE. The EEPROM can not be programmed dur ing a CPU write to the Flash memo ry. The software must check that the Flash programming is co mpleted before in itiating a new EEPROM write. Step 2 is only relevant if the softwar e contains a Boot Loa der allowin g the CPU to progra m the Flash. If the Flash is ne ver being upd ated by the CPU, step 2 can be omitted . See ”Boot Lo ader Suppor t – Read-While-Wr ite Self-Pro grammi ng” on page 272 for det ails abou t Boot programmin g. Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt ro utine accessing the EEPROM is interr upting another EEP ROM access, the EEAR or EEDR Register will be modified, causing the interr upted EE PROM access to fa il. It is recommended to have the Global Interrupt Flag cleared dur ing all th e steps to avoid these prob lems. When the write access time has elapsed, the EEPE bit is clea red by hardware. The user softwar e can poll this bit and wait for a zero before writ ing the next byte. When EEPE has been se t, the CPU is halted for two cycles before the next instruction is executed. T able 8-1. EEPROM Mode Bit s EEPM1 EEPM0 Programming Tim e Operation 0 0 3.4ms Erase and Wr ite in one operation (Atomic Operation) 0 1 1.8ms Eras e Only 1 0 1.8ms W rite On ly 11 – Reserved for future use A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 33 • Bit 0 – EERE: EEPROM Read Enable The EEPROM Read Enable Sig nal EERE is the read strobe to the EEP ROM. When the correct address is set up in the EEAR Register, the EERE bi t must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the re quested data is availabl e immediately. When the EEPROM is read, the CPU is halt ed for four cycles before the next instruction is executed. The user should poll the EEPE bit before starting the read ope ration. If a write operation is in progress, it is neither possible to read the EEPROM , nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM access es. Table 8- 2 lists the typical programming time for EEPROM access from the CPU. The following code examples show one assembly and one C function fo r writing to the EEPROM. The examples assume that interrupts are c ontrolled (e.g. by disabling in terrupts globally) so that no interrupts will occur during executio n of th ese func tions. Th e examp les also assume t hat no Flash Boot Loader is present in th e software. If such code is present, t he EEPROM write function must also wait for any ongoing SPM command to finish. T able 8-2. EEPROM Programming Time Symbol Number of Ca librated RC Oscilla tor Cycles T yp Programming T ime EEPROM write (from CPU) 26,368 3.3ms A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 34 The next code exam ples show assemb ly and C functions for rea ding the EEPROM. The e xamples as sume that interrupts are co ntrolled so that no interrupts will occur during ex ecution of these functions . Assembly Code Example EEPROM_write: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17 ) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to Dat a Register out EEDR,r16 ; Write logical one to EE MPE sbi EECR,EEMPE ; Start eeprom write by s etting EEPE sbi EECR,EEPE ret C Code Example void EEPROM_write( unsigned i nt uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1<<EEPE)) ; /* Set up address and Dat a Registers */ EEAR = uiAddress; EEDR = ucData; /* Write logical one to E EMPE */ EECR |= (1<<EEMPE); /* Start eeprom write by setting EEPE */ EECR |= (1<<EEPE); } A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 35 8.6.4 GPI OR2 – Ge neral Purpos e I/O Regis ter 2 8.6.5 GPI OR1 – Ge neral Purpos e I/O Regis ter 1 8.6.6 GPI OR0 – Ge neral Purpos e I/O Regis ter 0 Assembly Code Example EEPROM_read: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_read ; Set up address (r18:r17 ) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by wr iting EERE sbi EECR,EERE ; Read data from Data Reg ister in r16,EEDR ret C Code Example unsigned char EEPROM_read( u nsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1<<EEPE)) ; /* Set up address registe r */ EEAR = uiAddress; /* Start eeprom read by w riting EERE */ EECR |= (1<<EERE); /* Return data from Data Register */ return EEDR; } B i t 7654321 0 0x2B (0 x4B) MSB LSB GPI OR2 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 B i t 7654321 0 0x2A (0 x4A) MSB LSB GPI OR1 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 B i t 7654321 0 0x1E (0 x3E) MSB LSB GPI OR0 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 36 9. System Clock an d Clock Options 9.1 Clock Systems and their Distribution Figure 9- 1 presents the pr incipal clock systems in the AVR an d their d istribution. All of the clocks ne ed not be active at a given time. In order to reduce power cons um ption, the clocks to modules not be ing used can be halted by using different slee p modes, as described in ” Power Manag ement and Slee p Modes” o n page 48 . The clock systems are detailed below. Figure 9-1. Clock Distribu tion 9.1.1 C PU Clock – clk CPU The CPU clock is routed to parts of the system concern ed with operation of th e AVR core. Examples of such modules are the General Pur pose Register File, the St atus Regi ster and the data me mory holding the Stack Pointer. Halting the CPU clock inhibits the core from perfo rming general op erations and calculation s. 9.1.2 I/O Clock – clk I/O The I/O clock is used by the ma jority of the I/O m odule s, like Timer/Coun ters, SPI, and USART. The I/O clock is also used by th e External Interrup t module, but note th at start condition detection in the USI module is carried out a synch ronousl y w hen clk I/O is halted , TWI address recognitio n in all sleep modes. Note: Note that if a level triggered interrupt is used for wa ke-up from Power-down, the required l evel must be held lo ng enough for the MCU to complete the wa ke-up to trigger the level interrupt. If the level disapp ears before the end of the S tart-up T ime, the MCU will still wake up, but no interru pt will be generated. The star t-up time is defined by the SUT and CKSEL Fuses as described in ”System Clock an d Clock Options” on page 36 . General I/O Modules Asynchronous Timer/Counter CPU Core RAM clk I/O clk ASY A VR Clock Control Unit clk CPU Flash and EEPROM clk FLASH Source clock W atchdog Timer W atchdog Oscillator Reset Logic Clock Multiple x er W atchdog cloc k Calibrated RC Oscillator Timer/Counter Oscillator Cr ystal Oscillator Low-frequency Cr ystal Oscillator External Clock ADC clk ADC System Clock Prescaler A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 37 9.1.3 Flash Clock – clk FLASH The Flas h clock c ontrols ope ration of the Flas h interfac e. The Flash clock is usually active simultaneously with the CPU clock. 9.1.4 Asy nchronous T imer Clock – clk ASY The Asyn chro nous Tim er cl ock al lows th e Asynchronous Timer/Coun ter to be clocked directly from an external clock or an extern al 32kHz clock crystal. The de dicated clock domain allows using this Time r/Counter as a re al- time counter even when th e device is in sleep mode. 9.1.5 ADC Clock – clk ADC 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 digita l circuitry. Th is gives more accurate ADC conversion results. 9.2 Clock Sources The device ha s the following clock sou rce options, s electable by Flas h Fuse bits as show n below. The clo ck from the selected source is input to th e AVR clock generator, an d routed to the ap propriate module s. Note: 1. For all fuses “1” means unprogra mmed while “0” means programmed. 9.2.1 Defaul t Clock Sourc e The device is shipped with in ternal RC oscillator at 8.0M Hz and with the fuse CKDIV8 programmed, resulting in 1.0MHz system cl ock. The startup time is set to maximum and time-out period enabled. (CKSEL = "0010", SUT = "10", CKDIV8 = "0"). The defau lt setting ensures that all user s can make their des ired clock s ource settin g using any avail able programming inter face. 9.2.2 Clock S t artup Se quence Any cl ock sourc e needs a suf ficie nt V CC to start oscillating and a minimum number of oscilla ting cycles before it can be co nsidered stable. To ensure sufficient V CC , the device issues an internal rese t with a time- out delay (t TOU T ) after the device reset is released by all other reset sources. ”System Control and Reset” on pag e 56 describes the start cond itions for the internal reset. The delay (t TO UT ) is timed from the Watchdog Oscillator and the number of cycles in the delay is set by the SUTx and CKSELx fuse bits . The selectable de lays are shown in Table 9- 2 . The freq uency of the Watchdog Oscillator is voltag e dependent as shown in ”Typical Characte ristics – (TA = -40°C to 85°C)” on page 326 . T ab le 9-1. Device Clocking Op tions Select (1) Device Clocking Option CKSEL3...0 Low Power Crystal Oscillator 1 1 1 1 - 1000 Full Swing Crystal Oscillator 01 1 1 - 01 10 Low Frequency Crystal Oscillator 0101 - 0100 Intern al 128kHz RC Oscilla tor 001 1 Calibrated Internal RC Oscillator 0010 External Clock 0000 Reserved 0001 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 38 Main purpose of th e delay is to keep the AVR in reset until it is supplied with minimum V CC . The delay will not monitor the actual volt age and it will be required to sele ct a delay longer than the V CC rise time. If this is not possible, an internal or external B r own-Out Detection circuit should be used. A B OD circuit will ensure sufficient V CC before it releases the rese t, and the time-out de lay can be disabled. Disabling th e time-out delay without utilizing a Brown-Out Detection circ uit is not recommended. The oscillator is required to oscillate for a minimum number of cycles before the clock is considered stable. An internal ripple counter moni tors the osc illator output clock, and keep s the internal reset active for a given number of clock cyc les. The reset is then released and the device will start to execute. The recommended oscillator start-up time is dependent on the clock type, and varies from 6 cycl es for an ex ternally applied clock to 32K cycles for a low frequency crystal. The start-up sequ ence for the clo ck includes both the time -out delay and the start-u p time when the device starts up from reset. Wh en starting up from Power-save or Power -down mode, V CC is assumed to be at a sufficient level and only the start-up time is included. 9.3 Low Power Cryst al Oscillato r Pins XTAL1 and XTAL2 are input an d output, resp ectively, of an inv erting amp lifier which can be c onfigured fo r use as an On-chip Osc illator, as show n in Figure 9-2 on page 38 . Either a qu artz crystal or a ce ramic resonator may be used. This Crystal Oscillator is a low power osc illator, with re duced voltage sw ing on the XTAL2 output. It gives the lowest powe r consumption, but is not ca pable of driving othe r clock input s, an d may be more su sceptible to noise in noisy environmen ts. In thes e cases, refer to the ”Full S wing Crystal Oscillator” on page 39 . C1 and C2 should always be equal for both crystals and reso nators. The optimal va lue of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromag netic noise of the environ ment. Some init ial guidelines for choosi ng capacitors fo r use with crystals are given in Table 9-3 on page 3 9 . For ceramic resona tors, the capa citor values given by the manufacturer sh ould be used. Figure 9-2. Cr ystal Oscillator Co nnections The Low Power Oscillator can operate in three different modes, each op timized for a specific frequency range. The operating mode is selected by the fuses CKSEL3...1 as shown in Table 9-3 on pag e 39 . T abl e 9-2. Number of W atchdog Oscillator Cycles T yp Time-out (V CC = 5.0V) T yp T ime-out (V CC = 3.0V) Number of Cycles 0ms 0ms 0 4.1ms 4.3ms 512 65ms 69ms 8K (8,192) XT AL2 (T OSC2) XT AL1 (T OSC1) GND C2 C1 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 39 Notes: 1. This is the recommended CKSEL settings for the difference frequency ranges. 2. This option should not be use d with cryst als, only with ceramic resonators. 3. If the crystal frequency exceeds the specification of the device (depen ds on V CC ), the CKDIV8 Fu se can be programmed i n order to divide the internal freque ncy by 8 . It must be ensured that the resulting divided clock meets the frequency specif ication of the device. The CKSEL0 Fuse together with the SUT1...0 Fuses select th e start-up time s as shown in Table 9- 4 . Notes: 1. These options should only be used when not opera ting close to the maximum frequency of the device, and only if frequency stability at start- up is not import ant for t he application. These options are not suitable for crysta ls. 2. These options are intend ed for use with ceramic re sonator s and will en sure frequency st ability at start-up. They can also be used with crystals when not operating cl ose to the maximum frequ ency of the device, and if frequency stability at st art-up is not important for the application. 9.4 Full Swing Cryst al Oscillator Pins XTAL1 and XTAL2 are input an d output, resp ectively, of an inv erting amp lifier which can be c onfigured fo r use as an On-chip Osc illator, as show n in Figure 9-2 on page 38 . Either a qu artz crystal or a ce ramic resonator may be used. T ab le 9-3. Low Power Crystal Oscillator Operating Modes (3) Frequency Ran ge (MHz) Recommen ded Range for Cap acitors C1 and C2 (pF) CKSEL3...1 (1) 0.4 - 0.9 – 100 (2) 0.9 - 3.0 12 - 22 101 3.0 - 8.0 12 - 22 11 0 8.0 - 16.0 12 - 22 111 T ab le 9-4. St art-up Times for the Low Power Crystal Oscillator Clock Selection Oscillator Sour ce / Power Conditions St ar t-up Time from Power-down and Power-save Additional Delay from Reset (V CC = 5.0V) CKSEL0 SUT 1...0 Ceramic resonator , fast rising power 258 CK 14CK + 4. 1ms (1) 0 00 Ceramic resonator , slowly rising power 258 CK 14CK + 65ms (1) 0 01 Ceramic resonator , BOD enabled 1K CK 14CK (2) 0 10 Ceramic resonator , fast rising power 1K CK 14CK + 4. 1ms (2) 0 11 Ceramic resonator , slowly rising power 1K CK 14CK + 65ms (2) 1 00 Crystal Oscillator , BOD enabled 16K CK 14CK 1 01 Crystal Oscillator , fast rising power 16K CK 14CK + 4. 1ms 1 10 Crystal Oscillator , slowly rising power 16K CK 14CK + 65ms 1 11 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 40 This Crystal Oscillator is a full s wing oscillator, w ith rail-to-ra il swing on the XTA L2 outp ut. This is useful for driving other clock inputs and in noisy envir onment s. The curr ent cons umption is higher t han the ”L ow Power Crystal Oscillator” on page 38 . Note that the Full Swing Crystal Oscillator will only operate for V CC = 2.7 - 5.5 volts. C1 and C2 should always be equal for both crystals and reso nators. The optimal va lue of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromag netic noise of the environ ment. Some init ial guidelines for choosi ng capacitors fo r use with crystals are given in Table 9-6 on page 4 0 . For ceramic resona tors, the capa citor values given by the manufacturer sh ould be used. The operating mode is selected by the fuses CKSEL3...1 as shown in Table 9-5 . Notes: 1. If the cryatal frequency exceeds the specifica tion of the device (depends on V CC ), the CKDIV8 Fuse can be programmed i n order to divide the internal freque ncy by 8 . It must be ensured that the resulting divided clock meets the frequency specif ication of the device. Figure 9-3. Cr ystal Oscillator Co nnections T able 9-5. Full Swing Cryst al Oscillator operating mod es Frequen cy Range (1) (MHz) Recommended Range for Cap acitors C1 and C2 (pF) CKSEL3...1 0.4 - 20 12 - 22 01 1 T ab le 9-6. St art-up Times for the Full Sw ing Cryst al Oscillator Clock Selection Oscillator Sour ce / Power Conditions St ar t-up Time from Power-down and Power-save Additional Delay from Reset (V CC = 5.0V) CKSEL0 SUT 1...0 Ceramic resonator , fast rising power 258 CK 14CK + 4. 1ms (1) 0 00 Ceramic resonator , slowly rising power 258 CK 14CK + 65ms (1) 0 01 Ceramic resonator , BOD enabled 1K CK 14CK (2) 0 10 Ceramic resonator , fast rising power 1K CK 14CK + 4. 1ms (2) 0 11 Ceramic resonator , slowly rising power 1K CK 14CK + 65ms (2) 1 00 XT AL2 (T OSC2) XT AL1 (T OSC1) GND C2 C1 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 47 T ab le 9-17. Cloc k Prescaler Select CLKPS3 CLKPS2 CLKPS1 CLKPS0 Clock Divisio n Factor 0 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 0 1 1 8 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 Reserved A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 48 10. Power Management and Sleep Modes Sleep modes en able the applica tion to sh ut down unused modules in the MCU, thereby sa ving power. The AVR provides various sleep modes allowing th e user to tailor the power consumption to the appl ication’s requirem ents. When enabled, the Brown -out Detector (BOD) actively monitors th e power supp ly voltage during the sle ep periods. To further save power, it is possible to disabl e the BOD in so me sleep modes. See ”BOD Disable(1)” on page 4 9 for more details. 10.1 Sleep Modes Figure 9- 1 on page 36 presen ts the different clock systems in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and their distribution. Th e figure is helpful in selecting an ap propriate sleep mode. Table 10 -1 shows the different sleep modes, their wake up sources BOD disable ability. (1 ) Note: 1. BOD disable is only available for A Tmega48P A/8 8P A/168P A/328P. Notes: 1. Only recommended with external cryst al or resonator selected as clock source. 2. If T imer/Counter2 is ru nning in a synchronous mode. 3. For INT1 and INT0, on ly level inte rrupt. To enter any of the six sleep mode s, the SE bit in SMCR must be writte n to logic one and a SLEEP in struction must be e xecuted. The SM2, SM 1, and SM0 b its in t he SMCR Register select whic h sleep mode (Idle, ADC Noise Reduction, Power-do wn, Power-save, Standby, or Extended Standby) will be activated by the SLEEP instruction. See Table 10-2 on pa ge 53 for a summary. If an enabled interrupt occurs while the MCU is in a sl eep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt ro utine, 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 rese t occurs during sleep mode , the MCU wakes up and executes from the Reset Vector. T ab le 10-1. Active Clock Domains and W ake-up Sources in the Different Sle ep Modes Active Clock Domains Oscillators W ake-up Sourc es Software BOD Disable Sleep Mode clk CPU clk FLASH clk IO clk ADC clk ASY Main Clock Source Enabled T ime r Oscillator Enabled INT1, INT0 and Pin Chan ge TWI Address Match Ti m e r 2 SPM/EEPROM Ready ADC WDT Other I/O Idle X X X X X (2) X X X X X X X ADC Noise Reduction X X X X (2) X (3) X X (2) X X X Power-down X (3) X X X Power-save X X (2) X (3) X X X X S tandby (1) X X (3) X X X Extended S tandby X (2) X X (2) X (3 ) X X X X A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 49 10.2 BOD Disable (1) When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses - see Table 28-7 on page 291 and onwards, the BOD is actively mo nitoring the power sup ply voltage during a sleep peri od. To save power, it is possible to disable th e BOD by softwar e for s ome of th e sleep mo des, see Table 10-1 on p age 48 . The slee p mode power consumption wi ll then be at the same level as when BOD is globally dis abled by fuses. If BOD is disabled in software, the BOD functi on is turned off immediately a fter entering the sleep mo de. Upon wake-up from sleep, BOD is automaticall y enabled again. This ensure s safe operation in case the V CC level has dropped during the sleep per iod. When the BOD has been disabled, the wa ke-up time from sleep mode will be approximately 60 µs to ensure that the BOD is working correctly bef ore the MCU continues executing code. BOD disable is controlled by bit 6, BODS (BOD Sleep) in the contro l register MCUCR, see ”MCUCR – MCU Control Register ” on page 54 . Writing this bit to one turn s off the BOD in re levant sleep modes, while a zero in this bit keeps BOD act ive. Default setting keeps BOD active, i.e. BOD S set to zero. Writing to the BODS bit is control led by a timed sequence and an en able bit, see ”MCUCR – MCU Control Register” on pa ge 54 . Note: 1. BOD disable only available in picoPower ® devices A Tmega48P A/88P A/168P A/328P 10.3 Idle Mode When the SM2...0 bits are written to 000, the SLEEP instruction make s the MCU enter Idle mode, stopping the CPU but allowing the SPI, USART, An alog Comparator , ADC, 2-wire Se rial Interface, T imer/Co unters, Watchdog, and the interru pt system to continue operating. This sleep mode ba sically halts clk CPU and clk FLASH , while allowing the other c locks to run. Idle mode enable s the MCU to wake up from extern al tr iggered in terrupts as well as intern al ones like the Timer Overflow and USART Transmit Complete interrupt s. If wa ke- up from th e Analog C omparat or interr upt is not required, th e Analog Comparator can be powered down by setting the ACD bit in the Analog Comparator Control and Status Register – ACSR. This will reduce power consumption in Idle mode. If the ADC is enabled, a conversion starts auto matically when this mode is entered. 10.4 ADC Noise Reduction Mode When the SM2...0 bits are written to 001, the SLEEP instruction ma kes the MCU enter ADC Noise Reduction mode, st opping the CPU but allo wing the A DC, the ex ternal interr upts, the 2-wire Seria l Interfac e addre ss watch, Time r/Counte r2 (1) , and the Watchdog to continue operating (i f enabled). This sleep mode basically halts clk I/O , clk CPU , and clk FLASH , while allowing the other clocks to run. This improv es the noise en vironmen t for the ADC, e nabling higher reso lution me asurement s. If the AD C is enabled, a conversion starts autom atically when this m ode is en tered. Apar t from the ADC Conver sion Complete interrupt, only an Exte rnal Reset, a Watchdo g System Reset, a Watchd og Interrupt, a Br own-out Reset, a 2-wire Serial Interface addr ess match, a Time r/Counter2 in terrupt, an SPM/EEPROM ready interrupt, an external level interrupt on INT0 or INT1 or a pi n change interrupt can wak e up the MCU from ADC Noise Reduction mode. Note: 1. T imer/C ounter2 will only keep running in asynchro nous mode, see ”8-bit Ti mer/Counter2 with PWM and Asyn- chronous Operation” on pag e 150 for details. 10.5 Power-down Mode When the SM2...0 bits are written to 010, the SLEEP instruction ma kes the MCU enter Power-down mode. In this mode, the external Oscillator is s topped, while the exter nal interrupts, the 2-wire Serial Interface address watch, and the Watchdog con tinue opera ting (if e nabled) . On ly an External Reset, a Watchdo g System Reset, a Watchdog Interrupt, a Brown- out Reset, a 2-wire Serial In terface add ress match, an external leve l interrupt on A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 50 INT0 or INT1, or a pin cha nge interrupt can wake up the MCU. This sleep mode basically halts a ll generated clocks, allowing operation of asynchronous modules only. Note: If a level triggered interrup t is used for wake-up from Powe r-down, the required level must be held long enough for the MCU to complete the wa ke-up to trigger the level interr upt. If the level disap pears before the end of the S tart-up T ime, the MCU will still wake up, but no interrupt will be generated. ”External Interrupts” on page 79 . The sta rt-up time is defi ned by the SUT and CKSEL Fuses as described in ”System Clo ck and Clock Options” on page 36 . When waking up from Po wer-down mode, there is a de la y from the wake-u p condition occu rs until the wake -up becomes effe ctive. This allows the clock to restart and become stable after ha ving been sto pped. The wake-up period is defined by th e same CKSEL Fuses that de fine the Reset Tim e-out period, as de scribed in ”Clock Sources” on pa ge 37 . 10.6 Power-save Mode When the SM2...0 bits are written to 011, the SL EEP instruction makes the MCU en ter Power-save mode. This mode is identical to Powe r-down, with one ex ception: If Timer/Counter2 is enabled, it will keep running during sleep. The devi ce can wake up from either Timer Overflow or Output Compare even t from Timer/ Counter2 if the correspondin g Timer/Counter2 interrupt enab le bits are se t in TIMSK2, and the Global Interrupt Enable bit in SREG is set. If Timer/Counter 2 is not run ning, Power- down m ode is recomme nded instead of Power- save mode. The Timer/Counter2 can be clocked both synchron ously and asynch ronously in Power- save mode. If Timer/Counter2 is not using the asyn chronous clock, the Time r/Counter Oscillator is stopped during sleep. If Timer/Counter2 is not using the synchronous clo ck, the cl ock source is sto pped during sle ep. Note that even if the synch ronous c lock is runn ing in Power-sa ve, this clock is only available for Timer/ Counter2. 10.7 S t andby Mode When the SM2...0 bits are 110 and an external crystal/resonato r clock option is select ed, the SLEEP instruction makes the MCU enter Stand by mode. This mo de is i dentical to Power-down with th e exception that the Oscillator is kept running. Fr om Standby mode, the device wakes up in s ix clock cycles. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 51 10.8 Extended S t andby Mode When the SM2...0 bits are 111 and an external crystal/resonato r clock option is select ed, the SLEEP instruction makes the MCU enter Extende d Standby mode. This mo de is identical to Power-save with the exception that the Oscillator is kept running. Fr om Extended Standby mode, the device w akes up in six clock cyc les. 10.9 Power Reduction Register The Power Reduction Register (PRR), see ”PRR – Powe r Reduction Register ” on page 54 , provides a method to stop the clock to individual periphe rals to reduce p ower consumptio n. T he current state of the peripher al is frozen and the I/O registe rs can not be read or written. Resources used by the peripheral whe n stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. Waking up a module, which is done by cle aring the bit in PRR, puts the module in th e same state as be fore shutdown . Module shutdo wn can be used in Idle mod e and Acti ve mode to significantly reduce the overall power consumption. In all other sleep modes, the clock is already stopped. 10.10 Minimizing Power Consumption There are several possib ilities to consider when tryi ng to minimize the power cons umption in an AVR controlled system. In general, sleep modes should be used as much as possibl e, and the sleep mode should be selected so that as few as possible of the device’s functio ns ar e operating. All functions not needed sho uld be disabled. In particular, the following modules may need special consid eration when tryin g to achieve the lowest possible power consu mption. 10.10.1 Analog to Digit al Converter If enabled, the ADC will be enab led 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 c onversion will be an extended conversion. Refer to ”Analog-to-Digita l Converte r” on pa ge 246 for de tails on ADC operation. 10.10.2 Analog Comparator When ent ering Idle m ode, the An alog Com parator sh ou ld be disabled if not used. When entering ADC Noise Reduction mode, the Ana log Comparator should be disabled. In other sleep modes, th e Analog Comparat or is automatically disab led. However, if the Analo g Comparator is set up to use the Intern al Voltage Refe rence as input, the Analog Comparator should be disab led in all sl eep modes. Otherwise, the Inter nal Voltage Reference will be enabled, independent of sle ep mode. Refer to ” Analog C omparat or” on p age 243 for details on how to configure the Ana log Comparator. 10.10.3 Brown-o ut Detector If the Brown-ou t Detector is not needed by the application, this module sh ou ld be turned off. If t he Brown- out Detector is enabled by the BODLEVEL 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 cons um ption. Refer to ”Brown-ou t Detection” on page 58 for details on how to configure the Brown-out Detector. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 52 10.10. 4 Interna l V oltage Reference The Internal Voltage Re ference will be enabled when needed by the Brown-ou t Detection, the Analog Comparator or the ADC. If these modu les are disabled as described in the sections above, the internal voltage reference will be disabled and it will no t be consuming power. When turned on again, the user must allow the reference to start up be fore the output is used. If the re fe rence is kept on in sleep mo de, the output can be used immediately. Refer to ”Internal Voltage Re ference” on page 5 9 for deta ils on the sta rt-up tim e. 10.10.5 W atchdog T imer If the Watchdog Timer is n ot needed in th e application, the mo dule should be tur ned off. If the Watchdog Timer is enabled, it will be enable d in all sleep modes and hence always cons ume power. In the d eeper sleep modes, this will contribute signif icantly to the total curren t cons umption. Refer to ”Watchdo g Timer” on pa ge 60 for details on how to configure the Watchdog Timer . 10.10.6 Port Pins When enterin g a sleep mode, all port pins shou ld be co nfigured to use mi nimum powe r . The most importan t is then to ensure that no pins drive r esistive load s. In sleep modes where both the I/ O clock (clk I/O ) and the ADC clock (clk ADC ) are stopped, the input buffers of the device wi ll be disabled. This ensures that no power is consumed by the input log ic when not ne eded. In some cases, the input logic is need ed for detecting wake-up conditions, and it will then be enabled. Refer to the section ”Digital Input Enable and Sleep Mod es” on page 88 for details o n which pins are enab led. If the input buffe r is enable d and the input signal is left floatin g or have an analog sig nal level c lose to V CC /2, the input buffer will use exc essive power. For anal og input pin s, the dig ital input bu ffer shou ld be disab led at all ti mes. An ana log signal level close to V CC /2 on an inp ut pin can cause significant cur rent even in active mode . Digital input buffer s can be disabled by writing to the Dig ital Input Disable Reg isters (DIDR1 and DIDR0 ). Refer to ”DIDR 1 – Digital Input Disa ble Register 1” on pa ge 245 and ”DIDR0 – Digital Input Disable Re gister 0” on page 260 for details. 10.10.7 On-chip Debug Sys tem If the On-chip debug system is enab led by the DWEN Fu se and the chip enters sleep mode, the main clock source is enab led and hen ce always consu mes power. In the deep er sleep modes, this will contribute significantly to the to ta l current cons umption. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 53 10.1 1 Register Description 10.1 1.1 SMCR – Sl eep Mode Contro l Registe r The Sleep Mode Co ntrol Registe r contains control b its for powe r management. • Bit s [7:4]: Reserved These bits are unused in the AT mega48A/PA/88A/PA/168A/ PA/328/P, and will alwa ys be read as zero. • Bit s 3:1 – SM[2:0]: Sleep Mode Select Bit s 2, 1, and 0 These bits select betwe en the five available sleep modes as shown in Tab le 10-2 . Note: 1 . S t andby mode is on ly recomme nded for u se with ex ternal crys t als o r resonators . • Bit 0 – SE: Sleep Enable The SE bit must be written to logic one to make the MC U ente r the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mo de unless it is the programmer’s p urpose, it is recommend ed 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. B i t 7654321 0 0x33 (0 x53) –––– S M 2 S M 1 S M 0 S E S M C R Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 T ab le 10-2. Sleep Mode Select SM2 SM1 SM0 Sleep Mode 000 Idle 001 ADC Noise Reduction 010 Power-down 011 Power-save 100 Reserved 101 Reserved 110 S tandby (1) 111 External S tandby (1) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 54 10.1 1.2 MCUCR – MCU Control Register • Bit 6 – BODS: BOD Sleep (1) The BODS bit must be written to logic one in order to turn off BOD during sleep , see Table 10-1 on page 48 . Writing to the BODS bit is control led by a timed sequence and an enable bit, BODSE in MCUCR. To disa ble BOD in rele vant sleep m odes, both BO DS and BO DSE mu st firs t be set to one. Then, to set the BODS bit, BODS must be set to one and BODSE must be set to zero within four clock cycles. The BODS bit is active three clock cycles after it is se t. A sleep instruction must be executed while BODS is active in order to turn off the BOD for the actual slee p mode. The BODS bit is aut o matically cleared after three clock cycles. • Bit 5 – BODSE: BOD Sleep Enable (1) BODSE enables setting o f BODS control bit, as explained in BODS bit description. BO D dis able is controlled by a timed sequence. Note: 1. BODS and BODSE only available for picoPower devices A Tmega4 8P A/88 P A/16 8P A/3 28P 10.1 1.3 PRR – Power Reducti on Register • Bit 7 – PRTWI: Power Reduction TWI Writing a logic o ne to this bit shuts down the TWI by stopping the clock to the module. When waking up the TWI again, the TWI should be r e initialized to ensure proper operation. • Bit 6 – PRTIM2: Power Reduction T i mer/Counter2 Writing a logic one to this bit shuts down the Timer/Co un te r2 modul e in synchronous mode (AS2 is 0). When the Timer/Counter2 is enable d, operation will continue like before t he shutdown. • Bit 5 – PRTIM0: Power Reduction T i mer/Counter0 Writing a logic on e to this bit shuts down the Timer/ Counter0 module . When the Timer/Co unter0 is enable d, operation will continue lik e before the shutdown. • Bit 4 – Reserved This bit is reserved in ATm ega48A /PA/88A/PA/168A/PA/328/P an d will always read as zero. • Bit 3 – PRTIM1: Power Reduction T i mer/Counter1 Writing a logic on e to this bit shuts down the Timer/ Counter1 module . When the Timer/Co unter1 is enable d, operation will continue like before the shutdown. Bit 7 6 5 4 3 2 1 0 0x35 (0 x55) – BODS (1) BODSE (1) PUD – – IVSEL IVCE 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 Bit 7 6 5 4 3 2 1 0 (0x64) PRTWI PRTIM2 PRTIM0 – PRTIM1 PRSPI PRUSART0 PRADC PRR Read/Write R/ W R/W R/W R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 55 • Bit 2 – PRSPI: Power Reduction Serial Perip heral Interface If using debugWIRE On-chip Deb ug System, this bit should not be written to one. Writing a logic on e to this bit shuts do wn the Ser ial Peripher al Interfac e by stopp ing the cloc k to the mo dule. When wa king up th e SPI again, the SPI should be re initialized to ensure proper operati on. • Bit 1 – PRUSART0: Power Reduction USART0 Writing a logic on e to this bit shuts down the USART by stopping the clock to the m odule. When waking up the USART again , the USART s hould be re init ialized to ensure proper opera tion. • Bit 0 – PRADC: Power Reduction ADC Writing a logic on e to this bit shuts down the ADC. Th e ADC m ust be d isabled bef ore shut down. The analog comparator ca nnot use the ADC input MUX when the ADC is shut down. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 56 1 1. System Control and Reset 1 1.1 Resetting the A VR During rese t, all I/O Registers are se t to their initial value s, and the progr am starts exec ution from the R eset Vector. For ATmega168A/1 68PA/328/328P the instruct ion p laced at the Reset Vector must be a JMP – Absolute Jump – instr uction to the rese t handling r outin e. For the ATmega 48A/ 48PA and ATme ga88A/88PA, the instruction placed at the Reset Vector must be an RJ MP – Relative Jump – instru ction to the reset ha ndling routine. If the program never enables an interrupt sour ce, the Interrupt Vecto rs are not used, and re gular program code can be placed at these locations. T his is also the ca se if t he Reset Ve ctor is in the Application section while the Interrup t Vectors are in the Boot section or vice versa (ATmega88A/88PA/16 8A/168PA/328/32 8P only). The circuit diag ram in Figure 11- 1 on page 57 shows the reset logic. Table 29-11 on page 314 defines the electrical para me ters of the reset circuitry. The I/O ports of the AVR are immedia tely reset to their in itial state when a reset source goes active . This does not require any clock source to be running . After all reset sources ha ve gone inactive, a delay counter is invoked, stretching the internal reset. This allows the power to re ach a stable level bef ore normal ope rati on starts. The time-out period of the delay counter is defined by the user through the SU T and CKSEL Fuses. The different se lections for the delay period are presen ted in ”Clock Sources” on page 37 . 1 1.2 Reset Sources The ATmega48A/PA/88A/PA/168A/PA/3 28/P has four sources of reset:  Power-on Reset. The MCU is reset when the supp ly voltage is below the Powe r-on Reset threshold (V POT ).  External Reset. The MCU is reset when a low level is present on the RESET pi n for longer th an the minimum p ulse length.  W atchdog System Reset. The MCU is reset when th e W atchdog T imer period e xpires and the W atchdog System Reset mo de is enabled.  Brown-out Reset. The MCU is re set when the supp ly volta ge V CC is below the Bro wn-out Reset thre shold (V BOT ) and the Br own-out Detector is enabled . A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 63 1 1.9 Register Description 1 1.9.1 MCUSR – MCU St atus Register The MCU Status Re gister provides in formation o n which reset source ca used an MCU reset. • Bit 7:4: Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 3 – WDRF: W atchdog System Re set Flag This bit is se t if a Watchdog Sy stem Reset oc curs. The bi t is reset by a Power-on Re set, or by writing a logic zero to the flag. • Bit 2 – BORF: Brown-out Reset Flag This bit is set if a Brown- out Reset occurs. The bit is re se t by a Power- on Rese t, or by wr iting a logi c zero to the flag. • Bit 1 – EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is rese t by a Power- on Reset, or by writing a logi c zero to the flag. • Bit 0 – PORF: Power-on Reset Flag This bi t is se t if a Power-on Reset occurs. The bi t is reset only by writing a logic zero to the flag. To make use of the Reset Flags to identify a reset co ndition, the user shou ld read and then Reset the MCUSR as early as possible in the program. If the register is cl eared befor e another reset occurs, the so urce of the reset can be found by examining the Reset Flags. 1 1.9.2 WDTCSR – W atchdog T imer Control Register • Bit 7 – WDIF: W atchdog Interr upt Flag This bit is se t when a time- out occurs in t he Watchdog Timer and t he Watchd og Timer is co nfigured fo r interrupt. WDIF is cleared by har dware when executing th e corresp onding interrup t handling vector. Alternatively, WDIF is cleared by writi ng a logic one to the flag. When the I- bit in SREG and WDIE are set, the Watchdog Time -out Interrup t is exec uted. • Bit 6 – WDIE: W atchdog Interrupt Enab le When this bit is written to one and the I-bit in th e Stat us Register is set, the Watchdog Interrupt is enabled. If WDE is cleared in combin ation with this settin g, the Watchdog Timer is in Interrupt Mode, and the corresponding interrupt is executed if time-out in the Watch dog Timer occurs. If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing B i t 7654 3210 0x34 (0 x54) –––– W D R F B O R F E X T R F P O R F M C U S R Read/Write R R R R R/W R/W R/W R/W I n i t i a l V a l u e 0000 S e e B i t D e s c r i p t i o n B i t 76543210 (0x60) WDIF WDIE WDP3 WDCE WDE WDP2 WDP1 WDP0 WDTCSR Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 0000 X 000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 64 the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watc hdog goes to System Reset Mode ). This is useful for keeping the Watc hdog Timer security while us ing the interrupt. To stay in Interrupt and System Reset Mode, WDIE mu st be set af ter each interrup t. This should howeve r not be don e within the interrupt ser vice routine itse lf, as this might compro mise the sa fety-function of the Watchd og System Reset mode. If the interrup t is not exec uted before the next time-out, a Sy stem Reset will be applied. Note: 1. WDTON Fuse set to “0” means programmed and “1” means un programmed. • Bit 4 – WDCE: W atchdog Change Enab le This bit is used in timed se quences for chan ging WDE and prescaler bits. To cle ar the WDE bit, and/or change the pres caler bits, WDCE must b e set. Once written to one, hardware w ill clear WDCE after four clock cycles. • Bit 3 – WDE: W atchdog System Re set Enable WDE is overridden by WDRF in MCUSR. This mean s t hat WDE is always set when WDRF is set. To clear WDE, WDRF must be clea red first. T his feature ensures multiple rese ts during co nditions ca using failure , and a safe start-up after the failure. • Bit 5, 2:0 - WDP[3: 0]: W atchdog T imer Prescaler 3, 2, 1 and 0 The WDP[3:0] bits determine the Watchdog Timer p r escaling when the Watchdog Timer is running. The different pr escaling value s and their correspon ding time-out period s are shown in Table 11- 2 on page 64 . T able 1 1-1. W atchdo g T imer Configura tion WDTO N (1) WDE WDIE Mode Action on T ime-out 1 0 0 S t opped None 1 0 1 Interrupt Mode Interrupt 1 1 0 System Reset Mode Rese t 1 1 1 Interrupt and System Reset Mode Interrupt, then go to System Reset Mode 0 x x System Reset Mode Rese t T ab le 1 1-2. W atchdog Timer Prescale Select WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles T y pical T ime-out at V CC = 5.0V 0000 2K (2048) cycles 16ms 0001 4K (4096) cycles 32ms 0010 8K (8192) cycles 64ms 0011 16K (16384) cycles 0.125 s 0100 32K (32768) cycles 0.25 s 0101 64K (65536) cycles 0.5 s 0110 128K (131072) cycles 1.0 s 0111 256K (262144) cycles 2.0 s 1000 512K (524288) cycles 4.0 s 1001 1024K (1048576) cycl es 8.0 s A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 65 1010 Reserved 1011 1100 1101 1110 1111 T abl e 1 1-2. W atchdog Timer Prescale Select (Continued) WDP3 WDP2 WDP1 WDP0 Number of WDT Oscillator Cycles T y pical T ime-out at V CC = 5.0V A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 66 12. Interrupt s This section descri bes the spe cifics of the interr upt handling as perfor med in ATmega48A/PA/88A/PA/168A/PA/ 328/P. For a general explanation of the AVR interrupt handling , refer to ”Reset and Inter rupt Handlin g” on pa ge 23 . The interrupt vector s in ATmega 48A/48PA, ATme ga88A/88PA, ATmega168A/16 8PA and ATmega328/328P are gener ally the same, wit h the following differences:  Each Interrupt V ector occupies two in struction words in A Tmega1 68A/168P A and ATmega328/328P, and one instruction wo rd in A Tmega 48A/4 8P A and A T mega88A/88 P A.  A Tmega 48A/48P A does not have a separ ate Boot Loader Section. In ATmeg a88A/88PA, ATmega168A/1 68PA and ATmega32 8/328P, the Reset V e ctor is af fected by the BOOTRST fuse, and the Interrupt V ector start ad dress is af fected by the IVSEL bit in MCUCR. 12.1 Interrupt V ectors in A Tmega48A and A Tmega48P A T ab le 12-1. Reset and Interrup t V ectors in A Tm ega48A and A Tmega48P A Ve c t o r N o . Program Ad dress Source Interrupt Definition 1 0x000 RESET External Pin, Power-on Reset, Brown-out Reset and W atchdog System Reset 2 0x001 INT0 External Inte rrupt Request 0 3 0x002 INT1 External Inte rrupt 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 W atch dog T ime-o ut Interrupt 8 0x007 TIMER2 COMP A T imer/Counter2 Compare Match A 9 0x008 TIMER2 COMPB T imer/Counter2 Compare Match B 10 0x009 TIMER2 OVF T imer/Coun ter2 Overflow 11 0x00A TIMER1 CAPT T imer/Counter1 Ca pture Event 12 0x00B TIMER1 COMP A T imer/Counter1 Compare Match A 13 0x00C TIMER1 COMPB T imer/Coutner1 Co mpare Match B 14 0x00D TIMER1 OVF T imer/Counte r1 Overflow 15 0x00E TIMER0 COMP A T imer/Counter0 Compare Match A 16 0x00F TIMER0 COMPB T imer/Counter0 Compare Match B 17 0x010 TIMER0 OVF T imer/Coun ter0 Overflow 18 0x01 1 SPI, STC SPI Serial T ransfer Complete 19 0x012 USAR T , RX USART Rx Complete 20 0x013 USART , UDRE USART , Data Register Empty 21 0x014 USAR T , TX USAR T , Tx Complete 22 0x015 ADC ADC Conversion Compl ete 23 0x016 EE READY EEP ROM Ready A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 67 The most typical and general pr ogram setup for the Re set and Interrupt Vector Addres ses in ATmega 48A/4 8PA 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 ; Timer 2 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 Han dler 0x012 rjmp USART_RXC ; USART, RX Complete Handle r 0x013 rjmp USART_UDRE ; USART, UDR Empty Handler 0x014 rjmp USART_TXC ; USART, TX Complete Handle r 0x015 rjmp ADC ; ADC Conversion Complete H andler 0x016 rjmp EE_RDY ; EEPROM Ready Handler 0x017 rjmp ANA_COMP ; Analog Comparator Handler 0x018 rjmp TWI ; 2-wire Serial Interface H andler 0x019 rjmp ; SPM_RDYStore Program Memory Ready Handler ; 0x01A RESET: 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 <instr> xxx ... . .. ... ... 24 0x017 ANALOG COMP Analog Comparator 25 0x018 TWI 2-wire Serial Interface 26 0x019 SPM READY S tore Program Memory Ready T ab le 12-1. Reset and Interrup t V ectors in A Tmega 48A and A Tmega48P A (Continued ) Ve c t o r N o . Program Ad dress Source Interrupt Definition A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 68 12.2 Interrupt V ectors in A Tmega88A and A Tmega88P A Notes: 1. When the BOOTRST Fuse is programmed , the device will jump to the Boot Loa der address at reset, see ”Bo ot Loader Suppor t – Read-While-Wri te Self- Programming” on page 272 . 2. When the IVSEL bit in MCUCR is set, Inte rrupt V ectors w ill be moved to the st art of the Boot Flash Section. The address of ea ch Interr upt V ector will the n be the address in thi s table adde d to the st art address of the Boot Flash Section. Table 12 -3 on page 69 shows rese t and In terrupt Vect ors placem ent for the various c ombinations of BOOTRST and IVSEL setting s. If the program never enables an in terrup t source, the In terrupt Vector s are not u sed, and regular pro gram code can be pl aced at these locations. Th is is also the case if th e Reset Vector is in the Application section while the Inte rrupt Vectors are in the Boot section or vice ver sa. T ab le 12-2. Reset and Interrup t V ectors in A Tm ega88A and A Tmega88P A Ve c t o r N o . Program Address (2) Source Interrupt Definition 1 0x000 (1) RESET External Pin, Pow er-on Reset, Brown- out Reset an d W atchd og System Reset 2 0x001 INT0 Exte rnal Interrupt Request 0 3 0x002 INT1 Exte rnal 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 W atchdog T ime -out Interrupt 8 0x007 TIMER2 COMP A T imer/Counter2 Compare Match A 9 0x008 TIMER2 COMPB T imer/Counter2 Comp are Match B 10 0x009 TIMER2 OVF T imer/Counte r2 Overflow 11 0x00A TIMER1 CAPT T imer/Counter1 C apture Event 12 0x00B TIMER1 COMP A T imer/Counter1 Comp are Match A 13 0x00C TIMER1 COMPB T imer/Coutner1 Compare Match B 14 0x00D TIMER 1 OVF T imer/Counter1 Overflow 15 0x00E TIMER0 COMP A T imer/Counter0 Comp are Match A 16 0x00F TIME R0 COMPB T imer/Counter0 Comp are Match B 17 0x010 TIMER0 OVF T imer/Counte r0 Overflow 18 0x01 1 SPI, STC SPI Serial T ransfer Compl ete 19 0x012 USAR T , RX USART Rx Complete 20 0x013 USAR T , UDRE USART , Data Register Emp ty 21 0x014 USAR T , TX USAR T , Tx Complete 22 0x015 ADC ADC Conversion Compl ete 23 0x016 EE READY EEPROM Ready 24 0x017 ANALOG COMP Analog Comparator 25 0x018 TWI 2-wire Seri al Interface 26 0x019 SPM READY S tore Program Memory Ready A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 69 Note: 1. The Boot Reset Address is shown in Table 27-7 on page 284 . For the BOOTRST Fuse “1” means unprogrammed while “0” me ans programmed. The most typical and gener al progr am setup for the Re set and Interrupt Vector Ad dresses in ATmega88A/88 PA 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 ; Timer 2 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 ; Timer 1 Overflow Handler 0x00E rjmp TIM0_COMPA ; Timer0 Compare A Handler 0x00F rjmp TIM0_COMPB ; Timer0 Compare B Handler 0x010 rjmp TIM0_OVF ; Timer 0 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 Hand ler 0x016 rjmp EE_RDY ; EEPROM Ready Handler 0x017 rjmp ANA_COMP ; Analo g Comparator Handler 0x018 rjmp TWI ; 2-wire Serial Interface Hand ler 0x019 rjmp SPM_RDY ; Store Program Memory Ready Handler ; 0x01A RESET: 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 <instr> xxx When the BOOTRST Fuse is unprogrammed, the Boot se ction size set to 2Kbytes and the IVSEL bit in the MCUCR Re gister is se t before a ny interrup ts are en abled, th e most ty pical and ge neral prog ram setup for the Reset and Interr upt Vector Addres ses in ATmega88A/88 PA 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 T ab le 12-3. Reset and Interrup t V ectors Placem ent in A Tme ga88A and A Tmega88P A (1) BOOTRST IVSEL Reset Addr ess Interrupt V ectors St art Add ress 1 0 0x000 0x001 1 1 0x000 Boot Re set Addres s + 0x 001 0 0 Boot Reset Addr ess 0x001 0 1 Boot Reset Addr ess Boot Reset Address + 0x001 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 70 0x002 ldi r16,low(RAMEND) 0x003 out SPL,r16 0x004 sei ; Enable interrupts 0x005 <instr> 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 se ction size set to 2Kbyt es, the most typical and general progr am setup for the Reset a nd Interrupt Vector Addr esses in ATmega88A/8 8PA is: Address LabelsC odeComments .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 <instr> xxx When the BOOTRST Fu se is progr ammed, th e Boot sec t ion size set to 2Kbytes an d the IVSEL bit in the MCUCR Re gister is se t before a ny interrup ts are en abled, th e most ty pical and ge neral prog ram setup for the Reset and Interr upt Vector Addres ses in ATmega88A/88 PA 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 RAM 0xC1C ldi r16,low(RAMEND) 0xC1D out SPL,r16 0xC1E sei ; Enable interrupts 0xC1F <instr> xxx A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 71 12.3 Interrupt V ectors in A Tmega168A and A Tmega168P A Notes: 1. When the BOOTRST Fuse is programmed , the device will jump to the Boot Loa der address at reset, see ”Bo ot Loader Suppor t – Read-While-Wri te Self- Programming” on page 272 . 2. When the IVSEL bit in MCUCR is set, Inte rrupt V ectors w ill be moved to the st art of the Boot Flash Section. The address of ea ch Interr upt V ector will the n be the address in thi s table adde d to the st art address of the Boot Flash Section. Table 12 -5 on page 72 shows rese t and In terrupt Vect ors placem ent for the various c ombinations of BOOTRST and IVSEL setting s. If the program never enables an in terrup t source, the In terrupt Vector s are not u sed, and T ab le 12-4. Reset and Interrup t V ecto rs in A Tmega 168A and A Tmega168P A Ve c t o r N o . Program Address (2) Source Interrupt Definition 1 0x0000 (1) RESET External Pin, Power-o n Reset, Brown- out Reset and Watchdog System Reset 2 0x0002 INT0 Extern al Interrupt Request 0 3 0x0004 INT1 Extern al 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 0x000 C WDT W atchdog T ime-out Interrupt 8 0x000E TIMER2 COMP A T imer/Counter2 Compare Match A 9 0x0010 TIMER2 COMPB T imer/Counter2 Comp are Match B 10 0x0012 TIMER 2 OVF T imer/Counter2 Overflow 11 0x0014 TIMER1 CAPT T imer/Counter1 C apture Event 12 0x0016 TIMER1 COMP A T imer/Counter1 Comp are Match A 13 0x0018 TIMER1 COMPB T imer/Coutner1 Compare Match B 14 0x001A TI MER1 OVF Ti mer/Counter1 Overflow 15 0x001 C TIMER0 COMP A T imer/Counter0 Compare Match A 16 0x001E TIMER0 COMPB T imer/Counter0 Compare Match B 17 0x0020 TIMER 0 OVF T imer/Counter0 Overflow 18 0x0022 SPI, STC SPI Serial T ransfer Comple te 19 0x0024 USART , RX USAR T Rx Complete 20 0x0026 USART , UDRE USART , Data Register Emp ty 21 0x0028 USART , TX USART , Tx Comple te 22 0x002A ADC ADC Conve rsion Complete 23 0x002 C EE READY EEPROM Ready 24 0x002E ANALOG COMP Anal og Comp arator 25 0x0030 TWI 2-wire Serial Interface 26 0x0032 SPM READY S tore Program Memory Ready A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 72 regular pro gram code can be pl aced at these locations. Th is is also the case if th e Reset Vector is in the Application section while the In te rrupt Vectors are in the Boot section or vice ver sa. Note: 1. The Boot Reset Address is shown in Table 27-7 on page 284 . For the BOOTRST Fuse “1” means unprogrammed while “0” me ans programmed. The most typical and ge neral progra m setup for the Reset and In terrupt Vector Addr esses in ATmega168A/1 68PA 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 Ha ndler 0x000E jmp TIM2_COMPA ; Timer2 Compare A Handler 0x0010 jmp TIM2_COMPB ; Timer2 Compare B Handler 0x0012 jmp TIM2_OVF ; Timer 2 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 ; Timer 1 Overflow Handler 0x001C jmp TIM0_COMPA ; Timer0 Compare A Handler 0x001E jmp TIM0_COMPB ; Timer0 Compare B Handler 0x0020 jmp TIM0_OVF ; Timer 0 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 Co mplete Handler 0x002C jmp EE_RDY ; EEPROM Ready Handler 0x002E jmp ANA_COMP ; Analo g Comparator Handler 0x0030 jmp TWI ; 2-wire Serial Int erface Handler 0x0032 jmp SPM_RDY ; Store Program Memory Ready Handler ; 0x0034 RESET: ldi r16, high(RAMEND); Main program start 0x0035 out SPH,r16 ; Set Stack Pointer to top of RAM 0x0036 ldi r16, low(RAMEND) 0x0037 out SPL,r16 0x0038 sei ; Enable interrupts 0x0039 <instr> xxx ... ... ... ... When the BOOTRST Fuse is unprogrammed, the Boot se ction size set to 2Kbytes and the IVSEL bit in the MCUCR Re gister is se t before a ny interrup ts are en abled, th e most ty pical and ge neral prog ram setup for the Reset and Interr upt Vector Addre sses in ATmega 168A/168PA is: T ab le 12-5. Reset and Interrup t V ectors Placem ent in A Tme ga168A and A Tmega168P A (1) BOOTRST IVSEL Reset Addr ess Interrupt V ectors S t art Address 1 0 0x000 0x002 1 1 0x000 Boot Reset Address + 0x0002 0 0 Boot Reset Addr ess 0x002 0 1 Boot Reset Addr ess Boot Reset Address + 0x0002 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 79 13. External Interrupt s The External Inter rupts are trigge red by the INT0 and INT 1 pins or any of the P CINT23...0 pins. O bserve th at, if enabled, the interrup ts will trigger even if the INT0 and INT1 or PC INT23...0 pins are config ured as outputs. This feature provides a way of ge nerating a software interrup t. The pin change interrup t PCI2 will trigger if any enabled PCINT[23:16] pin toggles. The pin c hange interrupt PCI1 will trigger if any enabled PCINT[14:8] pin toggles. The pin change interrupt PCI0 will trigger if any enabled PCINT[7:0] pin toggles. The PCMSK2, PCMSK1 and PCMSK0 Registers contro l which pins co ntribute to the pin change interrupts. Pin ch ange interrup ts on PCINT23...0 are detected asynchrono usly. This implies th at these interrupts can be used for waking the part also from sleep modes other than Idle mode. The External In terrup ts can be triggere d by a falling or risi ng edge or a low level. This is set up as indicated in the specification for the Exte rnal Inte rrupt Control Register s – EICRA (INT2:0). When the external interr upt is enabled and is configured as lev el triggered, the interrupt will trigger as long as the pin is held low. Low lev el interrup ts and the edge interrupt on INT 2:0 are detected asynchronously. This implie s that these interrupts can be used for waking the part also fr om sleep mo des other than Idle mode. Th e I/O clock is halted in all sleep modes except Idle mo de. Note: Note that if a level triggered interrupt is used for wa ke-up from Power-down, the required l evel must be held lo ng enough for the MCU to complete the wa ke-up to trigger the level interrupt. If the level disapp ears before the end of the S tart-up T ime, the MCU will still wake up, but no interru pt will be generated. The star t-up time is defined by the SUT and CKSEL Fuses as described in ”System Clock an d Clock Options” on page 36 . 13.1 Pin Change Interrupt T iming An examp le of timing of a pin cha nge interrup t is shown in Figure 1 3-1 . Figure 13 -1. Timin g of pin ch ange inte rrupts 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 80 13.2 Register Description 13.2.1 EICRA – External Inte rrupt Control Register A The External In terrup t Control Register A contains control bits for interru pt sense control. • Bit 7:4 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 3, 2 – ISC1 1, ISC10: In terrupt Sense Contro l 1 Bit 1 and Bit 0 The External Interrupt 1 is activated by the external pin INT1 if the SREG I-flag and th e corresponding interrupt mask are set. The level and edge s on the externa l INT1 pin that activate the interr upt are de fined in T able 13-1 . The value on th e INT1 pin is sampled before de tecting edges . If edge or toggle inte rrupt is selected, pu lses that last longer than one clock period will generate an interr upt. Shorter pulses are no t ensured to generate an interrupt. If low level inte rrupt is selected, the low level must be he ld until the completi on of the cu rrently executing instru ction to genera te an interrupt. • Bit 1, 0 – ISC01, ISC00: Interrupt Sen se Contro l 0 Bit 1 an d Bit 0 The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and th e corresponding interrupt mask are set. The level and edge s on the externa l INT0 pin that activate the interr upt are de fined in T able 13-2 . The value on th e INT0 pin is sampled before de tecting edges . If edge or toggle inte rrupt is selected, pu lses that last longer than one clock period will generate an interr upt. Shorter pulses are no t ensured to generate an interrupt. If low level inte rrupt is selected, the low level must be he ld until the completi on of the cu rrently executing instru ction to genera te an interrupt. B i t 7654321 0 (0x69) – – – – ISC1 1 ISC10 ISC01 ISC00 EICRA Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 T ab le 13-1. Interrupt 1 Sense Con trol ISC1 1 ISC10 Description 0 0 The low level of INT1 generates an interru pt request. 0 1 Any logical change on IN T1 generates an interrupt req uest. 1 0 The falling edge of INT1 generates an interrup t request. 1 1 The rising edge of INT1 gene rates an interrupt request. T ab le 13-2. Interrupt 0 Sense Con trol ISC01 ISC00 Description 0 0 The low level of INT0 generates an interru pt request. 0 1 Any logical change on IN T0 generates an interrupt req uest. 1 0 The falling edge of INT0 generates an interrup t request. 1 1 The rising edge of INT0 gene rates an interrupt request. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 81 13.2.2 EIMSK – External Interrupt Mask Register • Bit 7:2 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 1 – INT1: External In terrupt Request 1 Enable When the INT1 bit is set (one) and the I- bit in the Status Register (SREG) is set (one), th e external pin interru pt is enabled. The In terrupt Sense Con trol1 bits 1/0 (ISC1 1 and ISC10) in th e External Inte rrupt Control Register A (EICRA) define whether the external in terrupt 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 correspon ding interrupt o f External Inte rrupt Requ es t 1 is executed from the INT1 Interrupt Vector. • Bit 0 – INT0: External In terrupt Request 0 Enable When the INT0 bit is set (one) and the I- bit in the Status Register (SREG) is set (one), th e external pin interru pt is enabled. The In terrupt Sense Con trol0 bits 1/0 (ISC0 1 and ISC00) in th e External Inte rrupt Control Register A (EICRA) define whether the external in terrupt 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 correspon ding interrupt o f External Inte rrupt Requ es t 0 is executed from the INT0 Interrupt Vector. 13.2.3 EIFR – External Interrupt Flag Register • Bit 7:2 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 1 – INTF1: External Interru pt Flag 1 When an edge or logic change on the INT1 pin triggers an inte rrupt request, INTF1 becomes set (one). If the I- bit in SREG and the INT1 bit in EIMSK are set (one), the MCU will jump to the correspo nding Interrupt Vector. The flag is cleared when the in terrupt routine is ex ecuted . Alternatively , the flag can be c leared by writing a logical one to it. This flag is alway s cleared wh en INT1 is config ured as a level interrupt. • Bit 0 – INTF0: External Interru pt Flag 0 When an edge or logic change on the INT0 pin triggers an inte rrupt 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 correspo nding Interrupt Vector. The flag is cleared when the in terrupt routine is ex ecuted . Alternatively , the flag can be c leared by writing a logical one to it. This flag is alway s cleared wh en INT0 is config ured as a level interrupt. B i t 76543210 0x1D (0x3D) –––––– I N T 1 I N T 0 E I M S K R e a d / W r i t e RRRRRR R / W R / W I n i t i a l V a l u e 00000000 B i t 76543210 0x1C (0x3C) –––––– I N T F 1 I N T F 0 E I F R R e a d / W r i t e RRRRRR R / W R / W I n i t i a l V a l u e 00000000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 82 13.2.4 PCICR – Pi n Change Interrupt Control Register • Bit 7:3 – Reserve d These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 2 – PCIE2: Pin Change Interrupt Ena ble 2 When the PCIE2 bit is set (one ) and the I- bit in the Status Register (SREG) is set (one ), pin change inter rupt 2 is enabled. Any change on any enabled PCINT[23:16] pin w ill cause an in terrupt. The corresponding interrupt of Pin Change Interr upt Request is ex ecuted from the PCI2 Interr upt Ve ctor. PCINT [23:16] pins ar e enabled individually by the PCMSK2 Register . • Bit 1 – PCIE1: Pin Change Interrupt Ena ble 1 When the PCIE1 bit is set (one ) and the I- bit in the Status Register (SREG) is set (one ), pin change inter rupt 1 is enabled. Any change on any enabled PCINT[14:8] pin will caus e an interr upt. The corresponding interrupt of Pin Change In terrupt R equest is ex ecuted fr om the PCI1 Interrup t Vector. PCINT[ 14:8] pins are enab led individu ally by the PCMSK1 Register. • Bit 0 – PCIE0: Pin Change Interrupt Ena ble 0 When the PCIE0 bit is set (one ) and the I- bit in the Status Register (SREG) is set (one ), pin change inter rupt 0 is enabled. Any change on any enabled PCINT[7:0] pin will cause an interrupt. The correspo nding interrupt of Pin Change Interr upt Request is executed from the PCI0 Interrupt Vector. PCINT[ 7:0] pins are enabled individually by the PCMSK0 Register. 13.2.5 PCIFR – Pin Change Interrupt Flag Register • Bit 7:3 – Reserve d These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 2 – PCIF2: Pin Change Interrupt Flag 2 When a logic change on any PCINT[23:16] pin trig gers an interrupt re ques t, PCIF2 becomes set (one). If the I- bit in SREG and the PCIE2 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the in terrupt routine is ex ecuted . Alternatively , the flag can be c leared by writing a logical one to it. • Bit 1 – PCIF1: Pin Change Interrupt Flag 1 When a logic change on any PCINT[14:8] pin triggers an interr upt request, PCIF1 be comes set (one). If the I- bit in SREG and the PCIE1 bit in PCICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the in terrupt routine is ex ecuted . Alternatively , the flag can be c leared by writing a logical one to it. B i t 76543210 (0x68) – – – – – PCIE2 PCIE1 PC IE0 PCICR R e a d / W r i t e RRRRR R / W R / W R / W I n i t i a l V a l u e 00000000 B i t 76543210 0x1B (0 x3B) ––––– P C I F 2 P C I F 1 P C I F 0 P C I F R R e a d / W r i t e RRRRR R / W R / W R / W I n i t i a l V a l u e 00000000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 83 • Bit 0 – PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT[7:0] pin tri ggers an interrupt re quest, PC IF0 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 in terrupt routine is ex ecuted . Alternatively , the flag can be c leared by writing a logical one to it. 13.2.6 PCMSK2 – Pin Change M ask Register 2 • Bit 7:0 – PCINT[23:16]: Pin Change Enable Mask 23...16 Each PCINT[23:16]- bit selects whether pin change in terrupt is enabled on the corresponding I/O pin . If PCINT[23:16] is set and the PCIE2 bi t in PCICR is set, pin ch ange interrupt is e nabled on the corr esponding I/O pin. If PCINT[23:16] is cleared, pin change inte rrupt on th e correspo nding I/O pin is disable d. 13.2.7 PCMSK1 – Pin Change M ask Register 1 • Bit 7 – Reserved This bit is an unused bit in the ATmega48A/PA/88A/PA/168A/PA/328 /P, and will always read as zero. • Bit 6:0 – PCINT [14:8]: Pin Change Enable Mask 14...8 Each PCINT[14:8]-bit sele cts whether pin change inte rrupt is en abled on the corres ponding I/O pin. If PCINT[14:8] is set and the PCIE1 bit in PCICR is set, pin change interr upt is enab led on th e correspond ing I/O pin. If PCINT[14:8] is cleared, pin change inte rrupt on the corresponding I/O pin is disabled . 13.2.8 PCMSK0 – Pin Change M ask Register 0 • Bit 7:0 – PCINT[7:0]: Pin Change Enable Mask 7...0 Each PCINT[7:0] bit se lects whether pin chan ge interrupt is enabled on th e correspo nding I/O pin. If PCINT[7:0] is set and the PCIE0 bit in PCICR is set, pin change interr upt is enabled on the co rresponding I/O pi n. If PCINT[7:0] is cleared, pin change interrup t on the co rresponding I/O pin is di sabled. B i t 765432 1 0 (0x6D) PCINT23 PCINT22 PCINT21 PCINT20 PCINT19 P CINT18 PCINT17 PCINT16 PCMSK2 Read/Write R/W R/W R/W R/W R /W R/W R/W R/W I n i t i a l V a l u e 000000 0 0 B i t 7 65432 1 0 (0x6C) – PCINT14 PCINT13 PCINT12 PC INT1 1 PCINT10 PCINT9 PCINT8 PCMSK1 Read/Write R R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 0 00000 0 0 B i t 76543210 (0x6B) PCINT7 PCINT6 PCINT5 PCINT4 PCIN T3 PCINT2 PCINT1 PCINT0 PCMSK0 Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 84 14. I/O-Port s 14.1 Overview All AVR ports have true Read- Modify-Write functionality wh en used as gener al digital I/ O ports. This means that the direction o f one port pin can be change d without unin tentionally chang ing the di rection of any other pin with the SBI and CBI in structions. The same a pplies when c han ging drive value (if configured as outpu t) or enabling/disa bling 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 dis plays directly. All port pins have ind ividually selectable pull-up re sist ors with a suppl y-vol tage invaria nt resistance. All I/O pins have pr otection diodes t o both V CC and Ground as ind icated in Figure 14 -1 . Refer to ”E lectrical Characte ristics – (T A = -40°C to 85°C)” o n page 30 8 for a comple te li st of par ameters. Figure 14 -1. I/O Pin Equivalen t Schematic All registers and bit refer ences in this section are wr itten in ge neral form. A lower case “x” represents th e numbering le tter for the po rt, and a lowe r case “n” repr esents the bit n umber. Howeve r, when using the register or bit defines in a program, the prec ise form must b e used. For exam ple, PORT B3 for bit no. 3 in Port B, here documented genera lly as PORTxn. The physical I/O Registers an d bit locations are listed in ”Register Description” on page 10 0 . Three I/O memor y address locations ar e allocated for each port, one each for the Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Po rt Input Pins I/O location is read only, while the Data Register an d the Data Direction Reg ister are re ad/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the correspo nding bit in the Data Register. In addition, the Pull-up Disable – PUD bit in MCUCR disables the pull-up fu nction for all pins in all ports when s et. Using the I/O port as Ge neral Digital I/O is described in ” Ports as General Dig ital I/O” on page 85 . Most port pins are multiplexed with alterna te functions fo r the peripheral fea tures on the device. How each alter nate function interferes with the port pin is descr ibed in ”Alternate Por t Functions” on page 89 . Refer to the individual module sections for a full description o f the alte rnate functions. Note th at enablin g the al ternate function of some of the port pins does no t affec t the use of the o ther pi ns in the port as general digi tal I/O. C pin Logic R pu S ee Figure "General Digital I/O" f or Details Pxn A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 85 14.2 Port s as General Digit al I/O The ports are bi-directiona l I/O ports with optional internal pull-ups. Figure 14-2 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 14-2. G eneral Digita l I/O (1) Note: 1. WRx, WPx, WDx, RRx, RPx, an d RDx are common to all pins within the same port. clk I/O , SLEEP , and PU D are common to al l ports . 14.2.1 Configuring the Pin Each port pin con sists of three re gister bits: DDxn , PORTxn, and PINx n. As shown in ”Register Descri ption” on page 1 00 , the DDxn bits ar e accessed at the DDRx I/O addr ess, the PORTxn bits at the POR Tx I/O address, and the PINxn bits at the PINx I/O address. The DDxn bit in the DDRx Register selects th e directio n of this pin. If DDxn is written logic one, Pxn is configure d as an output p in. If DDxn is written logic zero, P xn is con figured as an input pin. If PORTxn is written logic one when the pin is configured a s an inpu t pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written logic ze ro or the pin has to be configured as an outp ut pin. The port pins are tri- stated when reset conditio n becomes active, even if no clocks are running. If PORTxn is written logic one when the pin is configur ed as an output pin, the por t pin is driven high (one ). If PORTxn is written logic zero w hen th e pin is con figured as an output pin , the port pin is driven low (zero). 14.2.2 T oggling the Pin Writing a logic on e to PINxn toggles the value of PORTxn, independe nt on the value of DDRxn. Note that the SBI instruction can be used to t oggle one single bit in a por t. clk RPx RRx RDx WDx PUD S YNCHRONIZER WDx: WRITE DDRx WRx: WRITE POR Tx RRx: READ POR Tx REGI S TER RPx: READ POR Tx PIN PUD: PULLUP DI S ABLE clk I/O : I/O CLOCK RDx: READ DDRx D L Q Q RE S ET RE S ET Q Q D Q Q D CLR PORTxn Q Q D CLR DDxn PINxn D ATA B U S S LEEP S LEEP: S LEEP CONTROL Pxn I/O WPx 0 1 WRx WPx: WRITE PINx REGI S TER A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 86 14.2.3 Switching Between Input and Ou tput When switching between tri-state ({ DDxn, PORTxn} = 0b00) and outp ut high ({ DDxn, PORTxn} = 0b11 ), an intermedia te state with either pull-up enab led {DDxn, PORTxn} = 0b01) or outp ut low ({DDxn, PORTxn} = 0b10) must occur. Norma lly, the pull-up enabled state is fully accept able, as a high-imped ance environment will not notice the differe nce between a strong hig h driver and a pul l-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all pull-ups in al l ports. Switching between inp ut with pull-up and output low gener ates the same pr oblem. The user must use either the tri-state ({DDxn, PORTxn } = 0b00) or the output high st ate ({DDxn, PORTxn} = 0b11) as an intermediate step. Table 14 -1 summarizes the control sig nals for the pin value . 14.2.4 Reading the Pin V alue Independent of the se tting of Data Direction bit DDxn, th e port pin can be rea d through the PINxn Register bi t. As shown in Figure 14- 2 , the PINxn Register bit and the pr eceding latch constitute a synchron izer. This is needed to avoid metastability if the physical pin c hanges value near the edge of the internal cl ock, but it also introduces a dela y. Figure 14-3 shows a timing diagram of the s ynchroniza tion when r eading a n extern ally applied pin value. The maximum a nd minimum propagation d elays are denoted t pd,max and t pd,min respectively. Figure 14-3. Synchronization when Reading an Externally Applied Pin value Consider the clock period starting shortly af ter the first falling edge of the system clock. The latch is closed when the cloc k is low, and goes tran sparent when the clock is high, as indica ted by the sh aded 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 su cceeding positive clock ed ge. As indicated by the two ar rows tpd,max and tpd,min, a si ngle T able 14-1. Port Pin Configurations DDxn PORTxn PUD (in MCUCR) I/O Pull-up Comment 0 0 X Input No T ri-state (Hi-Z) 0 1 0 Input Ye s Pxn will source current if ext. pulled low . 0 1 1 Input No T ri-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 IN S TRUCTION S S YNC LATCH PINxn r17 XXX S Y S TEM CLK t pd, max t pd, min A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 87 signal transition on the pin will be del ayed between ½ and 1½ s ystem clock period depen ding upon the time of assertion. When reading ba ck a software assigned pin va lue, a nop instruction must be in serted as indicated in Figure 14- 4 . The out instr uction sets the “SYNC LATCH” sign al at the p ositive edge of the clock. In this case, the de lay tpd through the synchronizer is 1 system clock period. Figure 14-4. Synchronization when Reading a Software Assigned Pin Value The following code e xample shows how to set port B pins 0 and 1 hig h, 2 and 3 low, and define the port pi ns from 4 to 7 a s input with pull-ups a ssigned to port pins 6 and 7. The re sulting pin value s are read back again, bu t as previously discussed, a nop instr uction is included to be able to read back the value rece ntly assigned to some of the pins. out PORTx, r16 nop in r17, PINx 0xFF 0x00 0xFF SYSTEM CLK r16 INSTRUCTIONS SYNC LATCH PINxn r17 t pd A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 88 Note: 1. For the assembly program, two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1, 6, and 7, unti l the directi on bits are correctly se t, defini ng bit 2 and 3 as low and red efining bits 0 and 1 as strong h igh driv ers. 14.2.5 Digit al Input Enable and Sleep Modes As shown in Figure 14- 2 , the digital input signa l can be clamped to gr ound at the input of the Schmitt Trigger. The signal denoted SL EEP in the figure, is set by the MCU Sleep Controller in Po wer-down mode, Power-save mode, and Sta ndby mode to avoid hig h power consumpt ion if some input signals are left floating, or have an analog sig nal level c lose to V CC /2. SLEEP is overridden for por t pins enabled as external in terr upt pins. If the external interrupt re quest is not enabled, SLEEP is active also for th ese pins. SLEEP is also overridden by various other altern ate functi ons as describe d in ”Alternate Po rt Functions” on page 8 9 . If a logic high level (“one”) is presen t on an asynchron ous external interrupt pin con figured as “Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the ex ternal interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned Sl eep mode, as the clamping in these sl eep mode pro duce s the requested logic change . 14.2.6 Unconnected Pins If some pins are unu sed, it is recomme nded to ensure th at these p ins have a defined le vel. Even tho ugh most of the digital inputs are d isabled i n the deep slee p modes a s described above, floating inp uts should be avoided to reduce c urrent con sumption in all othe r modes wh ere th e digital inputs are e nabled (Reset, Acti ve mode and Idle mode). Assembly Code Example (1) ... ; Define pull-ups and set outputs high ; Define directions for p ort pins ldi r16,(1<<PB7)|(1<<PB6 )|(1<<PB1)|(1<<PB0) ldi r17,(1<<DDB3)|(1<<DDB2)|(1< <DDB1)|(1<<DDB0) out PORTB,r16 out DDRB,r17 ; Insert nop for synchron ization nop ; Read port pins in r16,PINB ... C Code Example unsigned char i; ... /* Define pull-ups and se t outputs high */ /* Define directions for port pins */ PORTB = (1<<PB7)|(1<<PB6) |(1<<PB1)|(1<<PB0); DDRB = (1<<DDB3)|(1<<DDB2 )|(1<<DDB1)|(1<<DDB0); /* Insert nop for synchro nization */ __no_operation(); /* Read port pins */ i = PINB; ... A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 95 The alte rnate pin configurat ion is as follows: • RESET /PCINT14 – Port C, Bit 6 RESET , Reset pin: When the RSTDISBL Fuse is programmed, this pin functions as a norma l I/O pin, and the part will have to rely on Power-on Reset and Brown-out Reset as its res e t sources. When the RSTDISBL Fuse is unprogramm ed, the rese t circuitry is co nnected to the pin, and the pin can not be used as an I/O p in. If PC6 is used as a reset pin, DDC6, PORTC6 and PINC6 will all read 0. PCINT14: Pin Change Inter rupt source 14. The PC6 pin can serve as an external interr upt source. • SCL/ADC5/PCINT13 – Port C, Bit 5 SCL, 2-wire Serial Interface Clock: When the TWEN bit in TWCR is set (one) to enable the 2-wire Ser ial Interface, pin PC5 is disconnected from the port and becomes th e Serial Clock I /O pin for the 2-wire Serial Interface. In this mode, ther e is a sp ike filter on the pin to suppress spikes shorter th an 50 ns on the input sign al, and the pin is drive n by an open drain driver with sl ew-r ate limitation. PC5 can also be used as ADC in put Channel 5. Note th at ADC i nput channe l 5 uses d igital powe r. PCINT13: Pin Change Inter rupt source 13. The PC5 pin can serve as an external interr upt source. • SDA/ADC4/PC INT12 – Port C, Bit 4 SDA, 2-wire Serial Interface Data: When the TWEN bit in TWCR is set (one) to enable the 2- wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, ther e is a sp ike filter on the pin to suppress spikes shorter th an 50 ns on the input sign al, and the pin is drive n by an open dr ain driver with slew -rate limitation. PC4 can also be used as ADC in put Channel 4. Note th at ADC i nput channe l 4 uses d igital powe r. PCINT12: Pin Change Inter rupt source 12. The PC4 pin can serve as an external interr upt source. • ADC3/PCINT1 1 – Port C, Bit 3 PC3 can also be used as ADC in put Channel 3. Note th at ADC i nput channe l 3 uses a nalog po wer. PCINT11: Pin Change Inter rupt source 11. The PC3 pin can serve as an external interr upt source. • ADC2/P CINT10 – Port C, Bit 2 PC2 can also be used as ADC in put Channel 2. Note th at ADC i nput channe l 2 uses a nalog po wer. PCINT10: Pin Change Inter rupt source 10. The PC2 pin can serve as an external interr upt source. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 96 • ADC1/PCINT9 – Port C, Bit 1 PC1 can also be used as ADC in put Channel 1. Note th at ADC i nput channe l 1 uses a nalog po wer. PCINT9: Pin Change Interr upt source 9. The PC1 pin can serve as an external interrup t source. • ADC0/PCINT8 – Port C, Bit 0 PC0 can also be used as ADC in put Channel 0. Note th at ADC i nput channe l 0 uses a nalog po wer. PCINT8: Pin Change Interr upt source 8. The PC0 pin can serve as an external interrup t source. Table 14 -7 and Table 14- 8 relate the alternate function s of Port C to the overriding signals shown in Figu re 14-5 on page 89 . Note: 1. When enabled, the 2-wire Serial Interface enabl es slew -rate controls on the output pi ns PC4 and PC5. This is not shown in the figure. In additi on, spike filters ar e connected betw een the AIO outpu t s shown in the port figure an d the digital logic of the TWI mo dule. T ab le 14-7. Overriding Signals for Alternate Functions in PC6...PC4 (1) Signal Name PC6/RESET /PCINT14 PC5/SCL/ADC5/PCINT13 PC4/SDA/ADC4/PCINT12 PUOE RSTDISBL TWEN TWEN PUOV 1 PORT C5 • PUD PORTC4 • PUD DDOE RSTDISBL TWEN TWEN DDOV 0 SCL_OUT SDA_OUT PVOE 0 TWEN TWEN PVOV 0 0 0 DIEOE RSTDISBL + PCINT14 • PCIE1 PCINT13 • PCIE1 + ADC5D PCINT12 • PCIE1 + ADC4D DIEOV RSTDISBL PCINT13 • PCIE1 PCINT12 • PCIE1 DI PCINT14 INPUT PCINT13 INPUT PCINT12 INPUT AIO RESET INPUT ADC5 INPUT / SCL INPUT ADC4 INPUT / SDA INPUT A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 97 14.3.3 Alternate Function s of Port D The Port D pins with altern ate fu nctions are shown in Table 14-9 . T ab le 14-8. Overriding Signals for Alternate Functions in PC3...PC0 Signal Name PC3/ADC3/ PCINT1 1 PC2/ADC2/ PCINT10 PC1/ADC1/ PCINT9 PC0/ADC0/ PCINT8 PUOE 0 0 0 0 PUOV 0 0 0 0 DDOE 0 0 0 0 DDOV 0 0 0 0 PVOE 0 0 0 0 PVOV 0 0 0 0 DIEOE PCINT1 1 • PCIE1 + ADC3D PCINT10 • PCIE1 + ADC2D PCINT9 • PCIE1 + ADC1D PCINT8 • PCIE1 + ADC0D DIEOV PCINT1 1 • PCIE1 PCINT10 • PCIE1 PCINT9 • PCIE1 PCINT8 • PCIE1 DI PCINT1 1 INPUT PCINT10 INPUT PCINT9 INPUT PCINT8 INPUT AIO ADC3 INPUT ADC2 INPUT ADC1 INPUT ADC0 INPUT T ab le 14-9. Port D Pins Alternate Functions Port Pin Alternate Fu nction PD7 AIN1 (Analog Comparator Negative Input) PCINT23 (Pin Change In terrupt 23) PD6 AIN0 (Analog Comparator Positive Input) OC0A (T i mer/Counter0 Outp ut Compare Match A Output) PCINT22 (Pin Change In terrupt 22) PD5 T1 (T ime r/Counter 1 External Counter Inpu t) OC0B (T i mer/Counter0 Outp ut Compare Match B Output) PCINT21 (Pin Change In terrupt 21) PD4 XCK (USAR T External Clock Input/Output) T0 (T ime r/Counter 0 External Counter Inpu t) PCINT20 (Pin Change In terrupt 20) PD3 INT1 (External Interrupt 1 Input) OC2B (T i mer/Counter2 Outp ut Compare Match B Output) PCINT19 (Pin Change In terrupt 19) PD2 INT0 (External Interrupt 0 Input) PCINT18 (Pin Change In terrupt 18) PD1 TXD (USAR T Output Pin) PCINT17 (Pin Change In terrupt 17) PD0 RXD (USAR T Input Pin) PCINT16 (Pin Change In terrupt 16) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 98 The alte rnate pin configurat ion is as follows: • AIN1/OC2B/PCINT23 – Port D, Bit 7 AIN1, Analog Comparator Negative Input. Configure th e port pin as input with the internal p ull-up switched off to avoid the digita l port function from interfer ing with th e function of the Anal og Comparator. PCINT23: Pin Change Inter rupt source 23. The PD7 pin can serve as an external interr upt source. • AIN0/OC0A/PCINT22 – Port D, Bit 6 AIN0, Analog Comparator Positive Input. Config ure the port pin a s input with the internal pull- up switched off to avoid the digita l port function from interfer ing with th e function of the Anal og Comparator. OC0A, O utput Com pare Ma tch outp ut: The PD6 pin can serve as an ex ternal outp ut for th e Timer/C ounter0 Compare Match A. The PD6 pin has to b e configured a s an output (DDD6 set (one)) to serve this function. The OC0A pin is also th e output pin for the PWM mode ti mer functio n. PCINT22: Pin Change Inter rupt source 22. The PD6 pin can serve as an external interr upt source. • T1/OC0B/PCINT21 – Port D, Bit 5 T1, Timer/Counter1 counter source. OC0B, O utput Com pare Ma tch outp ut: The PD5 pin can serve as an ex ternal outp ut for th e Timer/C ounter0 Compare Match B. The PD5 pin has to b e configured a s an output (DDD5 set (one)) to serve this function. The OC0B pin is also th e output pin for the PWM mode ti mer functio n. PCINT21: Pin Change Inter rupt source 21. The PD5 pin can serve as an external interr upt source. • XCK/T0/PCINT20 – Port D, Bit 4 XCK, USART ex ternal clock. T0, Timer/Counter0 counter source. PCINT20: Pin Change Inter rupt source 20. The PD4 pin can serve as an external interr upt source. • INT1/OC2B/PCINT 19 – Port D, Bit 3 INT1, External Interrupt source 1: The PD3 pi n can serve as an external interr upt source. OC2B, O utput Com pare Ma tch outp ut: The PD3 pin can serve as an ex ternal outp ut for th e Timer/C ounter0 Compare Match B. The PD3 pin has to b e configured a s an output (DDD3 set (one)) to serve this function. The OC2B pin is also th e output pin for the PWM mode ti mer functio n. PCINT19: Pin Change Inter rupt source 19. The PD3 pin can serve as an external interr upt source. • INT0/PCINT18 – Port D, Bit 2 INT0, External Interrupt source 0: The PD2 pi n can serve as an external interr upt source. PCINT18: Pin Change Inter rupt source 18. The PD2 pin can serve as an external interr upt source. • TXD/PCINT17 – Port D, Bit 1 TXD, Transmit Data (Dat a output pin for the USART). Wh en the USART Transmitter is enabled , this pin is configured as an output rega rdless of the value of DDD1. PCINT17: Pin Change Inter rupt source 17. The PD1 pin can serve as an external interr upt source. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Data Sheet Complete DS40002061A-page 99 • RXD/PCINT16 – Port D, Bit 0 RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the US ART forc es this pin to be an input, the pull-up can still be contr olled by the PORTD0 bit . PCINT16: Pin Change Inter rupt source 16. The PD0 pin can serve as an external interr upt source. Table 14 -10 and Table 14-11 relate th e alternate functions of Port D to the overridi ng signals shown in Figure 14-5 on page 89 . T ab le 14-10. Over riding Signals for Alternate Fun ctions PD7...PD4 Signal Name PD7/AIN1 /PCINT23 PD6/AIN0/ OC0A/PCINT 22 PD5/T1/OC0B/ PCINT21 PD4/XCK/ T0/PCI NT20 PUOE 0 0 0 0 PUO 0 0 0 0 DDOE 0 0 0 0 DDOV 0 0 0 0 PVOE 0 OC0A ENABLE OC0B ENABLE UMSEL PVOV 0 OC0A OC0B XCK OUTPUT DIEOE PCINT23 • PCIE2 PCINT22 • PCIE2 PCINT21 • PCIE2 PCINT20 • PCIE2 DIEOV 1 1 1 1 DI PCINT23 INPUT PCINT22 INPUT PCINT21 INPUT T1 INPUT PCINT20 INPUT XCK INPUT T0 INPUT AIO AIN1 INPUT AIN0 INPUT – – T ab le 14-1 1. Overriding Signals for Alternate Functions in PD3...PD0 Signal Name PD3/OC2B/INT1/ PCINT19 PD2/INT0/ PCINT18 PD1/TXD/ PCINT17 PD0/RXD/ PCINT16 PUOE 00 TXEN RXEN PUO 000 POR TD0 • PUD DDOE 00 TXEN RXEN DDOV 0010 PVOE OC2B ENABLE 0 TXEN 0 PVOV OC2B 0 TXD 0 DIEOE INT1 ENABLE + PCINT19 • PCIE2 INT0 ENABLE + PCINT18 • PCIE1 PCINT17 • PCIE2 PCINT16 • PCIE2 DIEOV 1111 DI PCINT19 INPU T INT1 INPUT PCINT18 INPUT INT0 INPUT PCINT17 INPUT PCINT16 INPUT RXD AIO –––– A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 100 14.4 Register Description 14.4.1 MCUCR – MCU Control Register Notes: 1. BODS and BODSE only available for picoPower devices A Tme ga48P A/88P A/168P A/328P • Bit 4 – PUD: Pull- up Disable When this bit is written to one, the pull-up s in the I/O ports are d isabled even if th e DDxn and PORTxn Regi sters are configure d to enable the pull-ups ( {DDxn, PORTxn} = 0b01). See ”Con figuring the Pin” o n page 85 for more details about this feature. 14.4.2 PORTB – The P ort B Dat a Register 14.4.3 DDRB – The Port B Dat a Direction Register 14.4.4 PINB – The P ort B Input Pins Address (1) 14.4.5 PORTC – The P ort C Dat a Register 14.4.6 DDRC – The Port C Dat a Direction Register Bit 7 6 5 4 3 2 1 0 0x35 (0 x55) – BOD S (1) BODSE (1) PUD – – IVSEL IVCE MCUCR Read/Wri te R R/W R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 B i t 76543210 0x05 (0 x25) PORTB7 PORTB6 PORTB5 PORTB4 PORT B3 PORTB 2 PORTB1 PORTB0 PORTB 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 B i t 7654321 0 0x04 (0 x24) DDB7 DDB6 DDB5 DDB4 DD B3 DDB2 DDB1 DDB0 DDRB Read/Wri te 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 B i t 7654321 0 0x03 (0 x23) PINB7 PINB6 PINB5 PINB4 PI NB3 PINB2 PINB1 PINB0 PINB Read/Wri te R/W R /W R/W R/W R/W R/W R/W R /W Initial Value N/A N/A N /A N/A N/A N/A N/A N/A B i t 7 6543210 0x08 (0 x28) – PORTC6 PORTC5 PORTC4 PORTC 3 PORTC2 PORTC1 PORTC0 PORTC Read/Write R R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 0 0000000 B i t 7654321 0 0x07 (0 x27) – DDC6 DD C5 DDC4 DDC3 DDC2 DDC1 DDC0 DDRC Read/Wri te 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 101 14.4.7 PINC – The P ort C Input Pins Address (1) 14.4.8 PORTD – The P ort D Dat a Register 14.4.9 DDRD – The Port D Dat a Direction Register 14.4.10 PIND – The Port D Input Pins Address (1) Note: 1. W riting to the pin register prov ides toggle functionality for IO (see ”To ggling the Pin” on page 85 ) B i t 7654321 0 0x06 (0 x26) – PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0 PINC Read/Wri te R R/W R/W R /W R/W R/W R/W R/W Initial Value 0 N/A N /A N/A N/A N/A N/A N/A B i t 76543210 0x0B (0 x2B) PORTD7 PORTD6 PORTD5 PORTD4 PORT D3 POR TD2 PORTD1 PORTD0 POR TD Read/Write R/W R/W R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 B i t 7654321 0 0x0A (0 x2A) DDD7 DDD6 DD D5 DDD4 DDD3 DDD2 DDD1 DDD0 DDRD Read/Wri te 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 B i t 7654321 0 0x09 (0 x29) PIND7 PIND6 PIND5 PIND4 PI ND3 PIND2 PIND1 PIND0 PIND Read/Wri te R/W R /W R/W R/W R/W R/W R/W R /W Initial Value N/A N/A N /A N/A N/A N/A N/A N/A A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 102 15. 8-bit Timer/Counter0 with PWM 15.1 Features • T w o Independen t Output Compare Unit s • Double Buffered Output Comp ar e Registers • Clear Timer on Comp are Match (Auto Reload) • Glitch Free, Phas e Correct Pulse Wid th Modu lator (PWM) • V ariable PWM Period • Frequen cy Generator • Three Indepe ndent Interrupt Sourc es (TOV0 , OCF0A, and OCF0B) 15.2 Overview Timer/Counter 0 is a general purpose 8-bit Ti mer/Counter modu le, with two independe nt Output Compar e Units, and with PWM support. It a llows accurate program e xecution timing ( event manage ment) and wave generation. A simplified block d iagram of the 8-bit Timer/Coun ter is shown in Figure 15-1 . For the actual placement of I/O pins, re fer to ”Pinout ATmega48A/PA/88A/PA/1 68A/PA/328/P” on page 12 . CPU accessible I/O Registers, including I/O b its and I/O pi ns, are shown in bold. The de vice-spe cific I/O Register and bit locations are listed in the ”Register Description” on pa ge 113 . The PRTIM0 bit in ”Minimizing Po wer Consum ption” on p age 51 must be written to zero to enable Timer/ Counter0 m odule. Figure 15 -1. 8-bit T ime r/Counter Block Diagram Clock S elect Timer/Counter DA T A B U S OCRnA OCRnB = = TCNTn Wav e fo r m Generation Wav e fo r m Generation OCnA OCnB = Fix ed TO P Va l u e Control Logic = 0 TO P B OT TO M Count Clear Direction TOV n (Int.Req.) OCnA (Int.Req.) OCnB (Int.Req.) TCCRnA TCCRnB Tn Edge Detector ( F rom Prescaler ) clk Tn A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 103 15.2.1 Definitions Many register and bit refe rences 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 th e Output Compar e Unit, in th is case Comp are Unit A or Compare Unit B. How ever, when using th e register or bit defines in a pr ogram, t he precis e form m ust be used, i.e., TCNT0 for accessing Timer/Co unter0 counter value an d so on. The definitions in Tab le 15-1 are also used extensivel y through out the document. T ab le 15-1. Definitions 15.2.2 Regi sters The Timer /Counter (TCNT0 ) and Output Compar e Register s (OCR0 A and OCR0B) are 8-bit re gisters. Interrupt request (abbreviated to Int.Req. in the figure) signals a re all visible in the Timer Interrupt Flag Re gister (TIFR0). All interrupts are in dividually masked with the Timer Inte r rupt Mask Register (TIMSK0). TIFR0 and TIMSK0 are not shown in the figure. The Tim er/Counter can be c locked inte rnally, via the presc a ler, or by an external clock source on the T0 pin. The Clock Select logic block controls w hich clock sour ce and edge the Timer/Co unter uses to increm ent (or decrement) its value . The Timer /Counter is inactive when no clock source is selected . The outpu t from the Clock Select logic is referred to as the timer clock (clk T0 ). The double buffer ed Output Compare Registers (OCR0A and OCR0B) ar e compared with th e Timer/Counter value at all times. The re sult of the compar e can be used by the Wavefor m Generator to genera te a PWM or variable fr equency outp ut on the Output Compare pins (OC0A and OC0B). See ”Using the Output Compare Unit” on page 130 for de tails. The compare match event will al so set the Compare Flag (OCF0A or OCF0B) which can be used to genera te an Output Compare inte rrupt request. 15.3 T imer/Cou nter Clock Sources The Timer/Counter can be clocked by an interna l or an ex tern al clock source. The clo ck source is selected by the Clock Select logic which is controlled by the Clock Sele ct (CS02:0) bits located in the Time r/Counter Con trol Register (T CCR0B). For details on clock sources a nd prescaler, see ”Timer/Counter0 and Timer/Co unter1 Prescalers ” on page 147 . 15.4 Counter Unit The main part of the 8-bit Timer/Counter is the programmab le bi-directio nal counter unit. Figur e 15-2 shows a block diagr am of the counter and its surro undings. BOTTOM The counter reac hes the BOTTOM when it becomes 0x00. MAX The counter reaches its MAXimum when it becomes 0xFF (decima l 255). TOP The coun ter reache s the TOP wh en it becomes equal to th e highest va lue in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or th e value s tored in th e OCR0A Register. Th e assignm ent is dependen t on the mode of o peration. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 104 Figure 15-2. Counter Unit Block Diag ram Signal descr iption (interna l signals): count Increment or decrement TCNT0 by 1. direction Sele ct between increment an d decrement. clear Clear TCNT0 (set all bits to zero). clk T n Timer/Counter clock, referred to as clk T0 in the following. top Signalize that TCNT0 has reached maximum value. bottom Signalize th at TCNT0 has re ached minimum value (zero). Depending o f the mode o f operation used, th e counte r is cleare d, incremented, o r decreme nted at each timer clock (clk T0 ). clk T0 can be generated fr om an extern al or intern al cl ock source, selected by the Clock Select bits (CS02:0). Whe n no clock source is selected (CS02:0 = 0) the timer is stopped. Howeve r, the TCNT0 value can be accesse d by the CP U, regardless of whethe r clk T0 is present or not. A CPU write overrid es (has priority ove r) all counter clear or count op erations. The counti ng sequence is dete rmined by the setti ng of the WGM0 1 and WGM00 bits located in th e Timer/Cou nter Control Re gister (TCCR0A) an d the WGM02 bit located in the Timer/C ounter Control Register B (TCCR0B). There ar e close connections between how t he counter be haves ( counts) and how wavefor ms are generate d on the Output Compare ou tputs OC0A and OC0B. For more details ab out adva nced counting sequence s and waveform generation, se e ”Modes of Operation” on page 107 . The Timer/Counter Overflow Flag (TOV 0) is set according to th e mode of opera tion selected by the WGM02:0 bits. TOV0 can be used for generating a CPU inte rrupt. 15.5 Output Comp are Unit The 8-b it compar ator con tinuously c ompares T CNT0 with the Output Compare Reg isters (OCR0A and OCR0B). Whenev er TCNT0 equals OCR0 A or OC R0B, the comparator sign als a match. A match will set the Output Co mpare Fla g (OCF0A or OCF0 B) at the next timer clo ck cycle. If the corr espondin g interrupt is enabled, the Ou tput Compare Flag genera tes an Output Comp are interrupt. Th e Output Compare Flag is automatically clear ed when the interrupt is executed. Altern atively, the flag can be clea red by softwar e by writing a logical one to its I/O bi t location. The Waveform Ge nerator uses th e match signa l to generate an output accord ing to oper ating mode set by th e WGM02 :0 bits and Compare Output mode (COM0x1:0) bits. The max and bottom signals are used by the Waveform Generator fo r handling the special ca ses of the extreme values in some mode s of operation ( ”Modes of Operation ” on page 107 ). Figure 15 -3 shows a block diagram of the Outp ut Compare unit. DA T A B U S TCNTn Control Logic count TOV n (Int.Req.) Clock S elect top Tn Edge Detector ( F rom Prescaler ) clk Tn bottom direction clear A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 111 15.8 T imer/Cou nter T i ming Diagrams The Timer/Counter is a synch ronou s desig n and the timer clock (clk T0 ) is therefore shown as a clock enable signal in the following figures. The figures incl ude infor mation on when interrup t flags are set. Fig ure 15-8 contains tim ing data fo r basic Timer/ Counter oper ation. The figur e shows the count sequence close to the MAX value in all modes other than phase correct PWM mode. Figure 15 -8. Timer/ Counter Ti ming Diagram , no Presc aling Figure 15 -9 shows the same timing data, bu t with the presca ler enabled. Figure 15-9. Timer/Counter Timing Diagram, with Pres caler (f clk_I/O /8 ) Figure 15 -10 shows the setting of OC F0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. Figure 15-10. Timer/Cou nter Timing Diagram , Setting of OCF0 x, with Prescaler (f clk_I/O /8) Figure 1 5-11 shows the set ting of OCF 0A and the clearing of TC NT0 in CTC m ode and fas t PWM mode where OCR0A is TOP. clk Tn (clk I/O /1) TOV n clk I/O TCNTn MAX - 1 MAX BO TTOM BO TT OM + 1 TOV n TCNTn MAX - 1 MAX BO TTOM BO TT OM + 1 clk I/O clk Tn (clk I/O /8) OCFnx OCRnx TCNTn OCRnx V alue OCRnx - 1 OCRnx OCRnx + 1 OCRnx + 2 clk I/O clk Tn (clk I/O /8) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 112 Figure 15-1 1. Time r/Counter Timi ng Diagram, Clear Timer on Compare Match mode, with Prescaler (f clk_I/O /8) OCFnx OCRnx TCNTn (CTC) TO P T OP - 1 TO P BO TT OM BOTT OM + 1 clk I/O clk Tn (clk I/O /8) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 113 15.9 Register Description 15.9.1 TCCR0A – Timer/Count er Control Register A • Bit s 7:6 – COM0A 1:0: Comp are Match Output A Mode These bits control the Output Compare pin (OC0A) behavi or. If one or both of the COM0A1:0 bits ar e set, the OC0A output over rides the normal port functionality o f the I/ O pin it is connected to. Ho wever, note that the Data Direction Register (DDR) bit cor responding to the OC0A pi n must be set in order to enable the output driver . When OC0A is connected to the pin, the functi on of the COM0A1:0 bits depe nds on the WGM02:0 bit setting. Table 15 -2 shows the COM0A1:0 bit functionality when th e WGM02:0 bits are set to a nor mal or CTC mode (non-P WM). Table 15 -3 shows the COM0A1:0 bit functionality when the WGM01:0 bits are set to fast PWM mo de. Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Comp are Match is ignored, but the set or clear is done at BOTTOM. See ”Fast PWM Mode” on page 108 for more details. Table 15 -4 shows the COM0A1:0 bit functionality when the WG M02:0 bits are set to phase correct PWM mode. B i t 7 6 5 4 3 210 0x24 (0 x44) COM0A 1 COM0A 0 COM0B 1 COM0B 0 –– 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 0 T ab le 15-2. Comp a re Output Mode, non-PWM Mod e COM0A1 COM0A0 Description 0 0 Normal port operation, OC0A disconne cted. 0 1 T oggle OC0A on Comp are Match 1 0 Clear OC0A on Compare Match 1 1 Set OC0A on Co mpare Match T ab le 15-3. Comp a re Output Mode, Fast PWM Mode (1) COM0A1 COM0A0 De scription 0 0 Normal port operation , OC0A disconnected. 0 1 WGM02 = 0: Normal Port Oper ation, OC0A Disconnected. WGM02 = 1: T oggl e OC0A on Compare Match. 1 0 Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode). 1 1 Set OC0A on Compare Match, clear OC0A at BOTT OM, (invert ing m ode). A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 114 Note: 1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Comp are Match is ignored, but the set or clear is done at TO P . See ”Phase Correct PWM Mode” on page 134 for more details. • Bit s 5:4 – COM0 B1:0: Comp are Matc h Output B Mo de These bits control the Output Compare pin (OC0B) behavi or. If one or both of the COM0B1:0 bits ar e set, the OC0B output over rides the normal port functionality o f the I/ O pin it is connected to. Ho wever, note that the Data Direction Register (DDR) bit cor responding to the OC0B pi n must be set in order to enable the output driver . When OC0B is connected to the pin, the functi on of the COM0B1:0 bits depe nds on the WGM02:0 bit setting. Table 15 -5 shows the COM0B1:0 bit functionality when th e WGM02:0 bits are set to a nor mal or CTC mode (non-P WM). Table 15 -6 shows the COM0B1:0 bit functionality when the WGM02:0 bits are set to fast PWM mo de. Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Comp are Match is ignored, but the set or clear is done at TO P . See ”Fast PWM Mode” o n page 108 for more details. Table 15 -7 shows the COM0B1:0 bit functionality when the WG M02:0 bits are set to phase correct PWM mode. T ab le 15-4. Comp a re Output Mode, Phase Correct PWM Mode (1) COM0A1 COM0A0 Descript ion 0 0 Normal port operation, OC0A disconnected. 0 1 WGM02 = 0: Norma l Port Operation , OC0A Disconnecte d. WGM02 = 1: T og gle OC0A on Comp are 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. T ab le 15-5. Comp a re Output Mode, non-PWM Mod e COM0B1 COM0B0 Description 0 0 Normal port operati on, OC0B disconnected. 0 1 T oggl e OC0B on C omp are Match 1 0 Clear OC0B on Comp are Match 1 1 Set OC0B on Comp are Match T ab le 15-6. Comp a re Output Mode, Fast PWM Mode (1) COM0B1 COM0B0 De scription 0 0 Normal port operation , OC0B disconnected. 0 1 Reserve d 1 0 Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode) 1 1 Set OC0B on Compare Match, clear OC0B at BOTT OM, (invert ing m ode). A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 115 Note: 1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Comp are Match is ignored, but the set or clear is done at TO P . See ”Phase Correct PWM Mode” on page 109 for more details. • Bit s 3, 2 – Reserved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit s 1:0 – WGM01:0: W aveform Ge neration Mode Combined with the WGM0 2 bit found in the TCCR0B R egister, these bits control the count ing sequence of the counter, the source for ma ximum (TOP ) counter value , an d what type of waveform gener ation to be used, see Table 15 -8 . Modes of operation sup ported by the Timer/Cou nter unit are: Normal mode (counter), Clear Time r on Com pare Matc h (CTC) m ode, an d two type s of Pulse Width Mod ulation (PW M) modes ( see ”Modes of Operation” on page 107 ). Notes: 1. MAX = 0xFF 2. BOTTOM = 0x00 T ab le 15-7. Comp a re Output Mode, Phase Correct PWM Mode (1) COM0B1 COM0B0 Descript ion 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. T able 15-8. W aveform Generat ion Mode Bit De scription Mode WGM02 WGM01 WGM00 Timer/Counter Mode of Operation TO P Up date of OCRx at TOV Fl a g Set on (1)(2) 0 0 0 0 Normal 0xFF Immediate MAX 1 0 0 1 PWM, Phase Correct 0xFF TO P BOTT OM 2 0 1 0 CTC OCRA Immediate MAX 3 0 1 1 Fast PWM 0xFF BOTTOM MAX 4 1 0 0 Reserved – – – 5 1 0 1 PWM, Phase Correct OCRA TO P BOTT OM 6 1 1 0 Reserved – – – 7 1 1 1 Fast PWM OCRA BOTTOM TOP A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 116 15.9.2 TCCR0B – Timer/Count er Control Register B • Bit 7 – FOC0A: Forc e Output Co mp are 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 mus t be se t to zero when TCCR0B is w ritten when operating in PWM mode. When writing a logical o ne to the FO C0A bit, a n immedi ate Comp are Match is forced on the Wave form Generation unit. The OC0A output is changed accordin g to its COM0A1:0 bits setting. Note that the FOC 0A bit is imp lemented as a stro be. Ther efore it is t he value present in the C OM0A1:0 bit s that determin es the effect of the forced compa re. 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 alwa ys read as zero. • Bit 6 – FOC0B: Forc e Output Co mp are 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 mus t be se t to zero when TCCR0B is w ritten when operating in PWM mode. When writing a logical o ne to the FO C0B bit, a n immedi ate Comp are Match is forced on the Wave form Generation unit. The OC0B output is changed accordin g to its COM0B1:0 bits setting. Note that the FOC 0B bit is imp lemented as a stro be. Ther efore it is t he value present in the C OM0B1:0 bit s that determin es the effect of the forced compa re. A FOC0B strobe will not generate any in terrupt, nor will it clear the timer in CTC mode using OCR0B as TOP. The FOC0B bit is alwa ys read as zero. • Bit s 5:4 – Res erved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit 3 – WGM02: W aveform Generation Mode See the descrip tion in the ”TCCR0A – Timer/Counte r Contro l Register A” on page 113 . • Bit s 2:0 – CS02:0: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counte r. Bit 7 6 5 4 3 2 1 0 0x25 (0 x45) FOC0A FOC0B – – WGM02 CS02 CS01 CS00 TCCR0B Read/Wri te W W R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 117 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 softwar e control of the counting. 15.9.3 TCNT0 – T imer/Count er Register The Timer/ Counte r Register gives direct a ccess, both for read a nd write o perations, to the Timer/Coun ter 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 coun ter is ru n ning, introduces a risk o f missing a Compare Match betwee n TCNT0 and the OCR0x Registers . 15.9.4 OCR0A – Output Comp are Register A The Out put Compar e Register A contain s an 8-bit va lue th at is continuously compared with the counter value (TCNT0). A match can be used to gener ate an Output Comp are interrupt, or to gene rate a wavefo rm output on the OC0A pin. 15.9.5 OCR0B – Output Comp are Register B The Out put Compar e Register B contain s an 8-bit va lue th at is continuously compared with the counter value (TCNT0). A match can be used to gener ate an Output Comp are interrupt, or to gene rate a wavefo rm output on the OC0B pin. T abl e 15-9. Cloc k Select Bit Description CS0 2 CS0 1 CS0 0 Description 000 No clock source (T imer/Counter stoppe d) 001 clk I/O /(No prescaling) 010 clk I/O /8 (From prescaler) 011 clk I/O /64 (From prescal er) 100 clk I/O /256 (From prescaler) 101 clk I/O /1024 (F rom prescaler) 110 External clock source on T0 pin. Clock on falling edg e. 111 External clock source on T0 pin. Clock on rising edge. B i t 7654321 0 0x26 (0 x46) 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 B i t 7654321 0 0x27 (0 x47) 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 0 B i t 7654321 0 0x28 (0 x48) 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 118 15.9.6 TIMSK 0 – Ti mer/Counter Interrupt Mask Register • Bit s 7:3 – Res erved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit 2 – OCIE0B: Ti mer/Counter Outp ut Comp are 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 corr esponding interr upt is executed if a Comp are Match in Timer/Counter occurs, i. e., when the OCF0 B bit is set in the Tim er/Counter Interrupt Flag Register – TIFR0. • Bit 1 – OCIE0A: Timer/Counter0 Outp ut Compare Match A Interrupt Enable When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the Ti mer/Counte r0 Comp are Match A interrupt is enabled. The corr esponding interrup t is executed if a Compar e Match in Timer/Counter0 occurs, i. e., when the OCF0 A bit is set in the Tim er/Counter 0 In terrupt Flag Register – TIFR0. • Bit 0 – T OIE0: T imer/Counter0 Overflow Interrup t Enable When the TOIE0 bit is written to one, an d the I-bit in the Status Register is set, the Time r/Counter0 Overflow interrup t is enabled. The correspond ing interr upt is executed if an overflow in Timer/Counter 0 occurs, i.e., when the TOV0 bit is set in t he Timer/Coun ter 0 Interrupt Flag Regis ter – TIFR0. 15.9.7 TIFR 0 – T imer/Counter 0 Interrupt Flag Regist er • Bit s 7:3 – Res erved These bits are reserved bits in the ATmega48A/PA/88A/PA/168A/PA/328/P and will always read as zero. • Bit 2 – OCF0B: T imer/Counter 0 Output Compare B Match Flag The OCF0B bit is set when a Compare M atch occurs between the Timer /Coun ter and the da ta in OCR0B – Output Compare Registe r0 B. OCF0B is cleared by hardware when executing the correspondin g interrupt handling vector . Alternatively, OCF0B is cleared b y wr iting a logi c one to th e flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Matc h Interr upt Enable), and OCF0 B are set, th e Timer/Cou nter Comp are Match Interrupt is executed. • Bit 1 – OCF0A: Timer/Counter 0 Output Comp are A Match F lag The OCF0A bit is set when a Compar e Match occur s be tween the Timer/Coun ter0 and the data in OCR0A – Output Compare Re gister0. OCF0A is cleared by hard ware when executin g the correspond ing interrupt handling vector . Alternatively, OCF0A is cleared b y wr iting a logi c one to th e flag. When the I-bit in SREG, OCIE0A (Timer/Counter 0 Compare Match Inter rupt Enable ), an d OCF0A are se t, the Timer/Cou nter0 Compare Match Interrupt is executed. Bit 7 6 5 4 3 2 1 0 (0x6E) – – – – – O CIE0B OCIE0A T OIE0 TIMSK0 Read/Wri te R R R R R R/W R/W R /W Initial Value 0 0 0 0 0 0 0 0 B i t 76543 2 1 0 0x15 (0 x35) ––––– O C F 0 B O C F 0 A T O V 0 T I F R 0 Read/Wri te R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 119 • Bit 0 – TOV0: T im er/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/ Counter0. TOV0 is clea red by hardwar e when executing the correspondin g interrupt hand ling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Over flow Interrupt Enable) , and TOV0 are set, the Timer/Counter 0 Overflow interrupt is executed. The setting of this flag is dependent of the WGM0 2:0 bit setting. Refer to Tabl e 15-8 , ”Waveform Ge neration Mode Bit De scription” on page 115 . A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 120 16. 16-bit Timer/Counter1 with PWM 16.1 Features • T rue 16-bit Design (i.e., Allows 16-bit PW M) • T w o independen t Output Compare Unit s • Double Buffered Output Comp ar e Registers • One Input Captu re Unit • Input Capture No ise Canceler • Clear Timer on Comp are Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • V ariable PWM Period • Frequen cy Generator • External Event Counter • Four indepe ndent interrup t Sources (T OV1, OCF1A, OCF1B, an d ICF1) 16.2 Overview The 16-bit Timer/Coun ter unit allo ws accurate prog ram executio n timing (eve nt managem ent), wave ge neration , and signal timing me asurement. Most register and bi t references in th is section are written in ge neral form . A lower ca se “n” rep laces the Timer/Counter number, and a lowe r case “x” replaces the Output Comp are unit channe l. However, when using the regis ter or bit defines in a progr am, the pr ec ise form must be used, i.e., TCNT1 for accessing Timer/Counter 1 counter value and so on. A simplified block d iagram of the 16-bit Timer /Counter is shown in Figure 16-1 . For the actual pl acement of I/O pins, re fer to ”Pinout ATmega48A/PA/88A/PA/1 68A/PA/328/P” on page 12 . CPU accessible I/O Registers, including I/O b its and I/O pi ns, are shown in bold. The de vice-spe cific I/O Register and bit locations are listed in the ”Register Description” on pa ge 140 . The PRTIM1 bit in ”PRR – Power Reductio n Register” on page 54 must be written to zero to enable Timer/ Counter1 m odule. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 127 The Input Capture unit is illustrate d by the block diagram shown in Figure 16-3 . The elem ents of th e block diagram that are no t directly a part of the Input Capture unit are gra y shaded. The small “n” in r egister and bit names in dicates th e Timer/C ounter num ber. Figure 16 -3. Input Capture U nit Block Diagram When a ch ange of the logic level ( an event) o ccurs on the Input Ca pture pin (ICP1) , alternatively on the Analog Comparator outpu t (ACO), and this change conf irms to the setting of the e dge detector, a capture will be triggere d. When a capture is triggered, th e 16-bi t value of the counter (T CNT1) is written to the Input Capt ure Register (ICR1). The Input Capture Flag (ICF1) is s et at the same system cloc k as the TCNT1 value is copied into ICR1 Register. If enabled (ICI E1 = 1) , the Input Capture Flag genera tes an Input Capture inte rrupt. The ICF1 Flag is automa tically clear ed when th e interrupt is exec uted. Altern atively the ICF1 Fla g can be cleared by softwar e by writing a logical one to its I/O bit location. Reading the 16-bit value in the Input Capture Register (ICR1) is d one by first reading the low byte (ICR1L) and then the high byte (ICR1H). When the low byte is r ead the high byte is copied into the high byte tempo rary register (TEMP). When the CPU reads the ICR1H I/O location it will ac cess the TEMP Register. The ICR1 Register can only be writte n when using a Waveform Generation mode that utilizes the ICR1 Register for defining the counter’s TOP valu e. In these cases the Waveform Generation mode (WGM13:0) bits must be set before the TOP value can be written to th e ICR1 R egister. When writing the IC R1 Register the high byte must be written to the ICR1 H I/O location before the low byte is written to ICR1L. For more info rmation on how to access the 16 -bit registers r efer to ”Accessing 16-bit Reg isters” on page 122 . 16.6.1 Input Capture T rigger Source The main trigg er source for the Input Capture unit is the In put Capture pin (ICP 1). Time r/Counter 1 can alternativ ely use the Anal og Comp arator out put as trigger source fo r the Input Capture unit. The Analog Comparator is selected as trigger source by setting the Analog Comparator In put Capture (ACIC) bit in the Analog Compa rator Co nt rol and Status Register (ACSR). Be awar e that changing trigg er source can trigger a captur e. The Inp ut Captur e Flag m ust therefore be clea red after the chan ge. Both th e Input Capt ure pin (ICP1) and the Analo g Comparator output (ACO) inputs are sampled using the same technique as for the T1 pin ( Figure 17 -1 on page 147 ). The edge dete ctor is also identical. However, wh en the noise canceler is enabled, additional logi c is inserted before the edge detector , which increases the delay by ICFn (Int.Req.) Analog Comparator WRITE ICRn (16-bit Register) ICRnH (8-bit) Noise Canceler ICPn Edge Detector TEMP (8-bit) D ATA B U S (8-bit) ICRnL (8-bit) TCNTn (16-bit Counter) TCNTnH (8-bit) TCNTnL (8-bit) A CIC* ICNC ICES A CO* A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 128 four system clock cyc les. No te that the input of the noise canceler an d edge de tector is alwa ys enabled unless the Timer/Counter is set in a Waveform Generation mode tha t uses ICR1 to define TOP. An Input Capture can be trig gered by software by controllin g the port of the ICP1 pin. 16.6.2 Noise Canceler The noise canceler improves noise immu nity by using a simp le digital filter ing scheme. The noise canceler inpu t is monitored over four samples, and all four must be equa l for changin g the output tha t in turn is used by the edge detector . The noi se cancel er is enabled by setting the Input Capture No ise Canceler (ICNC1) bit in Timer/Counter Control Register B (TCCR1B) . When enable d the noise ca nceler introd uces additional four system clo ck cycles of delay from a change applie d to the input, to th e update of t he ICR1 Register. The noise ca nceler uses the system clock and is therefore not affecte d by the prescaler. 16.6.3 Using the Input Capture Unit The main challe nge when using the Input Capture un it is to assign enough pro cessor capacity fo r handling the incoming even ts. The time between two e vents is cr itical . If the processor has not read the captured valu e in the ICR1 Register before the next ev ent occurs, the ICR1 will be overwritten wi th a new value. In this case the result of the capture will be inc orrect. When using the Input Captur e interrupt, the ICR1 Register should be read as early in the interrupt handler routine as possible. Even though the Input Capture interr upt has re latively high prio rity, the maximum interrup t response time is dependent on the maximum n umber of cl ock cycles it takes to handle any of the other inter rupt requests. Using the Input Capture unit in any mo de of operation wh en th e TOP value (resolution) is actively changed during oper ation, is not recommended. Measurement of an external signal’s duty cycle requir es that the trigger edge is chang ed after each capture . Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. Afte r a change of the edge, the Input Capture Fla g (ICF1) must be cleared by so ftware (writi ng a logical one to the I/O bit locatio n). For measuring freq uency only, the clearing of the ICF1 Flag is not requ ired (if an interrup t handler is used). 16.7 Output Comp are Unit s The 16-bit comp arator continuously comp ares TCNT1 with the Output Com pare Reg ister (OCR1x ). If TCNT equals OCR1x the comp arator signals a matc h. A match will s et the Output Compare Flag (OCF1 x) at the next timer clock cycle . If enabled (OCIE1x = 1), th e Output Compare Fla g generates an Output Compare inter rupt. The OCF1x Flag is automa tically cleared when the interr upt is exe cuted. Alternatively the OCF1x Flag can be cleared by softwar e by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output accord ing to oper ating mode se t by the Waveform Generation mode (WGM13 :0) bits and Compare Ou tput mode (COM1x1:0) bits. The TOP and BOTTO M signals ar e used by the Waveform Generator for handling the special case s of the extreme values in some modes of operation ( See Section “16.9” on page 131. ) A special fe ature of Output C ompare un it A allows it to define the Time r/Counter TOP value (i.e., cou nter resolution). In add ition to the counte r resolution, the TOP valu e defines the period time for waveforms gener ated by the Waveform Generator. Figure 16 -4 shows a block diagram of the Outp ut Compare unit. The sma ll “n” in the register and bit names indicates the device nu mber (n = 1 for Timer/Cou nter 1), and the “x” indi cates Output Compare unit (A/B). The elements of the bloc k diagram that are not directly a pa rt of the Output Compar e unit are gray shad ed. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 129 Figure 16-4. Output Compare Unit, Bl ock Diagram The OCR1x Register is dou ble buffered wh en using any of the twel ve Pulse Widt h Modulation (PWM) modes. For the Normal a nd Clear Timer on Compare (CTC) modes of op eration, the double buffering is disable d. The double bu ffering synchr onizes the update of the OCR1 x Comp are Register to either TOP or BOTTOM of th e counting sequen ce. The synchr onizatio n prevents the o c currence of odd -length, non -symme trical PWM pulse s, thereby ma king the outp ut glitch-free. The OCR1x Register access may seem complex, but this is not case. When the double bu ffering is enab led, the CPU has acces s to the OCR1x Buffer Register, and if double buffering is disabled the CPU will access the OCR1x directly. The content of the OCR1 x (Buffer or Comp a re) Register is only changed by a write ope ration (the Timer/Counter does not up date this register auto matically as the TCNT1 and ICR1 Register). Therefore OCR1x is not read via the high byte temporar y register (T EMP). However, it is a good practice to read the low byte first as when accessing other 16-bit r egisters. Writing the OCR1x Registers mu st be done via the T EMP Register si nce the compare of all 16 bits is done contin uously. The high byte (OCR1x H) has to be written f irst. When the high byte I/O location is wr itten by the CPU, the TEMP Register will be updated by the value w ritten. Then when the low byte (OCR1xL) is wr itten to the lower eight bits, the high byte will be copied into the upper 8- bits of either the OCR1x buffer or OCR1x Com pare Register in the same system clock cycle. For more inform ation of how to access the 16-bit register s refer to ”Accessing 16-bit Registers” on page 12 2 . 16.7.1 Force Output Comp are In non-PWM Waveform Generation modes, the match output of the comp arator can be forced by writing a one to the Force Output Compa re (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 (t he COM11:0 bits settings define whet her the OC1x pin is set, cleared or toggled ). 16.7.2 Comp are Match Blocking by TCNT1 Wr ite All CPU writes to the TCNT1 R egister will block any comp are match that occurs in the next timer clock cycle, even wh en the timer is stopped. T his featur e allows O CR1x to be initialized to t he same value as TCNT1 without triggerin g an interrupt wh en the Timer/ Counter cloc k is enabled. OCFnx (Int.Req.) = (16-bit Comparator ) OCRnx Buffer (16-bit Register) OCRnxH Buf. (8-bit) OCnx TEMP (8-bit) D ATA B U S (8-bit) OCRnxL Buf. (8-bit) TCNTn (16-bit Counter) TCNTnH (8-bit) TCNTnL (8-bit) COMnx1:0 WGMn3:0 OCRnx (16-bit Register) OCRnxH (8-bit) OCRnxL (8-bit) W av ef orm Generator TO P BO TT OM A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 130 16.7.3 Using the Ou tput Comp are Unit Since writing TCNT1 in any mode of operation will block all compare matche s for one timer clock cycle, there are risks involved when changing TCNT1 when usin g any of the Output Compare chan nels, independe nt of whether the Time r/Counter is running or not. I f the valu e written to TCNT1 eq uals the OCR1x value , the compare match will be miss ed, resulting in incorrect waveform generation. Do no t write the TCNT1 equal to TOP in PWM modes with variable TOP values. The com pare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly, do not write the TCNT1 value equal to BOTTO M when the counter is downcoun ting. The se tup of th e OC1x should be p erformed 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) str obe bits in Normal mode. The OC1x Re gister keeps its value even wh en changing betwee n Waveform Generation mode s. Be awar e that th e COM1x1 :0 bits ar e not doub le buffer ed toge ther with t he compar e value. C hanging the COM1x1:0 bits will take effect immediately. 16.8 Comp a re Mat ch Output Unit The Compare Ou tput mode (COM1 x1:0) bits have two func tions. Th e Waveform Generator uses the COM1x1:0 bits for defining th e Output Compare ( OC1x) state at the next compare match. Se condly the COM1x1:0 bits control th e OC1x pin outp ut source. Figure 16-5 shows a simplifie d schematic of the logic affected by the COM1x1:0 bit setting. The I/O Registers , I/O bits, and I/O pi ns in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (D DR and PORT) t hat are affected by the CO M1x1:0 bits are shown. When referring to the OC1x state, the refere nce is fo r the intern al OC1x R egister, not the OC1x pin. If a system reset occur, the OC1x R egister is rese t to “0”. Figure 16-5. Compare Matc h Output Unit, Schemati c The general I/O por t function is overridden by the Outp ut Compare (OC1x) from the Wave form Generato r if either of the COM1x1:0 bits are set. How ever, the OC1x pin directio n (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction Register bit for the OC 1x pin (DDR _OC1x) POR T DDR DQ DQ OCnx Pin OCnx DQ Wa ve fo r m Generator COMnx1 COMnx0 0 1 D ATA B U S FOCnx clk I/O A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 131 must be set as output before the OC1x value is visibl e on the pin. The port over ride function is generally independen t of the Waveform Generation mode , but there are some exceptions. Refer to Ta ble 16-1 on page 140 , Table 16-2 on page 14 0 and Table 16-3 on page 141 fo r deta ils. The design of th e Output Compare pi n logic allows initializ ation of the OC1 x state before th e output is enable d. Note that some COM1x1:0 bit settings are reser ved for certain mode s of operation. See ”Register Description” on page 140 . The COM1x1:0 bits have no effect on the Inpu t Capture unit. 16.8.1 Comp are Output Mode and W aveform Generation The Waveform Gen erator uses the COM1x1:0 bits d ifferently in normal, CTC, and PWM mo des. For all modes, setting the COM1x1:0 = 0 tells the Wavefo rm Generato r that no action on the OC1x Register is to be performe d on the n ext comp are matc h. For co mpare ou tput actio ns in the non-PWM m odes re fer to Table 16-1 on page 140 . F or fast PW M mode refer to Table 16-2 on page 140 , and fo r phase correct a nd phas e and fr equency correct PWM refer t o Table 16- 3 on page 141 . A change of the COM1x1:0 bits state w ill have effect at the fi rst compare match after the bits are written. For non-PWM modes, the action can be forced to have immediat e effect by usi ng the FOC1x strobe bits. 16.9 Modes of Operation The mode of opera tion, i.e., the behav io r of the Timer/Counte r and the Ou tp ut Compa re pins, is defined by the combination of the Waveform Generation mode (WGM13:0) and Compar e Output mode (COM1x1: 0) bits. The Compare Ou tput mode b its do n ot affect th e countin g sequence, wh ile the Waveform Generation mo de bits do. The COM1x1:0 bits control whether the PWM output gene rated should be inverted or no t (inverte d or non- inverted PWM) . For non- PWM modes the COM1x1:0 bits control whether the output shou ld be set, cle ared or toggle at a compare match (Se e “Compare Match Output Unit” on page 13 0. ) For detailed timing informatio n refer to ”Timer/Counter T iming Diagra ms” on page 138 . 16.9.1 Normal Mode The simplest mode of opera tion is the Norm al mode (WGM13:0 = 0). In this mode the counting direction is always up (incrementing) , and no count er cle ar is performed. Th e counter si mply overruns when it passes its maximum 16-bit value (MAX = 0xFFFF ) and then restarts fr om the BOTTOM (0x0000). In normal oper ation the Timer/ Counter O verflow Fla g (TOV1) will be set in the same timer cl ock cycle as the TCNT 1 becomes zero. The TOV1 Flag in this case beha ves like a 17th bit, except that it is only set, not cl eared. However , combined with the timer overflow interrupt that automatically clears the TOV1 Flag, the timer reso lution can be increased by software. There ar e no special cases to conside r in the Normal mode, a ne w counter value can be written anytime. The Input Capture unit is easy to use in Normal mode . However, obse rve that the maximum interval between the external events must not exceed the resolutio n of the counter. If the interval between ev ents are too long , the timer overflow interrupt o r the prescaler must be used to extend the re solution for the ca pture unit. The Output Compare units can be used to generate inter rupts at some given time. Using th e Output Compa re to generate wavefo rms in Normal mode is not reco mmended, since this will occupy too much of the CPU time. 16.9.2 Clear T imer on Comp are Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register are us ed to manipulate th e counter reso lution. In CT C mode the count er is cleared to zero when the counter value ( TCNT1) matches either the OCR1A (WGM13:0 = 4) or t he ICR1 (WGM13:0 = 12). The OCR1A or ICR1 define the top value for the counter, hence also its resolution. This mo de allows greater co ntrol of the compare match ou tput frequen cy. It also simplifies the op eration of coun ting external events. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 132 The timing diag ram for the CTC mode is shown in Fig ure 16-6 . The counter value (TCNT1) increase s until a compare match occur s with either OCR1A or ICR1, and then counter (TCNT1) is cleared. Figure 16-6. CTC Mode , Timing Dia gram An interr upt can be g enerated at each time the cou nter valu e reaches the TOP value by either using the OCF1A or ICF1 Flag according to th e register used to define the TOP value. If the interrupt is enabled, the interru pt handler routin e can be used for updating the TOP value. However, ch anging 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 ha ve the dou ble bufferin g featur e. If the new value wr itten to OCR1A or IC R1 is lower than the current value of TCNT1, the counter will miss the comp are match. The counter will th en have to count to its maximum value (0xF FFF) and wrap arou nd starting at 0x 0 000 before the compare ma tch can occur. In many cases this feature is not desirable. An alternative will then be to us e 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 Ou tput mode bits to t oggle mode (COM1A1:0 = 1). The OC1A value will not be vis ible on th e port p in unless t he data dir ection for the pin is set to outp ut (DDR_O C1A = 1). T he waveform generated will have a maximum frequency of f OC 1 A = f clk_I/O /2 when OCR1A is set to z ero (0x0000). The waveform freq uency is defined by the following equa tion: The N variable re presents the pr escaler factor (1, 8, 64, 256 , or 1024). As for the N ormal mo de of opera tion, the T OV1 Flag is se t in the same timer clock cyc le that the counter counts from MAX t o 0x000 0. 16.9.3 Fast PWM Mode The fast Pulse Width Modula tion 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-slo pe operation. The coun ter counts from BOTTOM to TOP th en r estarts from BOTTOM. In non-inver ting Compare Output mode, the Output Compare (OC1 x) is cleared on the co mpare match between TCNT1 an d OCR1x, and set at BOTTOM. In inverting Compare Outp ut mode out put is set on compare match and cleared at BOTTOM. Due to the sing le-slope oper ation, the o perating fr equen cy of the fast PWM mode ca n be twice as high as the phase correct an d phase an d frequency cor rect PWM modes that use d ual-slope o peration. This h igh freq uency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequen cy allows physically small sized external comp onents (c oils, capacitors) , hence re duces total system cost. TCNTn OCnA (T oggle) OCnA Interrupt Flag S et or ICFn Interrupt Flag S et (Interrupt on T OP) 1 4 P eriod 2 3 (COMnA1:0 = 1) f OCnA f clk_I/O 2 N 1 OCRnA +   ------------ ----------- ----------- ------------ ---- - = A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 133 The PWM resolution for fast PWM can be fixed to 8-, 9-, o r 10-bit, or defined by either ICR1 or O CR1A. The minimum resolution allo wed is 2-bit (ICR1 or OCR1A set to 0x000 3), and the maxim um resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be calcu lated by using the fo llowing equation: In fast PWM mode the counter is incremented until the counter value matches either on e of the fixed values 0x00FF, 0x 01FF, or 0x03F F (WGM13:0 = 5, 6, o r 7), the value in ICR1 ( WGM13:0 = 14), or the value in OCR1 A (WGM13:0 = 15). The counter is then cleared at th e following timer clock cycle. The timing diagram for the fast PWM mode is sh own in Figure 16-7 . The figure show s fast PWM mode wh en OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histogram for illu strating the single- slope operation. The diagram includ es non-inverted and inverted PWM ou tputs. Th e small horizonta l line marks on the TCNT 1 slopes represent compare matches between OCR1x and TCNT1. Th e OC1x Interrupt Flag will be set w hen a compare match occur s. Figure 16-7. Fast PWM Mode, Timing Diagram The Timer/Counter Overflow Flag (TOV 1) is set each ti me the co unter reaches TOP. In additio n 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 inter rupts are enab led, th e interrupt handler ro utine can be used for updating the TOP and comp are values. When changing the TOP value the program must en sure that the new TOP value is high er or equal to the value of all of the Compa re Registers. If the TOP valu e is lo wer tha n any of the Compar e Registers, a comp are match will never occur between the TC NT1 and the OCR1x. Note that when us ing fixed TOP v alues the unused bits are masked to ze ro when any of the OCR1x Registe rs are written. The proc edure for updating ICR1 differs from updating OC R1A when u sed for defin ing the TOP va lue. The IC R1 Register is not double buffer ed. This mean s that if ICR1 is changed to a lo w value wh en the cou nter is ru nning with none or a low prescaler value, th ere is a risk that t he new ICR1 value writte n is lower than the curren t value of TCNT1. The result will th en 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 star ting at 0x0000 be fore the compare match can occur . The OCR1A Register however, is dou ble buffered. This fea ture allo ws the OCR1A I/O location to be written anytime. When the OCR1A I/O location is written the valu e 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 time r clock cy cle the TCNT 1 matche s TOP. The up date is done at the same timer clo ck cycle as the TCNT1 is cleared and the TOV1 Flag is set. Using the ICR1 Register for defining TOP works well wh en using fixed T OP values. By using ICR1, the OCR1A Register is free to be used for ge nerating a PWM ou tput on OC1A. However , if the base PWM frequency is R FPWM TOP 1 +  log 2  log ---------- ----------- ------------ - - = TCNTn OCRnx/T OP Update and T O Vn Interrupt Flag Set and OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on T OP) 1 7 P eriod 2 3 4 5 6 8 OCnx OCnx (COMnx1:0 = 2) (COMnx1:0 = 3) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 134 actively chang ed (by ch anging the T OP value), u sing the OCR1A as TOP is clearly a better choice due to its double buffer feature. In fast PWM mode, t he compar e units allow generati on of PWM waveforms on the OC1x pins. Setting the COM1x1:0 bits to three will produce a inverted PW M and an non-inverte d PWM output can be generated by setting the COM1x1 :0 to t wo (see Table 16-2 on page 14 0 ). The actual OC1x value will only be v isible on the port pin if the data dire ction for the po rt pin is set as output (DDR_ OC1 x). The PWM waveform is generate d by setting (or clearin g) the OC1x Register at the comp are match betwee n OCR1x and TCNT1, and clearing (or setting) the OC1x Register at the time r clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequen cy for the output ca n be calculated by the followin g equation: The N variable repr esents the pr escale r divider (1, 8, 64, 256, or 1024) . The extreme values for the OCR1x Registe r repres ents special cases when ge nerating a PWM waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the ou tput will be a narrow spike for each TOP+1 timer clock cyc le. Setting the OCR1x equal to TOP will result in a constant high or low output (depending on the polarity of th e output set by the COM1 x1:0 bits.) A frequency (with 50% duty cycle) waveform ou tput in fast PWM mode can be achieved by setting OC1A to toggle its logical level on each compare match (COM1A1:0 = 1). This applies on ly if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform ge nerated will have a ma ximum frequency of f OC 1 A = f clk_I/O /2 when OCR1A is set to zero (0x0000). This feature is similar to the OC1A toggle in CTC mode, except the dou ble buffer feature of the O utput Com pare un it is enabled in the fast PWM mode. 16.9.4 Phase Corre ct PWM M ode The phase corr ect Pulse Width Modulation or phase correct PWM mode (WGM13 :0 = 1, 2, 3, 10, or 11) provides a high resolution phase corr ect PWM wavefo rm generation option . The phase co rrect PWM mode is, like the phase and freque ncy correct PWM mode, bas ed on a dua l-slope operation. The counter counts repeatedly from BOTTOM (0x0 000) to TOP and then fr om TOP to BOTT OM. In non -inverting Compare Outp ut mode, the Output Compare (OC1x) is cleared on the comp are match between TCNT1 and OCR1x while upcounting, and se t on the compare match while downc ounting. In inverting Output Co mpare mode, the operatio n is inve rted. Th e dual-slo pe oper ation has lower maximum ope ration freque ncy than single slope operation. However, du e to the symmetric feature of th e dua l-slope PWM mod es, these modes a re preferre d for motor control applications. The PWM resolution fo r the phase correct PWM m ode can be fixed to 8- , 9-, or 10-bit, or d efined by either ICR1 or OCR1A. The minimum resolutio n allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the maximu m resolution is 16-bit (IC R1 or OCR1A set to MAX). The PWM reso lution in bits can be calcul ated by using the following eq uation: In phase correct PWM mode the counter i s incremented un til the counter value ma tches either one o f the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM 13:0 = 1, 2, or 3), th e value in ICR1 (WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counte r has then re ached th e TOP an d changes the cou nt direction. The TCNT1 value will be equal to TOP for one timer c lock cycle. The timing diagram for the phase correct PW M mode is shown on Figur e 16-8 on page 13 5 . The figur e shows phas e correc t PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a histog ram for illustrating the dual-slope operation. The dia gram includes non-in verted and inve rted PWM outputs. The small hor izontal line marks on f OCnxPWM f clk_I/O N 1 TOP +   ---------- ------------ ----------- - - = R PCPWM TOP 1 +  log 2  log ----------- ----------- ----------- - - = A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 135 the TCNT1 slopes represent compar e matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set when a compare ma tch occurs. Figure 16-8. Phase Correct PWM Mode, Timing Diagram The Timer/Counte r Overflow Flag (TOV1) is set each tim e the counte r reaches BOTTOM. When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is se t accordingly at the s ame timer clock cycle as the OCR1x Registers are updat ed with th e double bu ffer valu e (at TOP). The Interr upt Flag s can be used to gener ate an interrup t each time th e co unter reaches the TOP or BOTTOM value. When changing the TOP value the program must en sure that the new TOP value is high er or equal to the value of all of the Compa re Registers. If the TOP valu e is lo wer tha n any of the Compar e Registers, a comp are match will never occur between the TC NT1 and the OCR1x. Note that when us ing fixed TOP values, the unused bits are masked to ze ro when any of the OCR1x Registe rs are written. As the third per iod shown in Figure 1 6-8 on page 1 35 illustrates, changing the TOP ac tively while the Ti mer/Counter is running in the phase co rrect mode can resu lt in an un symmetric al output . The reas on for th is can be fo und in th e time of update of the OC R1x Register. Sinc e the OCR1x update occurs at TOP, the PW M period sta rts 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 va lue. When these two values differ the tw o slopes of the period will differ in length. The difference in length give s the unsymmetrical result on the output. It is recommended to use th e phase and freq uency corr ect mode inste ad of the phase correct mod e when changing the TOP va lue while the Timer/Co unter is run ning. Whe n using a static TO P value ther e are pr actically no differences between th e two mode s of operation. In phase co rrect PWM mod e, the comp are units allow g e neration of PWM waveforms on th e OC1x pins. Setting the COM1x1:0 bits to two will pro duce a n on-invert ed PWM and an inverted PWM outpu t can be generated by setting the COM1x1:0 to thre e (See Table 16 -3 on p age 141 ). The actual OC1x valu e will only be visible on the port pin if the data dire ction for the po rt pin is set as output (DDR_ OC1 x). The PWM waveform is generate d by setting (or clearin g) the OC1x Register at the comp are match betwee n OCR1x and TCNT1 when the coun ter increments, an d clearing (or setting ) the OC1x Regi ster at compare ma tch between OCR1x and TCNT1 when the counter decrements. The PWM frequency for the out put whe n using phase correct PWM can be calculated by the following e quation: OCRnx/T OP Update and OCnA Interrupt Flag Set or ICFn Interrupt Flag Set (Interrupt on T OP) 1 2 3 4 T O Vn Interrupt Flag Set (Interrupt on Bottom) TCNTn P eriod OCnx OCnx (COMnx1:0 = 2) (COMnx1:0 = 3) f OCnxPCPWM f clk_I/O 2 NT O P  ----------- ----------- ----- - = A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 136 The N variable repr esents the pr escale r divider (1, 8, 64, 256, or 1024) . The extre me values for th e OCR1x Regist er represen t special cases when gen erating a PWM waveform output in the phase correct PWM mo de. If the OCR1x is set eq ual to BOTTOM the output w ill 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 OC 1A output will toggle with a 50% duty cycle. 16.9.5 Phase and F requenc y Correct PWM Mode The phase an d frequen cy correct Pulse Width Modulation, o r phase and frequen cy correct PWM mode (WGM13:0 = 8 or 9) provides a high reso lution phase and fr equency corre ct PWM waveform generation optio n. The phase and fr equency correct PWM mo de is, like th e phase correct PWM mode, ba sed on a dual-slope operation. Th e counter counts re peatedly from BOTTOM (0x0000) to TOP and then from TOP to BOTTOM. In non-invert ing Compare Output m ode, the Output Comp are (OC1 x) is cleared on the comp are match betwee n TCNT1 an d OCR1x w hile upcounti ng, and se t on the com pare match while downcounti ng. In inverting Compare Output mode, the opera tion is inverted. The dual-slo pe o peration give s a lower maximum op eration frequency compared to the single-slo pe operation. However, due to the symmetric featur e of the du al-slope PW M modes , these mo des are prefer red for moto r control applica tions. The main difference be tween the phase correct, and the phase and fre quency correct PWM mode is the time the OCR1x Register is up dated by the OCR1x Buffer Register, (see Figure 16 -8 on page 13 5 and Figure 16-9 on page 137 ). The PWM re solution for the ph ase and fr equency correct PWM mode ca n be defined by eith er ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1 A set to 0x0003), and the maximum reso lution is 16-bit (ICR1 or OCR1A set to MAX). The PW M resolution in bits can be calcul ated using the following equation : In phase and freq uency correct PWM mode the counter is incremented u ntil 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 d irection. T he TCNT1 va lue will be equal to TOP for on e timer c lock cycle. T he timing diagram fo r the phase correct and frequency corr ect PWM mode is shown on Figure 16- 9 on page 137 . The figure shows phase and frequency corr ect PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing diagram shown as a hi stogram for illustrating the dual-slope oper ation. The diagram includ es non-inverted and inverted PWM outputs . T he small hor izontal line marks on the TCNT1 slopes represent compare matches between OC R1x and TCNT1. The OC1x Interrupt Flag w ill be set when a compare match oc curs. R PFCPWM TOP 1 +  log 2  log ---------- ----------- ----------- -- - = A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 143 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 softwar e control of the counting. 16.1 1.3 TCCR1C – Timer/Counter1 Control Register C • Bit 7 – FOC 1 A: Force Output Comp are for Channel A • Bit 6 – FOC 1 B: Force Output Comp are for Channel B The FOC1A/FOC1B bits are on ly active when the WGM1 3:0 bits specifies a non-PWM mod e. When writing a logical one to the FOC1 A/FOC1B bit, an immediate comp are match is fo rced on the Waveform Generation unit. The OC1A/OC1B ou tput is changed according to its COM1 x1:0 bits setting. Note that t he FOC1A/FOC1B bits are implemented as strobes. T herefore it is the valu e presen t in the COM 1x1:0 bit s that de termine the effect of the forced compare. A FOC1A/FOC1B strobe will not generate any interr upt nor will it clear the timer in Clear Timer on Compare match (CTC) mode using OCR 1A as TOP. T he FOC1 A/FOC1B bit s are always read as ze ro. 16.1 1.4 TCNT1H and TCNT1L – T imer/Counter1 The two T imer/Co unter I/O locatio ns (TCNT1H and TCNT1L, combined TCNT1) give dir ect access, both for read and for write op erations, to the Timer/Counter unit 16-bit counte r. To ensure that both the hig h and low bytes are read and written simulta neously when the CP U accesses these re gister s, the access is per formed using an 8-bit temp orary High Byte Register (TEMP). This tempor ary regist er is shared by all the other 16-b it registers. See ”Accessing 16-bit Registe rs” on page 122 . Modifying the counter (TCNT1) while the coun ter is ru nning introduces a risk of missing a comp are match between TCNT1 and one of th e OCR1x Registers. Writing to the TCNT1 Register blocks (removes) the compar e match on the following timer clock for all compar e units. T abl e 16-5. Cloc k Select Bit Description CS12 CS11 CS10 Description 0 0 0 No clock source (Timer/Counter stopped). 0 0 1 clk I/O /1 (No prescaling ) 0 1 0 clk I/O /8 (From prescaler) 0 1 1 clk I/O /64 (From prescaler) 1 0 0 clk I/O /256 (From prescaler) 1 0 1 clk I/O /1024 (From prescaler) 1 1 0 External clock so urce on T1 pin. Clock on falling edge. 1 1 1 External clock so urce on T1 pin. Clock on rising edge. B i t 765 4 3 210 (0x82) FOC1A FOC1 B – – – – – – TCCR1C Read/Write R/W R/W R R R R R R Initial Value 0 0 0 0 0 0 0 0 B i t 7654321 0 (0x85) TCNT1[15:8] TCNT1H (0x84) TC NT1[ 7:0] T CNT1 L 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 144 16.1 1.5 OCR1AH a nd OCR1 AL – Output Comp are Regi ster 1 A 16.1 1.6 OCR1BH a nd OCR1 BL – Output Comp are Regi ster 1 B The Output Co mpare Registers contain a 1 6-bit value that is continuou sly compared with the counte r value (TCNT1). A match can be used to gener ate an Output Comp are interrupt, or to gene rate a wavefo rm output on the OC1x pin. The Out put Comp are Regis ters are 16 -bit in size . To ensure that both the high and low bytes ar e written simultaneously when the CPU writes to these registers, the access is pe rform ed using an 8-bit tempo rary High Byte Register (TEMP). This temp orary regi ster is shared by all the o ther 16-bit register s. See ”Accessing 16-bit Register s” on page 122 . 16.1 1.7 ICR1H and ICR1L – Input Capture Register 1 The Input Capture is updated with the counter (TCNT1) va lu e each time an event occur s on the ICP1 pin (or optionally o n the Analog C omparat or ou tput for Timer/Counter1). The Input Capture can be used for d efining the counter TOP value. The Input Cap ture Regi ster is 16-bit in size. To ensure that both th e high and low bytes are read simultan eously when the CPU accesses these registers, the acc ess is per formed usin g an 8-bit tempora ry High Byte Register (TEMP). This temp orary register is shar ed by all the other 16-bit registers. See ”Accessing 16-bit Registers” on page 1 22 . 16.1 1.8 TIMSK1 – T imer/Cou nte r1 Interrupt Mask Register • Bit 7, 6 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 5 – ICIE1: T imer/Counter1 , Inpu t Capture Interrupt Enable When this bit is writte n to one, and th e I-flag in the Status Register is set (int errupts g lobally enabled ), the Timer/Counter 1 Input Capture interrup t is enab led. The co rrespon ding Interrupt Vector (see “Interrupts” on page 66) is executed when the ICF1 Flag, locate d in TIFR1, is set. B i t 76543210 (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 I n i t i a l V a l u e 00000000 B i t 76543210 (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 I n i t i a l V a l u e 00000000 B i t 7654321 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 B i t 76543 2 1 0 (0x6F) – – ICIE1 – – OCIE1B OCIE1A T OIE1 TIMSK1 Read/Write R R R/W R R R/W R/W R/W I n i t i a l V a l u e 00000 0 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 145 • Bit 4, 3 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 2 – OCIE1B: Timer/Counter1, Ou tp ut Comp are B Match Interrupt Enable When this bit is writte n to one, and th e I-flag in the Status Register is set (int errupts g lobally enabled ), the Timer/Counter 1 Output Compare B Match interrupt is en abled. The corresponding Interrupt Vector ( see “Interrup ts” on page 66) is executed when th e OCF1B Flag, located in TIFR1, is set. • Bit 1 – OCIE1A: Timer/Counter1, Ou tp ut Comp are A Match Interrupt Enable When this bit is writte n to one, and th e I-flag in the Status Register is set (int errupts g lobally enabled ), the Timer/Counter 1 Output Compare A Match interrupt is en abled. The corresponding Interrupt Vector ( see “Interrup ts” on page 66) is executed when th e OCF1A Flag, located in TIFR1, is set. • Bit 0 – T OIE1: T imer/Counter1, Overflow Interru pt Enable When this bit is writte n to one, and th e I-flag in the Status Register is set (int errupts g lobally enabled ), the Timer/ Counter1 Ove rflow interr upt is enable d. The corres ponding In terrupt Vec tor (See ”Interrupts” on page 66 ) is executed when the TOV1 Flag , located in TIFR1, is set. 16.1 1.9 TIFR1 – Timer/Coun te r1 Interrupt Flag Register • Bit 7, 6 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 5 – ICF1 : T imer/Coun ter1, Input Capture Fl ag This flag is set when a cap ture 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 w hen the Input Capture Interrup t Vector is ex ecuted. Alter nativel y, ICF1 can be cleared by writi ng a logic one to its bit location. • Bit 4, 3 – Reserved These bits are unuse d bits in the ATmega48A/PA/88 A/PA/168A/PA/328/P, and will always re ad as zero. • Bit 2 – OCF1B: Timer/Counter1, Output Comp are B Match Fla g This flag is s et in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Re gister B (OCR1B). Note that a Forced Output Compare (F OC1B) strobe will not set the OCF1B Flag. OCF1B is automatically cle ared when the Ou tput Compare Match B Interrupt Vec tor is executed. Alternatively, OCF1B can be cleared by writin g a logic one to its bit location . • Bit 1 – OCF1A: Timer/Counter1, Output Comp are A Match Fla g This flag is s et in the timer clock cycle after the counter (TCNT1) value matches the Output Compare Re gister A (OCR1A). Note that a Forced Output Compare (F OC1A) strobe will not set the OCF1A Flag. B i t 765432 10 0x16 (0 x36) – – ICF1 – – OCF1B OCF1A T OV1 TIFR1 Read/Write R R R/W R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 146 OCF1A is automatically cle ared when the Ou tput Compare Match A Interrupt Vec tor is executed. Alternatively, OCF1A can be cleared by writin g a logic one to its bit location . • Bit 0 – T OV1: T imer/Count er1, Overflow Fl ag The setting of this flag is dependent o f the WGM13:0 bits setting. In Normal and CTC mod es, the TOV1 Flag is set when the timer overflows. Refer to Table 16 -4 on page 141 for the TOV1 Flag behavior when using another WGM13:0 bit settin g. TOV1 is automatically cleared when the Tim er/Counter1 Ov erflow Inte rrupt Vect or is exec uted. Alterna tively, TOV1 can be cleared by writing a logic one to its bit location. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 147 17. T imer/Counter0 and Ti mer/Counter1 Prescalers ”8-bit Timer/ Counter0 with PWM” on page 102 and ” 16-bit Timer/Co unter1 with PWM” on page 120 share the same prescaler module, but the Timer/Coun ters can have different pr escaler setting s. The descrip tion below applies to both Timer /Counter1 and Time r/Counter0. 17.1 Internal Clock Source The Timer/Counter can be clocked direct ly by th e system clock (by setting the CSn2:0 = 1). This provides the fastest operation, with a maximum Timer/ Counter cl ock freque ncy equal to system clock frequen cy (f CLK_ I/O ). Alternative ly, one of four tap s from th e presca ler c an be used as a clock source. The prescaled clock has a frequency of e ither f CLK_I/O /8, f CLK_I/O /6 4, f CLK_I/O /256, or f CLK_I/O /1024. 17.2 Prescaler Reset The prescaler is free running, i.e., operates indepen dently of the Clock Select logic of the Timer/Counter, and it is shared by Time r/Counter1 and Time r /Counter0. Since the prescaler is not affected by the Timer/Cou nter’s clock select, the state of the prescale r will have implications fo r situations where a pres caled clock is used. One examp le of prescaling artifacts occur s when the time r is enabled a nd clocked by the prescaler (6 > CSn2:0 > 1). The number of system clock cycle s from when the timer is enabled to the first count occurs can be from 1 to N+1 system clock cycles, where N equals th e prescaler divisor (8, 64, 256, or 1024 ). It is possible to us e the prescale r reset for sync hronizing the Tim er/Coun ter to program execution. Ho wever, care must be taken if th e other Timer /Counte r that shares th e same prescaler also uses prescaling. A p rescaler reset will affect the prescaler period for all Timer/ Counters it is connected to. 17.3 External Clock Source An exte rnal clock s ource applie d to the T 1/T 0 pin can be used as Timer/Counter clock (clk T1 /clk T0 ). T he T1/T 0 pin is sampled once every system clock cycle by t he pin synchronization logic. The synchronized (samp led) signal is then passed th rough the edge detect or. Figu re 17-1 shows a functional equivale nt block d iagram of the T1/T0 synchronization and e dge detector logic. The regi sters are cloc ked at the pos itive edge of th e internal system clock ( clk I/O ). The latch is transpar ent in th e high pe riod of the internal s ystem cloc k. The edge detector gener ates one clk T1 /clk T 0 pulse for ea ch positive (C Sn2:0 = 7) or neg ative (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. Enabling and disabl ing of the clock in put must be done whe n T1/T0 has been stable fo r at least one system clock cycle, otherw ise it is a risk that a false Timer/Counter cloc k pulse is generated. Each half period of the external clock applied mus t be longer than one system cloc k cycle to ensure correct sampling. The external clock must be ensured to have less than half th e system clock frequency (f ExtClk < Tn_sync (T o Clock S elect Logic) Edge Detector S ynchronization DQ DQ LE DQ Tn clk I/O A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 148 f clk_I/O /2) given a 50/50% duty cycle. Since the edge dete ctor uses sampling, the maxi mum frequ ency of an external clock it can detect is half the sampling fr equency (Nyquist sampling th eo rem). Howeve r, due to variation of the system clock frequency and duty c ycle caused by Oscillato r source (crystal , resonator, and capacitors) tolerances, it is recomm ended that maxim um frequency of an external clock sour ce is less than f clk_I/O /2.5. An external clock source can not be prescaled. Figure 17-2. Prescaler for Timer /Counter0 and T imer/Counter1 (1) Note: 1. The synchronizatio n logic on the i nput pins ( T1/T 0) is shown in Figure 17-1 . P S R S YNC Clear clk T1 clk T0 T1 T0 clk I/O S ynchronization S ynchronization A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 149 17.4 Register Description 17.4.1 GTCCR – General T ime r/Counter Control Register • Bit 7 – TSM: T imer/Counter Synchronizat ion Mode Writing the TSM bit to one activates the Timer/Counte r Sy nchronization mode. In this mode, the value that is written to the PSRASY an d PSRSYNC bits is kept, h ence keepin g the corr esponding prescaler reset sign als asserted. This ensu res that the corr espond ing Timer/Counters are halted an d can be configured to the same value without the risk of one of them advancing during co nfiguration . When the TSM bi t is written to zero, the PSRASY and PSRSYNC bits are cleared by hardware, and the Tim er/Counters start counting simultaneously. • Bit 0 – PSRSYNC: Prescale r Reset When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be R e set. This bit is normally cleared immediate ly by har dware, exce pt if the TS M bit is se t. Note that Timer/Counter1 an d Timer/Counter0 shar e the same prescaler and a rese t of this prescaler w ill affect both timers. B i t 765432 1 0 0x23 (0 x43) TSM ––––– PSRASY PSRSYNC GTCCR Read/Write R/W R R R R R R/W R/W I n i t i a l V a l u e 000000 0 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 150 18. 8-bit Timer/Counter2 with PWM and Asynchronous Operation 18.1 Features • Single Cha nnel Coun ter • Clear Timer on Comp are Match (Auto Reload) • Glitch-free, Phase Correct Pulse Width Modulator (PWM) • Frequen cy Generator • 10-bit Clock Prescaler • Overflow and Compare Match Interrupt Sources (TOV2, OCF2A and OCF2B) • Allows Clocking from External 32kH z W atc h Crys t a l Independent o f the I/O Clock 18.2 Overview Timer/Counter 2 is a general purpo se, single channel, 8-bit Time r/Counter module. A simplified block diagra m of the 8-bit Timer/Co unter is s hown in Figure 18-1 . For the actual placement of I/O pins, refer to ”Pinout ATmega48A/PA/88A/PA/1 6 8A/PA/328/P” on pa ge 12 . CPU accessible I/O Registers, including I/O bits and I/O pins, are sh own in bold. Th e device-s pecific I/O Re gister and bit lo cations are list ed in the ”Register Descri ption” on page 162 . The PRTIM2 bit in ”Minimizing Po wer Consum ption” on p age 51 must be written to zero to enable Timer/ Counter2 m odule. Figure 18 -1. 8-bit T ime r/Counter Block Diagram 18.2.1 Regi sters The Tim er/Counter (TCNT2) and Out put Compar e Register (OCR2A an d OCR2B) ar e 8-bit re gisters. I nterrupt request (shorten as In t.Req.) signals are all visib le in the Timer In terrupt Fla g Register (TIFR2). All inte rrupts are Clock S elect Timer/Counter DA T A BU S OCRnA OCRnB = = TCNTn Wav e fo r m Generation Wav e fo r m Generation OCnA OCnB = Fix ed TO P V alue Control Logic = 0 TO P B OT TO M Count Clear Direction TOV n (Int.Req.) OCnA (Int.Req.) OCnB (Int.Req.) TCCRnA TCCRnB Tn Edge Detector ( F rom Prescaler ) clk Tn A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 151 individually masked with the Timer Inter rupt Mask Regist er (TIMSK2). TIFR2 and TIMSK2 are not shown in the figure. The Timer/Counter can be clocked interna lly, via the pr escaler , or asynchro nously clocked from the TOSC1/2 pins, as detailed later in this sec tio n. The asynchronous ope ration is controlle d by the Asynchronous Stat us Register (ASSR). The Clock Select logi c block controls which clock source he Timer/Coun ter uses to increment (or decrement) its value. The Timer/C ounter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clk T2 ). The double buffer ed Output Compare Register (OCR2A a nd OCR2B) are compared with the Timer/Counter value at all times. The re sult of the compar e can be used by the Wavefor m Generator to genera te a PWM or variable fre quency output o n the Output Compare pin s (OC2A and OC2B). Se e ” Output Compare Unit” on page 152 for details. The compare match event will also set th e Compare Flag (OC F2A or OCF2B) which can be used to generate an Output Compare interrupt request. 18.2.2 Definitions Many register and bit refe rences in this documen t are written in general form. A lower case “n” r eplaces the Timer/Counter number, in this ca se 2. However, when using the r egister or bit defines in a p rogram, the precise form must be used, i.e., TCNT2 for accessin g Timer/Co unter2 counter value and so on. The definitions in Tab le 18-1 are also used extensivel y through out the section. T ab le 18-1. Definitions 18.3 T imer/Cou nter Clock Sources The Timer/Counter can be clocked by an interna l synchro nous or an external asynchr onous clock source. The clock source clk T2 is by default equal to the MCU clock, clk I/O . When the AS2 bit in the ASSR Register is writte n to logic one, the clock source is taken from the Timer/Counter Oscillato r connected to TOSC1 and TOSC 2. For details on asynchronous opera tion, see ”ASSR – Asynchronous Stat us Register” on page 167 . For details on clock sources and prescaler, see ”Timer/Counter Presca ler” on page 161 . 18.4 Counter Unit The main part of the 8-bit Timer/Counter is the programmab le bi-directio nal counter unit. Fig ure 18-2 on pag e 151 shows a block diagram of the counter and its su rrounding en vironment. Figure 18-2. Counter Unit Block Diag ram BOTTOM The counter reaches the BOTTOM when it becom es zero (0x00). MAX The counter reaches its MAXimum when it becomes 0xFF (decima l 255). TOP The coun ter reache s the TOP wh en it becomes equal to th e highest va lue in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or th e value s tored in th e OCR2A Register. Th e assignm ent is dependen t on the mode of o peration. D ATA B U S TCNTn Control Logic count TOVn (Int.Req.) top bottom direction clear T OSC1 T/C Oscillator T OSC2 Prescaler clk I/O clk Tn A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 152 Signal descr iption (interna l signals): count Increment or decrement TCNT2 by 1. direction Sele cts between incr ement and decrement. clear Clear TCNT2 (set all bits to zero). clk Tn Timer/Counter clock, referred to as clk T2 in the following. top Signalize s that TCNT2 ha s reached maxim um value. bottom Signalizes that TC NT2 has reache d minimum valu e (zero). Depending on the mode of opera tion used, the counter is cleared, increme nted, or decremented at ea ch timer clock (clk T2 ). clk T2 can be generated fr om an extern al or intern al cl ock source, selected by the Clock Select bits (CS22:0). Whe n no clock source is selected (CS22:0 = 0) the timer is stopped. Howeve r, the TCNT2 value can be accesse d by the CP U, regardless of whethe r clk T2 is present or not. A CPU write overrid es (has priority ove r) all counter clear or count op erations. The counti ng sequence is dete rmined by the setti ng of the WGM2 1 and WGM20 bits located in th e Timer/Counter Control Regist er (TCCR2A) and the WGM22 located in th e Timer/Counter Contr ol Register B (TCCR2B). There ar e close connections between how t he counter be haves ( counts) and how wavefor ms are generate d on the Output Compare ou tputs OC2A and OC2B. For more details ab out adva nced counting sequence s and waveform generation, se e ”Modes of Operation” on page 155 . The Timer/Counter Overflow Flag (TOV 2) is set according to th e mode of opera tion selected by the WGM22:0 bits. TOV2 can be used for generating a CPU inte rrupt. 18.5 Output Comp are Unit The 8-bit comparator continuously compares TCNT 2 wit h the Output Compare Re gister (OCR2A an d OCR2B). Whenever TCNT2 equals OCR2A or OC R2B, the comparator signals a ma tch. A match will set the Output Compare Flag (OCF2A or OCF2B) at the next timer cl ock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates a n Output Compare inter rupt. The Output Co mpare Flag is automatica lly 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 lo cation . The Wave form Ge nerator uses the match sig nal to ge nerate a n output accord ing to oper ating mode set by th e WGM22 :0 bits and Compare Output mode (COM2x1:0) bits. The max and bottom signals are used by the Waveform Generator fo r handling the special ca ses of the extreme values in some mode s of operation ( ”Modes of Operation ” on page 155 ). Figure 18 -3 shows a block diagram of the Outp ut Compare unit. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 255  Gain error: Af ter adjusting for of fset, the gain error is found a s the deviati on of the last tran sition (0x3FE to 0x3FF) comp ared to the idea l transition (at 1.5 LSB belo w maximum). Ideal value: 0 LSB Figure 24-1 1. Gain Error  Integral Non-linearity (INL): After adjusting for of fset and gain error , the INL is the maxim um deviation of an actual transition comp ared to an idea l transition for any code. Ideal value: 0 LSB. Figure 24-12. Integral Non-linear ity (INL)  Dif ferential Non-linearity (DNL): Th e maximum deviation of the actual code wid th (the interval between two adjacent transitio ns) from the ideal code width (1 LSB). Ideal value: 0 LSB. Output Code V REF Input V oltage Ideal ADC Actual ADC Gain Error Output Code V REF Input V oltage Ideal ADC Actual ADC INL A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 256 Figure 24 -13. Differe ntial Non-l inearity (DN L)  Quantiza tion Error: Due to the quantization of the inpu t volt age into a finite number of code s, 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 (unad justed) transition compared to an ideal transition for a ny code. This is th e compound ef fect of of fset, gain error , dif ferential error , non-linear ity , and quantizatio n error . Ideal value: ±0.5 LSB. 24.7 ADC Conversion Result After the conversion is complete (ADIF is h igh), the conver sion result can be found in the ADC Result Registers (ADCL , ADCH) . For single ended conversion, the result is where V IN is the voltage on the selected inpu t pin and V REF the selected voltage refer ence (see Table 24-3 on page 2 57 and Table 24-4 on pa ge 258 ). 0x000 represen ts anal og ground , and 0x 3FF rep resents t he selecte d referenc e voltage minu s one LSB. 24.8 T emperature Measurement The tem perature m easurem ent is ba sed on a n on-chip t emperat ure senso r that is coupled t o a single ended ADC8 channel. Selecting the ADC8 chan nel by writing the MUX3...0 bits in ADMUX register to "1000" enables the temperature senso r. The internal 1.1V volta ge re ferenc e must also be selecte d for the ADC voltage referenc e source in the te mperature sensor m easurem ent. Whe n the temp erature sensor is enabled, the ADC converter can be used in single conversion mod e to measure the volta ge over the tempera ture sensor . The measured voltag e has a linear relationsh ip to the temper ature as described in Table 24-2 . The voltag e sensitivity is approximately 1 mV/°C and the accur a cy of the temperatur e measurement is +/- 10°C. The values descr ibed in Tabl e 24-2 are typical values. However, due to the pr ocess variation the temperature sensor output volta ge varies from one chip to another. To be capable of achieving m ore accura te results th e temperature m easurement can be calibrated in the applicat ion software. Th e software calibration requires that a Output Code 0x3FF 0x000 0 V REF Input V oltage DNL 1 LSB ADC V IN 1024  V REF ---------- ------------ ---- = T abl e 24-2. T emp erature vs. Sensor Output V oltage (T ypical Case) T em perature /  C -45  C +25  C +85  C V olt age / mV 242mV 314mV 380mV A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 257 calibration value is measured and stored in a regi ster or EEPROM for each chip, as a part of the production test. The software calibration can be done utilizing the formula: T = { [(ADCH << 8) | AD CL] - T OS } / k where ADCn are the ADC da ta registers, k is a fixe d coefficient and T OS is the temperat ure senso r offset value determined and stored into EEPROM as a part of the produ ction test. 24.9 Register Description 24.9.1 ADMUX – ADC Multiple xer Selectio n Register • Bit 7:6 – REFS[1:0]: Reference Selection Bit s These bits select the voltage refe rence for the ADC, as shown i n Table 24- 3 . If these bits are changed dur ing a conversion, the chan ge will not go in effe ct until this conversion is complete (ADIF in ADC SRA is set). The internal volta ge refere nce options may not be used if an external referen ce voltage is being applied to the AREF pin. • Bit 5 – ADLAR: ADC Le f t Adjust Result The ADLAR bit affects the presentation of the ADC conversion result in th e ADC Data Register. Write one to ADLAR to left adjust the re sult. Otherwise, the result is right adjus ted. Changing the ADLAR bit will affect the ADC Data Register immediately, regardless of any ongoing conver sions. For a complete de scription of this bit, see ”ADCL and ADCH – The ADC Da ta Register” on page 259 . • Bit 4 – Reserved This bit is an unused bit in the ATmega48A/PA/88A/PA/168A/PA/328 /P, and will always read as zero. • Bit s 3:0 – MUX[3:0]: Analog Ch annel Selection Bits The value o f these bits selects which anal og inputs are conn ected to the ADC. See Table 24-4 f or de tails. If these bits are changed during a conver sion, the c hange will not go in effect un til this conversion is complete (ADIF in ADCSRA is set). B i t 76543210 (0x7C) REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 ADMUX Read/Write R/W R/W R/W R R/W R/W R/W R/W I n i t i a l V a l u e 00000000 T ab le 24-3. V oltage Reference Selections for ADC REFS1 REFS0 V olt age Reference Selection 0 0 AREF , In ternal V ref turned off 0 1 AV CC with external capacitor at AREF pin 1 0 Reserved 1 1 Internal 1.1V V oltage Reference with exte rnal capacitor at AREF pin A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 258 Note: 1. For T emperatu re Sensor . 24.9.2 ADCSRA – ADC Control and St atus R egister A • Bit 7 – ADEN: ADC Enable Writing this bit to one enables the ADC. By writing it to z ero, the ADC is turned off. Turning the ADC off while a conversion is in progress, will terminate this c onversion. • Bit 6 – ADSC: ADC St art Conversion In Single Conversi on mode, write th is bit to one to start each conversion. In Free Ru nning mo de, write this bit to one to start the fir st conversion. The fir st conversi on after ADSC has been written after the ADC has been enabled, or if ADSC is written at th e same time as the ADC is enabled, w ill take 25 ADC clock cycles instead of the normal 13. This first c onversion performs initializ ation of the ADC. ADSC will read as one as long as a conv ersion is in progress. When the conversion is c omplete, it returns to zero. Writing zero to this bit has no effe ct. • Bit 5 – ADA TE: ADC Auto T rigger Enable When this bit is written to one, Au to Triggering of the AD C is enabled. The ADC w ill start a conversion on a positive edge of the selected t rigger signa l. The trigge r so urce is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB. T ab le 24-4. Input Channel Selections MUX3...0 Single Ended Input 0000 ADC0 0001 ADC1 0010 ADC2 001 1 ADC3 0100 ADC4 0101 ADC5 01 1 0 ADC6 0 111 ADC7 1000 ADC8 (1) 1001 (reserved) 1010 (reserved) 101 1 (reserved) 1 10 0 (reserved) 1 10 1 (reserved) 111 0 1.1V (V BG ) 1111 0V (GND) B i t 7 6543210 (0x7A) ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADP S0 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 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 259 • Bit 4 – ADIF: ADC Interrupt Flag This bit is set when an ADC conversion completes an d the Data Registers are up dated. The ADC Conversion Complete Interrupt is executed if the ADIE bit and the I- bit in SREG are set. ADIF is cleared by hard ware when executing the cor responding interr upt handling vector. Alte rn atively, ADIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write 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 th e I-bit in SREG is set, the ADC Co nver sion Complete Inte rrupt is act ivated. • Bit s 2:0 – ADPS[2:0]: ADC Prescaler Se lect Bit s These bits determine the division fa ctor be tween the system clock frequency an d the input clock to the ADC. 24.9.3 ADCL and ADCH – The ADC Dat a Register 24.9.3.1 ADLAR = 0 24.9.3.2 ADLAR = 1 When an ADC conversion is complete, the re sult is found in th ese two registers. T ab le 24-5. ADC Presca ler Selectio ns ADPS2 ADPS1 ADPS0 Division Factor 0 0 0 2 0 0 1 2 0 1 0 4 0 1 1 8 1 0 0 16 1 0 1 32 1 1 0 64 1 1 1 128 B i t 1 51 41 31 21 11 0 9 8 (0x79) – – – – – – ADC 9 ADC8 ADC H (0x78) ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC 1 ADC0 ADCL 76543210 R e a d / W r i t e RRRRRRRR RRRRRRRR I n i t i a l V a l u e 00000000 00000000 B i t 1 51 41 31 21 11 0 9 8 (0x79) ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADCH (0x78) ADC1 ADC0 –––––– ADCL 76543210 Read/Wri te R R R R R R R R RRRRRRR R Initial Value 0 0 0 0 0 0 0 0 00000000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 260 When ADCL is read, the ADC Data Registe r is not updated until ADCH is read . Consequent ly, if the result is left adjusted and no more th an 8-bit precision is required, it is sufficient to read ADCH . Otherwise, ADCL must be read firs t, then ADCH. The ADLAR bit in ADMUX, and the MUXn bits in ADMUX affect the way the result is read from the regis ters. 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 re sult from the conver sion, as detailed in ”ADC Conversion Result” on page 256 . 24.9.4 ADCSRB – ADC Control and St atus R egister B • Bit 7, 5:3 – Reserved These bits are reserved for future use. To ensure compat ibility with future devices, thes e bits must be written to zero when ADCSRB is written. • Bit 2:0 – ADTS[2:0]: ADC Auto T rigger Source If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If AD ATE is clea red, the ADTS[2:0] settings will have no ef fect. A conversion will be triggered by the rising edge of the sele cted Interrupt Flag . Note that switching from a trigge r source th at is cleared to a trigger source that is set, will generate a positi ve edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching to Free Runnin g mode (ADTS[2:0]=0) will not cause a trigger event, ev en if the ADC Interrupt Flag is set . 24.9.5 DIDR0 – Digital Inpu t Disable Regi ster 0 • Bit s 7:6 – Res erved These bits are reserved for future use. To ensure compat ibility with future devices, thes e bits must be written to zero when DIDR0 is written. B i t 7 6 543210 (0x7B) – ACME – – – ADTS2 AD TS1 ADTS0 ADCSRB Read/Wri te R R/W R R R R/W R/ W R/W Initial Value 0 0 0 0 0 0 0 0 T ab le 24-6. ADC Auto T rig ger Source Selections ADTS 2 ADTS1 ADTS0 T rigger Source 0 0 0 Free Runnin g mode 0 0 1 Analog Comparator 0 1 0 External Interrupt Request 0 0 1 1 T i mer/Counter0 Compare Match A 1 0 0 T i mer/Counter0 Overfl ow 1 0 1 T i mer/Counter1 Compare Match B 1 1 0 T i mer/Counter1 Overfl ow 1 1 1 T i mer/Counter1 Captur e Event B i t 76543210 (0x7E) –– ADC5D ADC4D ADC3D AD C2D ADC1D ADC0D DIDR0 Read/Write R R R/W R/W R/W R/W R/W R/W I n i t i a l V a l u e 00000000 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 261 • Bit 5:0 – ADC5D...ADC0D: AD C5...0 Digit al Input Disable When this bit is written logic one, the digital inp u t buffer on the correspond ing ADC pin is disabled . The corresponding PIN Register bit will always read as zero when this bit is set. When an an alog signal is appli ed to the ADC5...0 pin and the digi tal input from this pin is not neede d, this bit should be written logic one to reduce power consumptio n in the digital inpu t buffer. Note that ADC pins ADC7 and ADC6 do not have d igital inpu t buffer s, and there fore do not r equire Digital Input Disable bits. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 262 25. debugWIRE On-chip Debug System 25.1 Features • Complete Program Flo w Control • Emulates All On-chip Func tions, Both Digit al and Analog, excep t RESET Pin • Real-time Operation • Symbolic D ebugging Support (Both at C and Assembl er Source L evel, or for Othe r HLLs) • Unlimited Number of Program Br eak Poin t s (Using Sof t ware Break Points ) • Non-intru sive Operatio n • Electrical Characteris tics Identical to Real Device • Automatic Confi guration Syste m • High-Speed Operation • Programming of Non- volatile Memories 25.2 Overview The debugWIRE On- chip debug syste m uses a One-wire, bi -dire ctional interface to control the pr ogram flow, execute AVR instru ctions in th e CPU and to program the differ ent non- volatile me mories. 25.3 Physical Interface When the debug WIRE Enable ( DWEN) Fuse is progr am med a nd Lock bits are unpr ogrammed, the deb ugWIRE system within the targ et device is activated. The RESET port pin is configured as a wire- AND (open-dr ain) bi- directional I/O p in with pull-up ena bled and becom es t he communication gate way betw een target a nd emulator . Figure 25 -1. The debu gWIRE Setup Figure 25 -1 shows the schematic of a targ et MCU, with de bugWIRE enabled, and the emulato r connector. The system clock is not affected by debugWIRE and will always be the clock sour ce selected by the C KSEL Fuses. When designing a system where debug WIRE will be used, the following observ ations must be made for correct operation: dW GND dW(RESET) VCC 1.8 - 5.5V A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 263  Pull-up resistors on the dW/(RESET) line must not be smaller than 10k  . The pull-u p resistor is not required for debugWIRE functionality .  Connecting the RESET pin directly to V CC will not work.  Capacitors connected to the RESET pin must be disconnected when using debugWire.  All external reset sources must be disconnected. 25.4 Sof tware Break Point s debugWIRE suppor ts Program memor y Break Points by the AVR Break instruction. Setting a Break Point in Atmel Studio will insert a B REAK inst ruction in the Program memory. The instruction replaced by the BREAK instruction will be stored. When program execution is continued, the stored instructi on will be executed before continuing fr om the Program memor y. A break can be inse rted m anually by puttin g the BREAK instruction in the progr am. The Flash mu st be re-pro grammed e ach time a Break Poin t is change d. This is automatically handled b y Atmel Studio through the debug WIRE interf ace. The use of Brea k Points will therefore reduce the Flash Data retention. Devices used for debugging p urpos es shou ld not be shipped to end customers. 25.5 Limit ations of debugWIRE The debugWIRE co mmunication pin (d W) is physically lo cated on the same pin as Extern al Reset (RESET). An External Reset source is therefore not supporte d when the debugWIRE is enabled . A programmed DWEN Fuse ena bles some parts of the clock system to be running in all sleep modes. This will increase the power consumpt ion while in sleep. Thus, th e DWEN Fuse should be disabled wh en debugWire is not used. 25.6 Register Description The following sectio n describes the registers used with the de bugWire. 25.6.1 DWDR – debugWire Dat a Register The DWDR Register pro vides a communication channe l from the running program in the MCU to the debug ger. This register is on ly accessible by the d ebugWIRE and can therefore no t be used as a g eneral purp ose register in the normal oper ations. B i t 765 43210 DWDR[7:0] DWDR Read/Wri te 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 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 264 26. Self-Programming the Flash, AT m e g a 4 8 A / 4 8 PA 26.1 Overview In ATmega 48A/48PA there is no Re ad-While-Write sup port, and no separate Boo t Loader Section. The SPM instruction can be executed from the entir e Flash. The dev ice provid es a Self -Programm ing mech anism for d ownloadin g and uplo ading pr ogram cod e by the MCU itself. The Self-Programming can use any available data interface and associa ted protocol to read code and write (prog ram) that code into the Progra m memory. The Prog ram memory is updated in a page by page fash ion. Be fore progr amming a pag e with the data stored in the temporary page buffer, t he page must be erased. The temporary p age buffer is filled one word at a time using SPM and the buffer can be filled either before the Page Erase comm and or between a Page Erase and a Page Write operation : Alternative 1, fill the buffer before a Page Erase  Fill temporar y p age buf fer  Perform a Page Erase  Perform a Page W rite Alternative 2, fill the buffer after Page Erase  Perform a Page Erase  Fill temporar y p age buf fer  Perform a Page W rite If only a part of the page needs to be changed , the re st of the page must be stored (for example in the temporary p age buffer) before the erase, and then be re -written. Whe n using altern ative 1, the Boot Loader provides an effective Read-Mod ify-Write featur e which allows th e user software to first read the p age, do the necessary changes, and then write back the modified d ata. If alternative 2 is us ed, it is not possible to read the old data while l oading since the page is alread y eras ed. The temporar y page buffe r can be accessed in a random sequence. It is essential that the pag e address used in both the Page Erase and Page W r ite operation is addressing th e same p age. 26.1.1 Performing Page Erase by SPM To execute Page Erase, set up the ad dress in the Z-pointer, write “00000011” 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 igno red during this operation.  The CPU is halted du ring the Pa ge Erase o peration. Note: If an interrupt occurs in the ti me sequence the four cycle a ccess cannot be ensured. In order to ensure atomic oper- ation yo u should disa ble inte rr upts before writing to SP MCSR. 26.1.2 Filling the T emporar y Buffer (Page Loading) To write an instructio n word, set up the address in th e Z-p ointer and data in R1:R0, write “0000000 1” to SPMCSR and execute SPM within fo ur clock cy cles after writing SPMC SR. The co ntent of PCWO RD in the Z- register is used to addre ss the data in the temporary buffer. The te mporary buffer will auto -erase after a Page Write op eration o r by writ ing the RW WSRE bit in S PMCSR. It is also erased a fter a sys tem re set. Note t hat it is not possib le to write more than one tim e to each a ddress wit hout era sing the tem porary buffer. If the EEPROM is written in the middle of an SPM Page Load operation, all data loaded will be lost. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 271 ignored. The PGERS bit will auto-clear upon comple tion of a Page Erase, or if no SPM instruction is exec uted within four clock cycles. The CPU is halted during the entire Page Write operation. • Bit 0 – SPMEN: Store Program Me mory This bit e nables the S PM instru ction for the next four clock cycles. If w ritten to o ne togeth er with eit her RWWSRE, BLBSET, PGWRT, or PGER S, the following SPM instruction will have a sp ecial meaning, see description above. If only SPMEN is wr itten, the following SPM instruction will s tore the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of th e Z-pointer is ignored. The SPMEN bit will auto-clear upon co mpletion of an SPM instruction, or if no SPM ins truction is ex ecuted wit hin four cloc k cycles. During Page Erase and Page Write, the SPMEN bit rema ins high until the operatio n is completed. Writing any othe r combination than “ 10001”, “01001” , “00101”, “ 00011” or “00001” in the lower five bits will have no effect. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 272 27. Boot Loader Support – Read -While-W rite Self-Programming The Boot Loader Sup port applies to ATmega88A/88PA/1 68A/168PA/328/328 P 27.1 Features • Read-While-Write Se lf-Programming • Flexible Boot Memo ry Size • High Security (Sep arate Boot Lo ck Bits for a Flexible Protection) • Sep a rate Fuse to Select Reset V ector • Optimized Pa ge (1) Size • Code Efficien t Algorithm • Efficient Read-Modify-Write Suppor t Note: 1. A p age is a secti on in the Flash consisting of several bytes (see Table 28-11 on pa ge 294 ) used durin g pro- gramming. The page organization does no t af fect normal operati on. 27.2 Overview In ATmega88A/88PA/16 8A/168PA/328/328P the Boo t Loader Support pr ovides a real Read-While-Wr ite Self- Programming mechanism for downloading and up loading prog ram code by th e MCU itse lf. This feature allows flexible applicat ion software updates con trolled by the MCU using a Flash-re sident Boot Load er progra m. The Boot Loader program can use a ny available data in terf ace a nd associated protocol to read code and write (program ) that code into the Flash me mory, or read the code from the prog ram memory. The pr ogram code within the Boot Loader section has the capability to write into the entire Flash, including the Boot Loader memory. The Boot L oader 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 co nfigurable with fuses and th e Boot Loader ha s two separ ate sets of Boot Lock bits which c an be set i ndependently. This gives the user a unique flexibility to select different leve ls of pr otection. 27.3 Application and Boot Loader Flash Sections The Flash memory is orga nized in two main sections, th e Applica tion section and th e Boot Loader section (se e Figure 27 -2 ). The size of the different sections is co nfigured by the BOOTSZ Fuses as shown in Table 2 7-7 on page 2 84 and Figure 27-2 . These two sections c an have diff erent lev el of pro tection sinc e they ha ve differ ent sets of Lock bits. 27.3.1 Application Section The Applic ation sect ion is the se ction of th e Flash tha t is used for storing the app lic ation code. The protection level for the Application sect ion can be selected by the application Boot Lock bits (Boo t Lock bits 0), see Tabl e 27-2 on page 276 . The Application section can never store any Boot Loader code since the SPM instruction is disabled when ex ecuted fr om the A pplication section. 27.3.2 BLS – Boot Loader Sect ion While the Application se ction is used for sto ring the application cod e, the The Boot Loader software must be located in the BLS since the SPM instruction can initia te a programmin g when executing from the BLS only. The SPM instruction can access the e ntire Flash, including th e BLS itself. The protection level fo r the Boot Loader section ca n be sele cted by the Boot Load er Lock bits (Boo t Lock bits 1), see Table 27-3 on page 276 . A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 273 27.4 Read-While-W rite and No R ead-While-W rite Flash Sections Whether the CPU supports Read- While-Write or if the CP U is halted during a Boot Loader softwar e update is dependent on which ad dress that is being programmed . In addition to the two sections that are configurable by the BOOTSZ Fuses as de scribed above, the Flash is also divided into two fixed sectio ns, the Read- While-Write (RWW) section and the No Read-Whi le-Write (N RWW) section. T he limit betw een the RWW- and NRWW sections is given in Table 27-8 on page 284 and Figu re 27-2 o n page 275 . The main differ ence betw een the tw o sections is:  When erasing or writing a page lo cated inside the R WW section, the NRWW se ction can be read during the opera tion.  When erasing or writing a page loca ted inside the NR WW section, the CPU is h alted during the entire operation. Note that the user software can never read any code that is located inside the RWW sectio n during a Boot Loader softwar e operatio n. The syntax “ Read-While-Wr ite section” refers to which section that is being programme d (erased or written), not which section th at ac tually i s being r ead during a Boot Loa der software update . 27.4.1 R WW – Re ad-Wh ile-Write Section If a Boot Loader software up date is programming a pa ge inside the RWW section, it is possible to read cod e from the Flash, b ut only co de that is loc ated in the NRWW section. During an on-going pro gramming, the softwar e must ensu re that the RWW sec tion never is being read. If the user software is trying to read code that is located inside the RWW section (i .e., by a call/jmp/lpm or an inter rupt) during progra mming, the software might end up in an unknown state. To avoid this, the inte rrupts should eit her be disable d or moved to the Boo t Loader section. The Boot Lo ader section is always lo cated in the NRWW section. The RWW Section Busy bit (RWWSB) in the Store Progra m Memory Control and Status Register ( SPMCSR) will be read as logical one as long as the RWW section is blocked for reading . Afte r a prog ramming is completed , the RWWSB must be cleared by softwar e before reading code located in the RWW section. See Sectio n “27.9.1” on pa ge 287. fo r details on how to clear RWWSB. 27.4.2 NRWW – No Read-While-W rite Section The code located in the NRWW section can be read when the Boot Loade r software is updating a page in the RWW section. When the Boot Loader code update s the NRWW section, the CPU is halted during the entire Page Erase or Pag e Write operation. T abl e 27-1. Re ad-While-Write Features Which Secti on does the Z- pointer Address durin g the Programming? Which Sec tion can be read during Programming? CPU Halted? Read-While-Write Supported? R WW Section NRWW Section No Ye s NR WW Section None Ye s No A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 274 Figure 27 -1. Read-While -Write vs. No Read-While-W rite Read-While-Write (R WW) S ection No Read-While-Write (NR WW) S ection Z-pointer Addresses RWW S ection Z-pointer Addresses NRWW S ection CPU is Halted During the Operation Code Located in NRWW S ection Can be Read During the Operation A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 275 Figure 27 -2. Memory Sections Note: 1 . The p arameters in the figure above are gi ven in Table 27-7 on page 284 . 27.5 Boot Loader Lock Bit s If no Boot Loader capability is needed, the entire Flash is available for application code. The Boot Loader has two separ ate sets of Boot Lock bits which c an be set i ndependently. This gives the user a unique flexibility to select different leve ls of pr otection. The user can select:  T o protect the entire Flash from a sof t ware upda te by the MCU.  T o protect only the Boot Loader Flash sect ion from a soft ware update by the MCU .  T o protect only the Application Flash sect ion fro m a sof tware update b y the MCU.  Allow software up date in the entire F lash. See Table 27- 2 and Table 27 -3 for further de tails. The Boot Lock bits can be set in software and in Serial or Parallel Pr ogramming mode, but th ey can be cleared by a Chip Erase command only. The general Write Lock (Lock Bit mode 2) do es not co ntrol the programm ing of the F lash memo ry by SPM in struction. Similarly, the general Re ad/Write Lo ck (Lock Bit mode 1) does not cont ro l reading nor writing by LPM/ SPM, if it is attempted. 0x0000 Flashend Program Memory BOOTSZ = '11' Application Flash S ection Boot Loader Flash S ection Flashend Program Memory BOOTSZ = '10' 0x0000 Program Memory BOOTSZ = '01' Program Memory BOOTSZ = '00' Application Flash S ection Boot Loader Flash S ection 0x0000 Flashend Application Flash S ection Flashend End RWW S tart NRWW Application Flash S ection Boot Loader Flash S ection Boot Loader Flash S ection End RWW S tart NRWW End RWW S tart NRWW 0x0000 End RWW, End Application S tart NRWW, S tart Boot Loader Application Flash S ection Application Flash S ection Application Flash S ection Read-While-Write S ection No Read-While-Write S ection Read-While-Wr ite S ection No Read-While-Write S ection Read-While-Write S ection No Read-While-Write S ection Read-While-Write S ection No Read-While-Write S ection End Application S tart Boot Loader End Application S tart Boot Loader End Application S tart Boot Loader A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 276 Note: 1. “1” means unp rogrammed, “0” means p rogrammed Note: 1. “1” means unp rogrammed, “0” means p rogrammed 27.6 Entering the Boot Loader Program Entering the Boot Loa der takes place by a jump o r call from the applicat ion program. This may b e initiated by a trigger such as a co mmand received via USART, or SPI in terface. Alter natively, the Boot Rese t Fuse can be programme d so that the Rese t Vector is pointing to the Bo o t Flash st art addr ess after a reset. In this c ase, th e Boot Loader is started after a reset. After th e applicat ion code is loaded, the program can start executing the application co de. Note that the fu ses cannot be chang ed by the MCU itself. This means that once the Bo ot Reset Fuse is programmed, t he Reset Vector will always point to the Bo ot Loader Reset and the fuse can only be chan ged through the serial or parallel p rogramming interface. Note: 1. “1” means unp rogrammed, “0” means p rogrammed T abl e 27-2. Bo ot Lock Bit0 Protection Modes (Application Section) (1) BLB0 Mode BLB02 BLB01 Protection 1 1 1 No restriction s for SPM or LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 3 0 0 SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt V ectors are placed in the Boot Loader sectio n, interrupts are disabled while executing from the Applicatio n section. 4 0 1 LPM executing from the Boot Load er sectio n is not allow ed to read from the Application secti on. If Interrupt V e ctors are placed in the Boot Loader section, interrup t s are disabled while executing from the Application section. T abl e 27-3. Bo ot Lock Bit1 Protection Modes (Boot Loader Section ) (1) BLB1 Mode BLB12 BLB1 1 Protection 1 1 1 No restriction s for SPM or LPM accessing the Boot Loader section. 2 1 0 SPM is n ot allowed to write to the Boot L oader section. 3 0 0 SPM is not allowed to w rite to the Boot Loade r section, a nd LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interru pt V ectors are placed in the Application se ction, interru p ts are disabled while executing from the Boot Lo ader section. 4 0 1 LPM executing from the Applicat ion section is not allowed to read from the Boot Loader section. If Interrupt V ectors are placed in the Application se ction, interrupts are disabl ed while executing from the Boot Loader section. T abl e 27-4. Bo ot Reset Fuse (1) BOOTRST Reset Address 1 Reset V ector = Applicati on Reset (address 0x0000) 0 Reset V ector = Boot Loader Re set (see Table 27-7 on page 284 ) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 277 27.7 Addressing the Flash During Self-Programming The Z-point er is used to address the SPM command s. Since the Flash is organized in pages (see Table 28-11 on pag e 294 ), the Pro gram Counter can be treate d as having two different sections. On e sectio n, consisting of the least sig nificant bits, is ad dressing the words within a page, while the most significant bits are addr essing the pages. This is1 shown in Figu re 27-3 . Note that the Page Erase and Page Write operations are ad dressed indep endently. Therefor e it is of major importa nce that the Boot Loader so ftware addresse s the same page in bo th the Page Er ase and Page Write o peration. Once a programming op eration is initiated, th e addr ess is latched and the Z- pointe r can be used fo r other operations. The only SPM opera tion that does not use th e Z-pointer is Setting the Boot Loader Lock bits. The content of the Z-pointer is ignored and will have no effe ct on the operation. Th e LPM instruction does al so use the Z-pointer to store the address. Since th is instruction a ddresses the Flas h byte -by-byte, also the LSB ( bit Z0) of the Z-poin ter is used. Figure 27 -3. Addressing the Fl ash During SPM (1) Note: 1. The different variables u sed in Figure 27-3 are listed in Table 27-9 on page 284 . B i t 1 51 41 31 21 11 0 9 8 ZH (R31) Z15 Z14 Z13 Z12 Z1 1 Z10 Z9 Z8 Z L ( R 3 0 ) Z 7Z 6Z 5Z 4Z 3Z 2Z 1Z 0 76543210 PROGRAM MEMORY 0 1 15 Z - REGI S TER BIT 0 ZPAGEM S B WORD ADDRE SS WITHIN A PAGE PAGE ADDRE SS WITHIN THE FLA S H ZPCM S B IN S TR UCTION W ORD PA G E PCWORD[P AGEM S B:0]: 00 01 02 P AGEEND PA G E PCWORD PCP AGE PCM S B PAGEM S B PROGRAM COUNTER A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 278 27.8 Self-Programming the Flash The progr am memory is u pdated in a pa ge by page fashion. Before progra mming a page with the d ata stored in the temporary page buffer, t he page must be erased. The temporary p age buffer is filled one word at a time using SPM and the buffer can be filled either before the Page Erase comm and or between a Page Erase and a Page Write operation : Alternative 1, fill the buffer before a Page Erase  Fill temporar y p age buf fer  Perform a Page Erase  Perform a Page W rite Alternative 2, fill the buffer after Page Erase  Perform a Page Erase  Fill temporar y p age buf fer  Perform a Page W rite If only a part of the page needs to be changed , the re st of the page must be stored (for example in the temporary p age buffer) before the erase, and then be rewritten. Wh en using alter native 1, th e Boot Loader provides an effective Read-Mod ify-Write featur e which allows th e user software to first read the p age, do the necessary changes, and then write back the modified d ata. If alternative 2 is us ed, it is not possible to read the old data while l oading since the page is alread y eras ed. The temporar y page buffe r can be accessed in a random sequence. It is essential that the pag e address used in both the Page Erase and Page W r ite operation is addressing th e same p age. See ”Simple Assembly Co de Example for a Boot Loader” on page 281 for an assembly code exam ple. 27.8.1 Performing Page Erase by SPM To execute Page Erase, set up the ad dress in the Z-pointer, wr ite “X0000011 ” to SPMCSR and exec ute 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 igno red during this operation.  Page Eras e to the R WW section: T he NRWW section can be read du ring the Pa ge Erase.  Page Erase to the NR WW section: The CPU is halted during the operatio n. 27.8.2 Filling the T emporar y Buffer (Page Loading) To write an instructio n word, set up the address in th e Z-p ointer and data in R1:R0, write “0000000 1” to SPMCSR and execute SPM within fo ur clock cy cles after writing SPMC SR. The co ntent of PCWO RD in the Z- register is used to addre ss the data in the temporary buffer. The te mporary buffer will auto -erase after a Page Write op eration o r by writ ing the RW WSRE bit in S PMCSR. It is also erased a fter a sys tem re set. Note t hat it is not possib le to write more than one tim e to each a ddress wit hout era sing the tem porary buffer. If the EEPROM is written in the middle of an SPM Page Load operation, all data loaded will be lost. 27.8.3 Performing a Page Write To execute Page Write, set up the address in the Z- pointer, write “X0 000101” 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 mu st be written to zero during th is operation.  Page W rite to the R W W section: The NR WW section can be read during the Page W rite.  Page W rite to the NR WW section: The CPU is halted during the o peration. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 279 27.8.4 Using the SPM I nterrupt If the SPM interrupt is enabled, t he SPM interrupt will generat e a constant interrupt when the SPMEN bit in SPMCSR is cleared. This means that the interr upt can be used in stead of polling the SPMCSR Register in softwar e. When using the SPM interrup t, the Interrupt Vectors should be moved to t he BLS section to avoid that an interrupt is accessing the RW W se ction when it is blocked for read in g. How to move th e interrupts is describe d in ”Inter rupts” o n page 6 6 . 27.8.5 Consideration While Up dating BLS Special care must be take n if the user allows the Boot Loade r section to be update d by leaving Boot Lock bit11 unprogra mmed. An accidental write to the Boo t Loader it self can corrupt th e entire Boot Lo ader, and furthe r software updates might be impossible. If it is not necess ary to change th e Boot Loader software itself, it is recommended to prog ram the Boot Lock bit11 to pr otect the Boot Loader software from any internal software changes. 27.8.6 Prevent Reading the RWW Section Durin g Self-Programming During Self- Programming (e ither Page Erase or Page Wr ite), the RWW sectio n is always blocked for read ing. The user so ftware itself must preven t that this se ction is addresse d duri ng th e self programmin g operation. T he RWWSB in the SPMCSR will be set as long as the RWW section is busy. During Self-P rogramming t he Interrupt Vector table sho uld be moved to the BLS as described in ”W atchdog Time r” on page 60 , or the interrupts must be disabled. Before add ressing the RWW se ction after t he program ming is co mpleted, th e user so ftware m ust clear the RWWSB by writing the RWWSRE. See ”Simp le Assembly Code Example fo r a Boot Loader ” on page 281 for an example. 27.8.7 Setting the Boot Loader Loc k Bit s by SPM To set the Boot Loader Lock bits and gener al Lock Bits , write the desired da ta to R0, write “X0001001” to SPMCSR and execute SPM within four clock cy cles after writ ing SPMCSR. See Table 27- 2 and Table 27 -3 for how the different se ttings of the Bo ot Loader bits affect the Flash access. If bits 5...0 in R0 are cleared (zer o), the corresponding Lock bit will be pr ogrammed if an SPM ins truction is executed within four cycles after BL BSET and SPMEN are set in SPMCSR. Th e Z-pointer is don’t care during this operation, but for futu re compatibility it is recomm ended to load the Z-pointer with 0x0001 (same as used for reading t he lO ck bits). For future compatibility it is also recommended to set bits 7 and 6 in R0 to “1” when writing the Lock bits. When programming the Lock bits the entire Fl ash can be read during the operation. 27.8.8 EEPROM Write Prevent s Writing to SPMCSR Note that an EEPROM write operatio n will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during th e EEPROM write operation. It is recommended that the user checks the status bit (EEPE) in the EECR Register and verifies that the bit is cl eared before wr iting to the SPMCSR Register. 27.8.9 Reading the Fuse and Lock Bit s from Soft ware It is possible to read both the Fuse and Lock bits fr om software. To read the Lock bits, loa d the Z-pointer with 0x0001 and set the BLBSET and SPMEN bits in SPMCSR. When an LPM inst ruction is executed within three CPU cycles after the BLBSET and SPMEN bits are set in SPMCS R, the value of the Lock bits will be loaded in the destination register. T he BLBSET and SPMEN bits will auto-clear u pon completion of re ading the Lock bits B i t 76543210 R0 1 1 BLB12 BLB1 1 BLB02 BLB01 LB2 LB1 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 280 or if no LPM instruction is executed within thre e CPU cycles or no SPM instruction is executed withi n four CPU cycles. When BLBSET and SPMEN are cleared, LPM will wo rk as described in the Instruction set Manual. The algorith m for reading the Fuse Low byte is similar to the one described above for r eading the Lock bits. To read the Fuse Low byte, load th e Z-pointer with 0x000 0 and set the BLBSET a nd SPMEN bits in SPMCSR. When an LPM instruction is execut ed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low by te (FLB) will be loaded in the destination register as show n below. Refer to Table 28-5 on page 291 for a detailed descrip tion and mapping of the Fuse Low byte. Similarly, when read ing the F use High byte, loa d 0x0003 in the Z -pointer. When an LPM ins truction is execut ed 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 th e destination register as shown below. Refer to Table 28-7 on page 291 for detailed description and mapping of the Fuse High byte. When reading the Exte nded Fuse byte , load 0x0002 in the Z-po inter. When an LPM instruction is executed within three cycles after the BLBSET and SPMEN bits are set in the SPMCSR, the value of t he Extended Fuse byte (EFB) will be loaded in the destinati on register as show n below. Refer to Table 28- 5 on page 291 for detailed description an d mapping of the Extended Fuse byte. Fuse and Lock bits that ar e programmed, will be read as zero. Fuse and Lock bits that ar e unprogrammed, w ill be read as one. 27.8.10 R eading the Signat ure Row from Sof tware To read the Signature Row from softwar e, load the Z-pointer with the sig nature byte address give n in Table 27 - 5 on page 280 and set the SIGRD and SPMEN bi ts in SPMCSR. When an LPM in struction is execut ed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, th e signature byte value will be loaded in the destination register. The SIG RD and SPMEN bits will auto-clear upon co mpletion of read ing the Signature Row Lock bits or if no LPM instruc tion is execut ed within three CPU cycles. When SIGR D and SPMEN are cleared, LPM will work as described in the Instruction set Manual. Note: All other addresses are reserved for future use. B i t 76543210 Rd – – BLB12 BLB1 1 BLB02 BLB01 LB2 LB1 B i t 7 6 543 2 1 0 Rd FLB7 FLB6 FLB5 FLB4 FLB3 FLB2 FLB1 FLB0 B i t 7 6 543 2 1 0 Rd FHB7 FHB6 FHB5 FHB4 FHB3 FHB2 FHB1 FHB0 B i t 7 6 543 2 1 0 Rd – – – – EFB3 EFB2 EFB1 EFB0 T ab le 27-5. Signature Row Addressin g Signatur e Byte Z-Pointer Addre ss Device Signature Byte 1 0x0000 Device Signature Byte 2 0x0002 Device Signature Byte 3 0x0004 RC Oscillator Calibration Byte 0x0001 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 287 27.9 Register Description 27.9.1 SPMCSR – Store Program Memo ry Control and S t atus Register The Store Prog ram Memory Co ntrol and Status Register contains the co ntrol bits need ed to control the Boot Loader o perations. • Bit 7 – SPMIE: SPM Interrupt Enable When the SPMIE bit is written to one, and th e I-bit in t he Status Register is set (one ), the SPM ready interrup t will be enabled. The SPM ready Interrupt will be executed as long as the SPMEN bit in the SPMCSR Register is cleared. • Bit 6 – R W WSB: Read-W hile-W rite Section Busy When a Se lf-Programm ing (Page Er ase or Pa ge Write) operation to the RWW secti on is initiated, the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section ca nnot be accessed. The RWWSB bit will be cleared if the R WWSRE bit is wr itten to one after a Self-Progr amming operation is completed. Alternatively the RWWSB bit will automatically be cleared if a page load operation is initiated. • Bit 5 – SIGRD: Si gnature Row Read If this bit is written to one at the s ame time as SPMEN , the next LPM instruction wi thin three cl ock cycles will read a byte from the sig nature ro w in to the destinatio n register. se e ”Reading th e Signature Row from Softwar e” on page 280 for details. An SPM instructio n within four cycles after SIG RD and SPMEN are set will have no effect. This operation is reserved for future use and should not be use d. • Bit 4 – R WWSRE: Read-While-Write Section Read Enable When program ming (Page Erase or Page Wr ite) to the RWW section, the RWW section is blo cked for read ing (the RWWSB will be set by hardware). To re-enable the RWW section, th e user softw are 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 SPM EN, the ne xt SPM instru ction within fo ur clock cycles re-enables the RWW section. The RWW section cannot be re-enable d while the Flash is busy wi th a Page Erase or a Page Write (SPM EN 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 : Bo ot Lock Bit Set If this bit is written to one at the s ame time as SPMEN , the next SPM instruction wit hin four clock cycles sets Boot Lock bits and Memory Lock bits, according to the data in R0. The data in R1 and the address in the Z- pointer are ignored. The BLBSET bit will au tomatically be cleared up on completion of the Lock bit set, or if no SPM instruction is executed w ithin four clock cycles. An LPM instruction within three cycles after BLBSET and SPMEN are set in th e SPMCSR Register, will read either the Lock bits or the Fuse bits (depending on Z0 in th e Z-pointer) into th e destination register. See ”Reading the Fuse and L ock Bits from Software ” on page 2 79 for details. • Bit 2 – PGWRT : Page W rite If this bit is written to one at the s ame time as SPM EN, the next SPM instructi on within four clock cycles executes Page Write , with the data stored in the temporar y buffer. The page address is taken fro m the high par t of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear up on c ompletion of a Page Bit 7 6 5 4 3 2 1 0 0x37 (0 x57) SPMIE RWWSB SIGRD RWWSR E 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 0 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 288 Write, or if no SPM ins truction is ex ecuted wit hin four clock cycles. The CPU is ha lted during the entire Page Write operation if the NRWW section is addr essed. • Bit 1 – PGERS: Page Erase If this bit is written to one at the s ame time as SPM EN, the next SPM instructi on within four clock cycles executes Pag e Erase. The pag e addre ss is taken from the hi gh part of the Z-pointe r. The data in R1 and R0 are ignored. The PGERS bit will auto-clear upon comple tion of a Page Erase, or if no SPM instruction is exec uted within four clock cycles. The CPU is halted during the entire Page Writ e operat ion if th e NRWW section is addressed. • Bit 0 – SPMEN: Store Program Me mory This bit e nables the S PM instru ction for the next four clock cycles. If w ritten to o ne togeth er with eit her RWWSRE, BLBSET, PGWRT or PGERS, the following SPM instruction will have a special meaning, see description above. If only SPMEN is wr itten, the following SPM instruction will s tore the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of th e Z-pointer is ignored. The SPMEN bit will auto-clear upon co mpletion of an SPM instruction, or if no SPM ins truction is ex ecuted wit hin four cloc k cycles. During Page Erase and Page Write, the SPMEN bit rema ins high until the operatio n is completed. Writing any othe r combination than “ 10001”, “01001” , “00101”, “ 00011” or “00001” in the lower five bits will have no effect. A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 289 28. Memory Programming 28.1 Program And Dat a Memory Lock Bit s The ATmega 48A/4 8PA provides two Lock bits and th e ATmega88A/88PA/16 8A/168PA/328/32 8Pprovides six Lock bits. Th ese can be left unprogramm ed (“1”) or can be programm ed (“0”) to obta in the addition al feature s listed in Tabl e 28-2 . The Lock bits can only be erased to “1” with the Chip Erase command . The ATmega 48A/4 8PA has no separate Bo ot Loader sectio n, and the SPM instruction is enabled for the who le Flash if the SELFPRGEN fuse is progra mmed (“0” ). Otherwise the SPM ins truction is disabled. Notes: 1. “1” means unpro grammed, “0” means p rogrammed. 2. Only on A Tmega88A/88P A/168 A/168P A/328/328P. Notes: 1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 2. “1” means unpro grammed, “0” means p rogrammed T able 28-1. Lock Bit Byte (1) Lock Bit Byte Bit No De scription Default V alue 7 – 1 (unprogrammed) 6 – 1 (unprogrammed) BLB12 (2) 5 Boot Lock bi t 1 (u nprogrammed) BLB1 1 (2) 4 Bo ot Lock bit 1 (unprogramme d) BLB02 (2) 3 Boot Lock bi t 1 (u nprogrammed) BLB01 (2) 2 Boot Lock bi t 1 (u nprogrammed) LB2 1 Lock bit 1 (unprogrammed) LB1 0 Lock bit 1 (unprogrammed) T able 28-2. Lock Bit Protect ion Mode s (1)(2) Memory Lo ck Bit s Protection T ype LB Mode LB2 LB1 1 1 1 No memory lock features enabled . 2 1 0 Further programming of the Flas h and EEPROM is disabled in Parallel and Serial Programming mode. The Fuse bits are locked in both Serial and Parallel Programming mode. (1) 3 0 0 Further programming and verifi cation of the Flash and EEPROM is disabled in Parall el and Serial Programming mode. The Boot Lock bits and Fuse bit s are locked in both Serial and Parallel Programming mode. (1) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 290 Notes: 1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 2. “1” means unpro grammed, “0” means p rogrammed 28.2 Fuse Bit s The ATmega48A/PA/88A/PA/168A/PA/ 328/P has three Fuse bytes. Table 28- 4 - Table 28-9 on page 292 describe briefly the function ality of all the fuses and how they are map ped into the Fuse bytes. Note that the fuses are read as log ical zero , “0”, if they are prog rammed. T able 28-3. Lock Bit Protect ion Mode s (1)(2) . Only A Tmega88 A/88P A/168A/168P A/328/328P. BLB0 Mode BLB02 BLB01 1 1 1 No restriction s for SPM or LPM accessing the Application section. 2 1 0 SPM is not allowed to write to the Application section. 3 0 0 SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt V ectors are placed in the Boot Loader sectio n, interrupts are disabled while executing from the Applicatio n section. 4 0 1 LPM executing from the Boot Load er sectio n is not allow ed to read from the Application secti on. If Interrupt V e ctors are placed in the Boot Loader section, interrup t s are disabled while executing from the Application section. BLB1 Mode BLB12 BLB1 1 1 1 1 No restriction s for SPM or LPM accessing the Boot Loader section. 2 1 0 SPM is n ot allowed to write to the Boot L oader section. 3 0 0 SPM is not allowed to w rite to the Boot Loade r section, a nd LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interru pt V ectors are placed in the Application se ction, interru p ts are disabled while executing from the Boot Lo ader section. 4 0 1 LPM executing from the Applicat ion section is not allowed to read from the Boot Loader section. If Interrupt V ectors are placed in the Application se ction, interrupts are disabl ed while executing from the Boot Loader section. T ab le 28-4. Extended Fuse Byte for A Tmega 48A/48P A Extended Fuse Byte Bit No Description Default V alue – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 – 3 – 1 – 2 – 1 – 1 – 1 SELFPRGEN 0 Self Programming Enable 1 (unprogrammed) A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 291 Note: 1. The default value of BOOTSZ[1:0 ] results in maximum Boot S ize. See ”Pin Name Mapping” on page 295 . Note: 1. See Table 29-12 on page 314 for BODLEVEL Fuse decoding. T ab le 28-5. Extended Fuse Byte for A Tmega 88A/88P A /168A/168P A Extended Fuse Byte Bit No Descr iption Default V alue – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 – 3 – 1 BOOTSZ1 2 Select Boot Size (see Table 27-7 on page 284 and Table 27-10 on page 285 for details) 0 (programmed) (1) BOOTSZ0 1 Select Boot Size (see Table 27-7 on page 284 and Table 27-10 on page 285 for details) 0 (programmed) (1) BOOTRST 0 Select Reset V ector 1 (unprogrammed) T ab le 28-6. Extended Fuse Byte fo r A Tmega 328/328P Extended Fuse Byte Bit No Descr iption Default V alue – 7 – 1 – 6 – 1 – 5 – 1 – 4 – 1 – 3 – 1 BODLEVEL2 (1) 2 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL1 (1) 1 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL0 (1) 0 Brown-out Detector trigger level 1 (unprogrammed) T ab le 28-7. Fuse High Byte for A Tmeg a48A/48P A/88A/88P A/168A/168P A High Fuse Byte Bit No Descriptio n Default V alue RSTDISBL (1) 7 External Reset Disable 1 (unprogrammed) DWEN 6 debugWIRE En able 1 (unprogrammed) SPIEN (2) 5 Enable Serial Prog ram and Data Downloadi ng 0 (programmed, SPI programmi ng enabled) WDTON (3) 4 W atchdog T imer Always On 1 (unpro grammed) EESA VE 3 EEPROM memory is preserved through the Chip Erase 1 (unprogrammed), EEPROM not reserved A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 292 Notes: 1. See ”Alternate Functions of Port C” on page 94 for description of RSTDISBL Fuse. 2. The SPIEN Fuse is not accessible in serial programming mo de. 3. See ”WDTCSR – Watchdog Time r Control Register” on page 63 for details. 4. See Table 29-12 on page 314 for BODLEVEL Fuse decoding. Notes: 1. See ”Alternate Functions of Port C” on page 94 for description of RSTDISBL Fuse. 2. The SPIEN Fuse is not accessible in serial programming mo de. 3. See ”WDTCSR – Watchdog Time r Control Register” on page 63 for details. 4. The default value of BOOTSZ[1:0] results in maximum Boot Size. See ”Pin Name Mapping” on page 295 . BODLEVEL2 (4) 2 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL1 (4) 1 Brown-out Detector trigger level 1 (unprogrammed) BODLEVEL0 (4) 0 Brown-out Detector trigger level 1 (unprogrammed) T ab le 28-8. Fuse High Byte for A T mega328/328P High Fuse Byte Bit No Descriptio n Default V alue RSTDISBL (1) 7 External Reset Disable 1 (unprogrammed) DWEN 6 debugWIRE En able 1 (unprogramm ed) SPIEN (2) 5 Enable Serial Program and Data Downloading 0 (programmed, SPI programming e nabled) WDTON (3) 4 W atchdog T imer Always On 1 (unprogrammed) EESA VE 3 EEPROM memory is preserved through the Chip Erase 1 (unprogrammed), EEPROM not reserved BOOTSZ1 2 Select Boot Size (see Table 27-7 on page 284 , Table 27-10 on page 285 and Table 27-13 on page 286 for details) 0 (programmed) (4) BOOTSZ0 1 Select Boot Size (see Table 27-7 on page 284 , Table 27-10 on page 285 and Table 27-13 on page 286 for details) 0 (programmed) (4) BOOTRST 0 Select Reset V ector 1 (unprogrammed) T able 28-9. Fuse Low Byte Low Fuse Byte Bit No Descrip tion Default V alue CKDIV8 (4) 7 Divide clock by 8 0 (p rogrammed) CKOUT (3) 6 Clock output 1 (unprogrammed) SUT1 5 Select start-up time 1 (unprogrammed) (1) SUT0 4 Select start-up time 0 (programmed) (1) T ab le 28-7. Fuse High Byte for A Tmeg a48A/48P A/88A/88P A/168A/168P A (Co ntinued) High Fuse Byte Bit No Descriptio n Default V alue A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 293 Note: 1. The default value of SUT1...0 resu lt s in maxi mum st art-up time for the default clock sour ce. See Table 9-12 on page 43 for details. 2. The default setti ng of CKSEL3...0 results in internal RC Oscillator @ 8MHz. See Table 9-11 on page 43 for details. 3. The CKOUT Fuse a llows the system cl ock to be output on PORTB0. See ”Clock Output Buffer” on page 45 for details. 4. See ”System Clock Prescaler” on page 45 for details. The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are loc ked if Lock bit 1 (LB1) is programmed. Pr ogram the Fuse bits befor e progra mming the Lock b its. 28.2.1 Latching of Fuses The fuse values are latched when the device enters programming mode an d changes of the fuse values will have no effect until the part l eaves Programming mode. This does no t apply to the EESAVE Fuse which will take effect once it is programmed. Th e fuses are al so latched on Power-up in Norma l mode. 28.3 Signature Bytes All AVR micr ocontrolle rs have a three-by te signatu re code which identifies the device . This code can be rea d in both serial and parallel mo de, also when the device is locke d. The three bytes reside in a separa te address space. For the ATmega 48A/PA/ 88A/PA/168A/PA/328/P the sign ature bytes are gi ven in Tab le 28-10 . 28.4 Calibration Byte The ATmega48A/PA/88A/PA/168 A/PA/328/P has a byte calib ration value for the Internal RC Oscillator. This byte resides in the high byte of add ress 0x000 in the signature ad dress spa ce. During reset, t his byte is automatically written into the OSCCAL Register to ensure correct frequ ency of the calibrated RC Oscillator. CKSEL3 3 Select Clock source 0 (programmed) (2) CKSEL2 2 Select Clock source 0 (programmed) (2) CKSEL1 1 Select Clock source 1 (unprogrammed) (2) CKSEL0 0 Select Clock source 0 (programmed) (2) T able 28-9. Fuse Low Byte (Continued) Low Fuse Byte Bit No Descrip tion Default V alue T ab le 28-10. Device ID Part Signature Bytes Addr ess 0x000 0x0 01 0x002 A Tmega48A 0x1E 0x92 0x05 A Tmega48P A 0x1E 0x92 0x0A A Tmega88A 0x1E 0x93 0x0A A Tmega88P A 0x1E 0x93 0x0F A Tmega168A 0x1E 0x94 0x06 A Tmega168P A 0x1E 0x94 0x0B A Tmega328 0x1E 0x95 0 x14 A Tmega328P 0x1E 0x95 0x0F A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 294 28.5 Page Size 28.6 Parallel Programming Paramete rs, Pin Mapping, and Commands This section describes how to pa rallel program and verify Flash Program memory , EEPROM Data memory, Memory Lo ck bits, and Fuse bits in the ATmega 48A/ PA/88A/PA/168A/PA/328/P. Pulses are assumed to be at least 250 ns unless othe rwise noted. 28.6.1 Signal Names In this section, some pins of the ATmega48A/PA/88A/PA/16 8A/PA/328/P are referen ced by signal names describing their functionality during parallel programmin g, see Figure 28- 1 and Table 28- 13 . Pins not de scribed in the following table ar e refere nced by pin names. T abl e 28-1 1. No. of Wo rds in a Page and No. of Page s in the Flash Device Flash Size Page Size PCWORD No. of Pages PCP AGE PCMSB A Tmega48A 2K words (4Kbytes) 32 word s PC[4:0] 64 PC[10:5] 10 A Tmega48P A 2K words (4Kbytes) 32 word s PC[4:0] 64 PC[10:5] 10 A Tmega88A 4K words (8Kbytes) 32 word s PC[4:0] 128 PC[1 1:5] 11 A Tmega88P A 4K words (8Kbytes) 32 word s PC[4:0] 128 PC[1 1:5] 11 A Tmega168A 8K words (16Kbytes) 64 words PC[5:0] 128 PC[12: 6] 12 A Tmega168P A 8K words (16Kbytes) 64 words PC[5:0] 128 PC[12: 6] 12 A Tmega328 16K words (32Kbytes) 64 word s PC[5:0] 256 PC[13:6] 13 A Tmega328P 16K words (32Kbytes) 64 word s PC[5:0] 256 PC[13:6] 13 T ab le 28-12. No. of Words in a Page and No. of Pages in the EEPROM Device EEPROM Size Page Size PCWORD No. of Pages PCP AGE EEAMSB A Tmega48A 256bytes 4bytes EEA[1:0] 64 EEA[7:2] 7 A Tmega48P A 256bytes 4bytes EEA[1:0] 64 EEA[7:2] 7 A Tmega88A 512bytes 4bytes EEA[1:0] 128 EEA[8:2] 8 A Tmega88P A 512bytes 4bytes EEA[1:0] 128 EEA[8:2] 8 A Tmega168A 512b ytes 4bytes EEA[1:0] 128 EEA[8:2] 8 A Tmega168P A 512bytes 4bytes EEA[1:0] 128 EEA[8:2] 8 A Tmega328 1Kbytes 4bytes EEA[1:0] 256 EEA[9:2] 9 A Tmega328P 1Kbytes 4bytes EEA[1:0] 256 EEA[9:2] 9 A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 295 The XA1/XA0 pins determin e the action executed when the XTAL1 p in is given a positive pulse. The bit coding is shown in Table 28-1 5 . When pulsing WR or OE , the command loaded determines the action executed. The differe nt Commands are shown in Table 28- 16 . Figure 28 -1. Paral lel Programmi ng Note: V CC - 0.3V < A V CC < V CC + 0.3V , however , A V CC should always be within 4.5 - 5.5V T ab le 28-13. Pin Name Mapping Signal Name in Programming Mode Pin Name I/O Function RDY/BSY PD1 O 0: Device is busy progr amming , 1: Device is ready for new command OE PD2 I Output Enable (Active low) WR PD3 I Write Pulse (Active low) BS1 PD4 I Byte Select 1 (“0” selects Low byte, “1” selects High byte) XA0 PD5 I XT AL Action Bit 0 XA1 PD6 I XT AL Action Bit 1 PA G E L PD7 I Program memory and EEPROM Data Page Load BS2 PC2 I Byte Select 2 (“0” selects Low byte, “1” selects 2’nd H igh byte) DA T A {PC[1:0]: PB[5:0]} I/ O Bi-directional Data bus (Output when OE is low) T ab le 28-14. Pin V alues Used to Ente r Programming Mode Pin Symbol Va l u e PA G E L Prog_enab le[3] 0 XA1 Prog_enable[2] 0 XA0 Prog_enable[1] 0 BS1 Prog_enable[0] 0 VCC GND XT AL1 PD1 PD2 PD3 PD4 PD5 PD6 PC[1:0]:PB[5:0] DA T A RESET PD7 +12 V BS1 XA0 XA1 OE RDY/BSY PAGEL PC2 WR BS2 AVCC +4.5 - 5.5V +4.5 - 5.5V A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 296 28.7 Parallel Programming 28.7.1 Enter Programming Mode The following algorithm puts th e device in Parallel (High- voltage) Programmin g mode: 1. Set Prog_enable pins listed in Ta ble 28-14 on pag e 296 to “0000”, RESET pin to 0V and V CC to 0V . 2. Apply 4.5 - 5.5V between V CC and GND. Ensure that V CC reac hes at least 1.8V withi n the next 20 µs. 1. W ait 20 - 60 µs, and apply 1 1.5 - 12.5V to RESET . 2. Keep the Prog_en able pins u nchanged for a t least 10µs af ter the High-volta ge has be en applied to ensure the Prog_e nable Sign ature has be en latched. 3. W ait at least 300 µs befo re giving any p arallel programming commands. 4. Exit Programming m ode by power the devi ce down or by bringing RESET pin to 0V . If the rise time of the V CC is unable to fulfill the requi rements listed above, the follo wing alternative algorithm can be used. 1. Set Prog_enable pins listed in Ta ble 28-14 on pag e 296 to “0000”, RESET pin to 0V and V CC to 0V . 2. Apply 4.5 - 5.5V between V CC and GND. 3. Monito r V CC , and as soon as V CC reaches 0.9 - 1.1V , apply 1 1.5 - 12.5V to RESET . 4. Keep the Prog_en able pins u nchanged for a t least 10µs af ter the High-volta ge has be en applied to ensure the Prog_e nable Sign ature has be en latched. 5. W ait until V CC actually reaches 4.5 -5.5V before giving any p arallel progr amming commands. 6. Exit Programming m ode by power the devi ce down or by bringing RESET pin to 0V . T ab le 28-15. XA1 and XA0 Coding XA1 XA0 Action when XT AL1 is Pulsed 0 0 Load Flash or EEPROM Add ress (High or low a ddress byte determined by BS1). 0 1 Load Data (High or Low dat a byte for Flash determin ed by BS1). 1 0 Load Command 1 1 No Action, Idle T ab le 28-16. Comman d Byte Bit Coding Command Byte Command Executed 1000 0000 Chip Erase 0100 0000 Wr i te Fu s e b i ts 0010 0000 Write Lock bits 0001 0000 Write Flash 0001 0001 Write EEPROM 0000 1000 R ead Signature Bytes and Cali bration byte 0000 0100 R ead Fuse and Lock bits 0000 0010 R ead Flash 0000 001 1 R ead EEPROM A Tmega48A/P A/88A/P A/168A/P A/328/P  2018 Microchip Technology Inc. Da ta Sheet Complete DS40002 061A-page 303 28.7.14 R eading the Calibr ation Byte The algori thm for re ading the Calibrati on byte is as follows (refer to ”Programming th e Flash” on page 297 for details on Command and Address loading) : 1. A: Load Command “000 0 1000”. 2. B: Load Address Low Byte, 0x00. 3. Set OE to “0”, and BS1 to “1”. The Calib ration byte can now be read at DA T A. 4. Set OE to “1”. 28.7.15 Parallel Prog ramming Charact eristics For characteristics of th e Parallel Programming, see ”Parallel Program ming Characteristics” on pag e 320 . 28.8 Serial Downloading Both the Flash and EEPROM memo ry arrays can be progra mmed using the serial SPI bus while RESET is pulled to GND. The serial interf ace consists of pins SCK, MOSI (input) an d MI SO (outpu t). After RESET is set low, the Progr amming Enable instructio n needs to be ex ecuted first before p rogra m/er ase operat ions can be execute d. NOTE , in Table 28-17 on pag e 304 , the pin mapping for SPI programming is listed. Not all parts use the SPI pins dedicated for the internal SPI interface. Figure 28-7. Ser ial Programming a nd Verify (1) Notes: 1. If the device is clocked by the internal Oscillator , it is no need to connect a clock source to the XT AL1 pin. 2. V CC - 0.3V < AV CC < V CC + 0.3V , however , AV CC should always be within 1.8 - 5.5V When prog ramming th e EEPROM, an auto-erase cycle is bu ilt into th e self-timed programm ing operation (i n the Serial mode ONLY) an d there is n o need to first execut e the Chip Er ase instru ction. The Chip Erase op eration turns the content of ever y memory location in both the Pro gram and EEPROM arrays into 0xFF. Dependin g on CKSEL Fuses, a valid clock mu st be pres ent. The minimum low and high periods for the ser ial clock (SCK) input ar e defined as follows: Low:> 2 CPU clock cycles for f ck < 12MHz, 3 CPU clock cycles for f ck  12M Hz High:> 2 CPU clock cyc les for f ck < 12MHz, 3 CPU clock cycles for f ck  12M Hz VCC GND XT AL1 S CK MI S O MO S I RE S ET +1.8 - 5.5V AVCC +1.8 - 5.5V (2) [Document text truncated for crawler view.]